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 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151
|
/******************************************************************************
*
* Project: Mapinfo Image Warper
* Purpose: Implementation of one or more GDALTrasformerFunc types, including
* the GenImgProj (general image reprojector) transformer.
* Author: Frank Warmerdam, warmerdam@pobox.com
*
******************************************************************************
* Copyright (c) 2002, i3 - information integration and imaging
* Fort Collin, CO
* Copyright (c) 2008-2013, Even Rouault <even dot rouault at spatialys.com>
* Copyright (c) 2021, CLS
*
* SPDX-License-Identifier: MIT
****************************************************************************/
#include "cpl_port.h"
#include "gdal_alg.h"
#include "gdal_alg_priv.h"
#include <climits>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <limits>
#include <utility>
#include "cpl_conv.h"
#include "cpl_error.h"
#include "cpl_list.h"
#include "cpl_minixml.h"
#include "cpl_multiproc.h"
#include "cpl_string.h"
#include "cpl_vsi.h"
#include "gdal.h"
#include "gdal_priv.h"
#include "ogr_core.h"
#include "ogr_spatialref.h"
#include "ogr_srs_api.h"
CPL_C_START
void *GDALDeserializeGCPTransformer(CPLXMLNode *psTree);
void *GDALDeserializeTPSTransformer(CPLXMLNode *psTree);
void *GDALDeserializeGeoLocTransformer(CPLXMLNode *psTree);
void *GDALDeserializeRPCTransformer(CPLXMLNode *psTree);
void *GDALDeserializeHomographyTransformer(CPLXMLNode *psTree);
CPL_C_END
static CPLXMLNode *GDALSerializeReprojectionTransformer(void *pTransformArg);
static void *GDALDeserializeReprojectionTransformer(CPLXMLNode *psTree);
static CPLXMLNode *GDALSerializeGenImgProjTransformer(void *pTransformArg);
static void *GDALDeserializeGenImgProjTransformer(CPLXMLNode *psTree);
static void *GDALCreateApproxTransformer2(GDALTransformerFunc pfnRawTransformer,
void *pRawTransformerArg,
double dfMaxErrorForward,
double dfMaxErrorReverse);
/************************************************************************/
/* GDALIsTransformer() */
/************************************************************************/
bool GDALIsTransformer(void *hTransformerArg, const char *pszClassName)
{
if (!hTransformerArg)
return false;
// All transformers should have a GDALTransformerInfo member as their first members
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(hTransformerArg);
return memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) == 0 &&
strcmp(psInfo->pszClassName, pszClassName) == 0;
}
/************************************************************************/
/* GDALTransformFunc */
/* */
/* Documentation for GDALTransformFunc typedef. */
/************************************************************************/
/*!
\typedef typedef int (*GDALTransformerFunc)( void *pTransformerArg, int
bDstToSrc, int nPointCount, double *x, double *y, double *z, int *panSuccess );
Generic signature for spatial point transformers.
This function signature is used for a variety of functions that accept
passed in functions used to transform point locations between two coordinate
spaces.
The GDALCreateGenImgProjTransformer(), GDALCreateReprojectionTransformerEx(),
GDALCreateGCPTransformer() and GDALCreateApproxTransformer() functions can
be used to prepare argument data for some built-in transformers. As well,
applications can implement their own transformers to the following signature.
\code
typedef int
(*GDALTransformerFunc)( void *pTransformerArg,
int bDstToSrc, int nPointCount,
double *x, double *y, double *z, int *panSuccess );
\endcode
@param pTransformerArg application supplied callback data used by the
transformer.
@param bDstToSrc if TRUE the transformation will be from the destination
coordinate space to the source coordinate system, otherwise the transformation
will be from the source coordinate system to the destination coordinate system.
@param nPointCount number of points in the x, y and z arrays.
@param[in,out] x input X coordinates. Results returned in same array.
@param[in,out] y input Y coordinates. Results returned in same array.
@param[in,out] z input Z coordinates. Results returned in same array.
@param[out] panSuccess array of ints in which success (TRUE) or failure (FALSE)
flags are returned for the translation of each point. Must not be NULL.
@return TRUE if all points have been successfully transformed (changed in 3.11,
previously was TRUE if some points have been successfully transformed)
*/
/************************************************************************/
/* GDALSuggestedWarpOutput() */
/************************************************************************/
/**
* Suggest output file size.
*
* This function is used to suggest the size, and georeferenced extents
* appropriate given the indicated transformation and input file. It walks
* the edges of the input file (approximately 20 sample points along each
* edge) transforming into output coordinates in order to get an extents box.
*
* Then a resolution is computed with the intent that the length of the
* distance from the top left corner of the output imagery to the bottom right
* corner would represent the same number of pixels as in the source image.
* Note that if the image is somewhat rotated the diagonal taken isn't of the
* whole output bounding rectangle, but instead of the locations where the
* top/left and bottom/right corners transform. The output pixel size is
* always square. This is intended to approximately preserve the resolution
* of the input data in the output file.
*
* The values returned in padfGeoTransformOut, pnPixels and pnLines are
* the suggested number of pixels and lines for the output file, and the
* geotransform relating those pixels to the output georeferenced coordinates.
*
* The trickiest part of using the function is ensuring that the
* transformer created is from source file pixel/line coordinates to
* output file georeferenced coordinates. This can be accomplished with
* GDALCreateGenImgProjTransformer() by passing a NULL for the hDstDS.
*
* @param hSrcDS the input image (it is assumed the whole input image is
* being transformed).
* @param pfnTransformer the transformer function.
* @param pTransformArg the callback data for the transformer function.
* @param padfGeoTransformOut the array of six doubles in which the suggested
* geotransform is returned.
* @param pnPixels int in which the suggest pixel width of output is returned.
* @param pnLines int in which the suggest pixel height of output is returned.
*
* @return CE_None if successful or CE_Failure otherwise.
*/
CPLErr CPL_STDCALL GDALSuggestedWarpOutput(GDALDatasetH hSrcDS,
GDALTransformerFunc pfnTransformer,
void *pTransformArg,
double *padfGeoTransformOut,
int *pnPixels, int *pnLines)
{
VALIDATE_POINTER1(hSrcDS, "GDALSuggestedWarpOutput", CE_Failure);
double adfExtent[4] = {};
return GDALSuggestedWarpOutput2(hSrcDS, pfnTransformer, pTransformArg,
padfGeoTransformOut, pnPixels, pnLines,
adfExtent, 0);
}
static bool GDALSuggestedWarpOutput2_MustAdjustForRightBorder(
GDALTransformerFunc pfnTransformer, void *pTransformArg, double *padfExtent,
int /* nPixels*/, int nLines, double dfPixelSizeX, double dfPixelSizeY)
{
double adfX[21] = {};
double adfY[21] = {};
const double dfMaxXOut = padfExtent[2];
const double dfMaxYOut = padfExtent[3];
// Take 20 steps.
int nSamplePoints = 0;
for (double dfRatio = 0.0; dfRatio <= 1.01; dfRatio += 0.05)
{
// Ensure we end exactly at the end.
if (dfRatio > 0.99)
dfRatio = 1.0;
// Along right.
adfX[nSamplePoints] = dfMaxXOut;
adfY[nSamplePoints] = dfMaxYOut - dfPixelSizeY * dfRatio * nLines;
nSamplePoints++;
}
double adfZ[21] = {};
int abSuccess[21] = {};
pfnTransformer(pTransformArg, TRUE, nSamplePoints, adfX, adfY, adfZ,
abSuccess);
int abSuccess2[21] = {};
pfnTransformer(pTransformArg, FALSE, nSamplePoints, adfX, adfY, adfZ,
abSuccess2);
nSamplePoints = 0;
int nBadCount = 0;
for (double dfRatio = 0.0; dfRatio <= 1.01; dfRatio += 0.05)
{
const double expected_x = dfMaxXOut;
const double expected_y = dfMaxYOut - dfPixelSizeY * dfRatio * nLines;
if (!abSuccess[nSamplePoints] || !abSuccess2[nSamplePoints] ||
fabs(adfX[nSamplePoints] - expected_x) > dfPixelSizeX ||
fabs(adfY[nSamplePoints] - expected_y) > dfPixelSizeY)
{
nBadCount++;
}
nSamplePoints++;
}
return nBadCount == nSamplePoints;
}
static bool GDALSuggestedWarpOutput2_MustAdjustForBottomBorder(
GDALTransformerFunc pfnTransformer, void *pTransformArg, double *padfExtent,
int nPixels, int /* nLines */, double dfPixelSizeX, double dfPixelSizeY)
{
double adfX[21] = {};
double adfY[21] = {};
const double dfMinXOut = padfExtent[0];
const double dfMinYOut = padfExtent[1];
// Take 20 steps.
int nSamplePoints = 0;
for (double dfRatio = 0.0; dfRatio <= 1.01; dfRatio += 0.05)
{
// Ensure we end exactly at the end.
if (dfRatio > 0.99)
dfRatio = 1.0;
// Along right.
adfX[nSamplePoints] = dfMinXOut + dfPixelSizeX * dfRatio * nPixels;
adfY[nSamplePoints] = dfMinYOut;
nSamplePoints++;
}
double adfZ[21] = {};
int abSuccess[21] = {};
pfnTransformer(pTransformArg, TRUE, nSamplePoints, adfX, adfY, adfZ,
abSuccess);
int abSuccess2[21] = {};
pfnTransformer(pTransformArg, FALSE, nSamplePoints, adfX, adfY, adfZ,
abSuccess2);
nSamplePoints = 0;
int nBadCount = 0;
for (double dfRatio = 0.0; dfRatio <= 1.01; dfRatio += 0.05)
{
const double expected_x = dfMinXOut + dfPixelSizeX * dfRatio * nPixels;
const double expected_y = dfMinYOut;
if (!abSuccess[nSamplePoints] || !abSuccess2[nSamplePoints] ||
fabs(adfX[nSamplePoints] - expected_x) > dfPixelSizeX ||
fabs(adfY[nSamplePoints] - expected_y) > dfPixelSizeY)
{
nBadCount++;
}
nSamplePoints++;
}
return nBadCount == nSamplePoints;
}
/************************************************************************/
/* GDALSuggestedWarpOutput2() */
/************************************************************************/
/**
* Suggest output file size.
*
* This function is used to suggest the size, and georeferenced extents
* appropriate given the indicated transformation and input file. It walks
* the edges of the input file (approximately 20 sample points along each
* edge) transforming into output coordinates in order to get an extents box.
*
* Then a resolution is computed with the intent that the length of the
* distance from the top left corner of the output imagery to the bottom right
* corner would represent the same number of pixels as in the source image.
* Note that if the image is somewhat rotated the diagonal taken isn't of the
* whole output bounding rectangle, but instead of the locations where the
* top/left and bottom/right corners transform. The output pixel size is
* always square. This is intended to approximately preserve the resolution
* of the input data in the output file.
*
* The values returned in padfGeoTransformOut, pnPixels and pnLines are
* the suggested number of pixels and lines for the output file, and the
* geotransform relating those pixels to the output georeferenced coordinates.
*
* The trickiest part of using the function is ensuring that the
* transformer created is from source file pixel/line coordinates to
* output file georeferenced coordinates. This can be accomplished with
* GDALCreateGenImgProjTransformer() by passing a NULL for the hDstDS.
*
* @param hSrcDS the input image (it is assumed the whole input image is
* being transformed).
* @param pfnTransformer the transformer function.
* @param pTransformArg the callback data for the transformer function.
* @param padfGeoTransformOut the array of six doubles in which the suggested
* geotransform is returned.
* @param pnPixels int in which the suggest pixel width of output is returned.
* @param pnLines int in which the suggest pixel height of output is returned.
* @param padfExtent Four entry array to return extents as (xmin, ymin, xmax,
* ymax).
* @param nOptions Options flags. Zero or GDAL_SWO_ROUND_UP_SIZE to ask *pnPixels
* and *pnLines to be rounded up instead of being rounded to the closes integer, or
* GDAL_SWO_FORCE_SQUARE_PIXEL to indicate that the generated pixel size is a square.
*
* @return CE_None if successful or CE_Failure otherwise.
*/
CPLErr CPL_STDCALL GDALSuggestedWarpOutput2(GDALDatasetH hSrcDS,
GDALTransformerFunc pfnTransformer,
void *pTransformArg,
double *padfGeoTransformOut,
int *pnPixels, int *pnLines,
double *padfExtent, int nOptions)
{
VALIDATE_POINTER1(hSrcDS, "GDALSuggestedWarpOutput2", CE_Failure);
const bool bIsGDALGenImgProjTransform{
pTransformArg &&
GDALIsTransformer(pTransformArg, GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME)};
/* -------------------------------------------------------------------- */
/* Setup sample points all around the edge of the input raster. */
/* -------------------------------------------------------------------- */
if (bIsGDALGenImgProjTransform)
{
// In case CHECK_WITH_INVERT_PROJ has been modified.
GDALRefreshGenImgProjTransformer(pTransformArg);
}
else if (GDALIsTransformer(pTransformArg,
GDAL_APPROX_TRANSFORMER_CLASS_NAME))
{
// In case CHECK_WITH_INVERT_PROJ has been modified.
GDALRefreshApproxTransformer(pTransformArg);
}
const int nInXSize = GDALGetRasterXSize(hSrcDS);
const int nInYSize = GDALGetRasterYSize(hSrcDS);
/* ------------------------------------------------------------- */
/* Special case for warping on the same (or null) CRS. */
/* ------------------------------------------------------------- */
if ((!nOptions || (nOptions & GDAL_SWO_FORCE_SQUARE_PIXEL) == 0) &&
pTransformArg && bIsGDALGenImgProjTransform)
{
const GDALGenImgProjTransformInfo *psInfo =
static_cast<const GDALGenImgProjTransformInfo *>(pTransformArg);
if (!psInfo->sSrcParams.pTransformer &&
!psInfo->bHasCustomTransformationPipeline &&
!psInfo->sDstParams.pTransformer &&
psInfo->sSrcParams.adfGeoTransform[2] == 0 &&
psInfo->sSrcParams.adfGeoTransform[4] == 0 &&
psInfo->sDstParams.adfGeoTransform[0] == 0 &&
psInfo->sDstParams.adfGeoTransform[1] == 1 &&
psInfo->sDstParams.adfGeoTransform[2] == 0 &&
psInfo->sDstParams.adfGeoTransform[3] == 0 &&
psInfo->sDstParams.adfGeoTransform[4] == 0 &&
psInfo->sDstParams.adfGeoTransform[5] == 1)
{
const OGRSpatialReference *poSourceCRS = nullptr;
const OGRSpatialReference *poTargetCRS = nullptr;
if (psInfo->pReprojectArg)
{
const GDALReprojectionTransformInfo *psRTI =
static_cast<const GDALReprojectionTransformInfo *>(
psInfo->pReprojectArg);
poSourceCRS = psRTI->poForwardTransform->GetSourceCS();
poTargetCRS = psRTI->poForwardTransform->GetTargetCS();
}
if ((!poSourceCRS && !poTargetCRS) ||
(poSourceCRS && poTargetCRS &&
poSourceCRS->IsSame(poTargetCRS)))
{
const bool bNorthUp{psInfo->sSrcParams.adfGeoTransform[5] <
0.0};
memcpy(padfGeoTransformOut, psInfo->sSrcParams.adfGeoTransform,
sizeof(double) * 6);
if (!bNorthUp)
{
padfGeoTransformOut[3] = padfGeoTransformOut[3] +
nInYSize * padfGeoTransformOut[5];
padfGeoTransformOut[5] = -padfGeoTransformOut[5];
}
*pnPixels = nInXSize;
*pnLines = nInYSize;
// Calculate extent from hSrcDS
if (padfExtent)
{
padfExtent[0] = psInfo->sSrcParams.adfGeoTransform[0];
padfExtent[1] =
psInfo->sSrcParams.adfGeoTransform[3] +
nInYSize * psInfo->sSrcParams.adfGeoTransform[5];
padfExtent[2] =
psInfo->sSrcParams.adfGeoTransform[0] +
nInXSize * psInfo->sSrcParams.adfGeoTransform[1];
padfExtent[3] = psInfo->sSrcParams.adfGeoTransform[3];
if (!bNorthUp)
{
std::swap(padfExtent[1], padfExtent[3]);
}
}
return CE_None;
}
}
}
const int N_PIXELSTEP = 50;
int nSteps = static_cast<int>(
static_cast<double>(std::min(nInYSize, nInXSize)) / N_PIXELSTEP + 0.5);
if (nSteps < 20)
nSteps = 20;
else if (nSteps > 100)
nSteps = 100;
// TODO(rouault): How is this goto retry supposed to work? Added in r20537.
// Does redoing the same malloc multiple times work? If it is needed, can
// it be converted to a tigher while loop around the MALLOC3s and free? Is
// the point to try with the full requested steps. Then, if there is not
// enough memory, back off and try with just 20 steps?
retry:
int nStepsPlusOne = nSteps + 1;
int nSampleMax = nStepsPlusOne * nStepsPlusOne;
double dfStep = 1.0 / nSteps;
double *padfY = nullptr;
double *padfZ = nullptr;
double *padfYRevert = nullptr;
double *padfZRevert = nullptr;
int *pabSuccess = static_cast<int *>(
VSI_MALLOC3_VERBOSE(sizeof(int), nStepsPlusOne, nStepsPlusOne));
double *padfX = static_cast<double *>(
VSI_MALLOC3_VERBOSE(sizeof(double) * 3, nStepsPlusOne, nStepsPlusOne));
double *padfXRevert = static_cast<double *>(
VSI_MALLOC3_VERBOSE(sizeof(double) * 3, nStepsPlusOne, nStepsPlusOne));
if (pabSuccess == nullptr || padfX == nullptr || padfXRevert == nullptr)
{
CPLFree(padfX);
CPLFree(padfXRevert);
CPLFree(pabSuccess);
if (nSteps > 20)
{
nSteps = 20;
goto retry;
}
return CE_Failure;
}
padfY = padfX + nSampleMax;
padfZ = padfX + nSampleMax * 2;
padfYRevert = padfXRevert + nSampleMax;
padfZRevert = padfXRevert + nSampleMax * 2;
// Take N_STEPS steps.
for (int iStep = 0; iStep <= nSteps; iStep++)
{
double dfRatio = (iStep == nSteps) ? 1.0 : iStep * dfStep;
int iStep2 = iStep;
// Along top.
padfX[iStep2] = dfRatio * nInXSize;
padfY[iStep2] = 0.0;
padfZ[iStep2] = 0.0;
// Along bottom.
iStep2 += nStepsPlusOne;
padfX[iStep2] = dfRatio * nInXSize;
padfY[iStep2] = nInYSize;
padfZ[iStep2] = 0.0;
// Along left.
iStep2 += nStepsPlusOne;
padfX[iStep2] = 0.0;
padfY[iStep2] = dfRatio * nInYSize;
padfZ[iStep2] = 0.0;
// Along right.
iStep2 += nStepsPlusOne;
padfX[iStep2] = nInXSize;
padfY[iStep2] = dfRatio * nInYSize;
padfZ[iStep2] = 0.0;
}
int nSamplePoints = 4 * nStepsPlusOne;
memset(pabSuccess, 1, sizeof(int) * nSampleMax);
/* -------------------------------------------------------------------- */
/* Transform them to the output coordinate system. */
/* -------------------------------------------------------------------- */
{
CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
pfnTransformer(pTransformArg, FALSE, nSamplePoints, padfX, padfY, padfZ,
pabSuccess);
}
constexpr int SIGN_FINAL_UNINIT = -2;
constexpr int SIGN_FINAL_INVALID = 0;
int iSignDiscontinuity = SIGN_FINAL_UNINIT;
int nFailedCount = 0;
const int iSignArray[2] = {-1, 1};
for (int i = 0; i < nSamplePoints; i++)
{
if (pabSuccess[i])
{
// Fix for https://trac.osgeo.org/gdal/ticket/7243
// where echo "-2050000.000 2050000.000" |
// gdaltransform -s_srs EPSG:3411 -t_srs EPSG:4326
// gives "-180 63.691332898492"
// but we would rather like 180
if (iSignDiscontinuity == 1 || iSignDiscontinuity == -1)
{
if (!((iSignDiscontinuity * padfX[i] > 0 &&
iSignDiscontinuity * padfX[i] <= 180.0) ||
(fabs(padfX[i] - iSignDiscontinuity * -180.0) < 1e-8)))
{
iSignDiscontinuity = SIGN_FINAL_INVALID;
}
}
else if (iSignDiscontinuity == SIGN_FINAL_UNINIT)
{
for (const auto &iSign : iSignArray)
{
if ((iSign * padfX[i] > 0 && iSign * padfX[i] <= 180.0) ||
(fabs(padfX[i] - iSign * -180.0) < 1e-8))
{
iSignDiscontinuity = iSign;
break;
}
}
if (iSignDiscontinuity == SIGN_FINAL_UNINIT)
{
iSignDiscontinuity = SIGN_FINAL_INVALID;
}
}
}
else
{
nFailedCount++;
}
}
if (iSignDiscontinuity == 1 || iSignDiscontinuity == -1)
{
for (int i = 0; i < nSamplePoints; i++)
{
if (pabSuccess[i])
{
if (fabs(padfX[i] - iSignDiscontinuity * -180.0) < 1e-8)
{
double axTemp[2] = {iSignDiscontinuity * -180.0,
iSignDiscontinuity * 180.0};
double ayTemp[2] = {padfY[i], padfY[i]};
double azTemp[2] = {padfZ[i], padfZ[i]};
int abSuccess[2] = {FALSE, FALSE};
CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
if (pfnTransformer(pTransformArg, TRUE, 2, axTemp, ayTemp,
azTemp, abSuccess) &&
fabs(axTemp[0] - axTemp[1]) < 1e-8 &&
fabs(ayTemp[0] - ayTemp[1]) < 1e-8)
{
padfX[i] = iSignDiscontinuity * 180.0;
}
}
}
}
}
/* -------------------------------------------------------------------- */
/* Check if the computed target coordinates are revertable. */
/* If not, try the detailed grid sampling. */
/* -------------------------------------------------------------------- */
if (nFailedCount)
{
CPLDebug("WARP", "At least one point failed after direct transform");
}
else
{
memcpy(padfXRevert, padfX, nSamplePoints * sizeof(double));
memcpy(padfYRevert, padfY, nSamplePoints * sizeof(double));
memcpy(padfZRevert, padfZ, nSamplePoints * sizeof(double));
{
CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
pfnTransformer(pTransformArg, TRUE, nSamplePoints, padfXRevert,
padfYRevert, padfZRevert, pabSuccess);
}
for (int i = 0; nFailedCount == 0 && i < nSamplePoints; i++)
{
if (!pabSuccess[i])
{
nFailedCount++;
break;
}
double dfRatio = (i % nStepsPlusOne) * dfStep;
if (dfRatio > 0.99)
dfRatio = 1.0;
double dfExpectedX = 0.0;
double dfExpectedY = 0.0;
if (i < nStepsPlusOne)
{
dfExpectedX = dfRatio * nInXSize;
}
else if (i < 2 * nStepsPlusOne)
{
dfExpectedX = dfRatio * nInXSize;
dfExpectedY = nInYSize;
}
else if (i < 3 * nStepsPlusOne)
{
dfExpectedY = dfRatio * nInYSize;
}
else
{
dfExpectedX = nInXSize;
dfExpectedY = dfRatio * nInYSize;
}
if (fabs(padfXRevert[i] - dfExpectedX) >
nInXSize / static_cast<double>(nSteps) ||
fabs(padfYRevert[i] - dfExpectedY) >
nInYSize / static_cast<double>(nSteps))
nFailedCount++;
}
if (nFailedCount != 0)
CPLDebug("WARP",
"At least one point failed after revert transform");
}
/* -------------------------------------------------------------------- */
/* If any of the edge points failed to transform, we need to */
/* build a fairly detailed internal grid of points instead to */
/* help identify the area that is transformable. */
/* -------------------------------------------------------------------- */
if (nFailedCount)
{
nSamplePoints = 0;
// Take N_STEPS steps.
for (int iStep = 0; iStep <= nSteps; iStep++)
{
double dfRatio = (iStep == nSteps) ? 1.0 : iStep * dfStep;
for (int iStep2 = 0; iStep2 <= nSteps; iStep2++)
{
const double dfRatio2 =
iStep2 == nSteps ? 1.0 : iStep2 * dfStep;
// From top to bottom, from left to right.
padfX[nSamplePoints] = dfRatio2 * nInXSize;
padfY[nSamplePoints] = dfRatio * nInYSize;
padfZ[nSamplePoints] = 0.0;
nSamplePoints++;
}
}
CPLAssert(nSamplePoints == nSampleMax);
{
CPLTurnFailureIntoWarningBackuper oErrorsToWarnings{};
pfnTransformer(pTransformArg, FALSE, nSamplePoints, padfX, padfY,
padfZ, pabSuccess);
}
}
/* -------------------------------------------------------------------- */
/* Collect the bounds, ignoring any failed points. */
/* -------------------------------------------------------------------- */
double dfMinXOut = 0.0;
double dfMinYOut = 0.0;
double dfMaxXOut = 0.0;
double dfMaxYOut = 0.0;
bool bGotInitialPoint = false;
nFailedCount = 0;
for (int i = 0; i < nSamplePoints; i++)
{
int x_i = 0;
int y_i = 0;
if (nSamplePoints == nSampleMax)
{
x_i = i % nStepsPlusOne;
y_i = i / nStepsPlusOne;
}
else
{
if (i < 2 * nStepsPlusOne)
{
x_i = i % nStepsPlusOne;
y_i = (i < nStepsPlusOne) ? 0 : nSteps;
}
}
if (x_i > 0 && (pabSuccess[i - 1] || pabSuccess[i]))
{
double x_out_before = padfX[i - 1];
double x_out_after = padfX[i];
int nIter = 0;
double x_in_before =
static_cast<double>(x_i - 1) * nInXSize / nSteps;
double x_in_after = static_cast<double>(x_i) * nInXSize / nSteps;
int invalid_before = !(pabSuccess[i - 1]);
int invalid_after = !(pabSuccess[i]);
// Detect discontinuity in target coordinates when the target x
// coordinates change sign. This may be a false positive when the
// target tx is around 0 Dichotomic search to reduce the interval
// to near the discontinuity and get a better out extent.
while ((invalid_before || invalid_after ||
x_out_before * x_out_after < 0.0) &&
nIter < 16)
{
double x = (x_in_before + x_in_after) / 2.0;
double y = static_cast<double>(y_i) * nInYSize / nSteps;
double z = 0.0;
int bSuccess = TRUE;
if (pfnTransformer(pTransformArg, FALSE, 1, &x, &y, &z,
&bSuccess) &&
bSuccess)
{
if (bGotInitialPoint)
{
dfMinXOut = std::min(dfMinXOut, x);
dfMinYOut = std::min(dfMinYOut, y);
dfMaxXOut = std::max(dfMaxXOut, x);
dfMaxYOut = std::max(dfMaxYOut, y);
}
else
{
bGotInitialPoint = true;
dfMinXOut = x;
dfMaxXOut = x;
dfMinYOut = y;
dfMaxYOut = y;
}
if (invalid_before || x_out_before * x < 0)
{
invalid_after = FALSE;
x_in_after = (x_in_before + x_in_after) / 2.0;
x_out_after = x;
}
else
{
invalid_before = FALSE;
x_out_before = x;
x_in_before = (x_in_before + x_in_after) / 2.0;
}
}
else
{
if (invalid_before)
{
x_in_before = (x_in_before + x_in_after) / 2.0;
}
else if (invalid_after)
{
x_in_after = (x_in_before + x_in_after) / 2.0;
}
else
{
break;
}
}
nIter++;
}
}
if (!pabSuccess[i])
{
nFailedCount++;
continue;
}
if (bGotInitialPoint)
{
dfMinXOut = std::min(dfMinXOut, padfX[i]);
dfMinYOut = std::min(dfMinYOut, padfY[i]);
dfMaxXOut = std::max(dfMaxXOut, padfX[i]);
dfMaxYOut = std::max(dfMaxYOut, padfY[i]);
}
else
{
bGotInitialPoint = true;
dfMinXOut = padfX[i];
dfMaxXOut = padfX[i];
dfMinYOut = padfY[i];
dfMaxYOut = padfY[i];
}
}
if (nFailedCount > nSamplePoints - 10)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Too many points (%d out of %d) failed to transform, "
"unable to compute output bounds.",
nFailedCount, nSamplePoints);
CPLFree(padfX);
CPLFree(padfXRevert);
CPLFree(pabSuccess);
return CE_Failure;
}
if (nFailedCount)
CPLDebug("GDAL",
"GDALSuggestedWarpOutput(): %d out of %d points failed to "
"transform.",
nFailedCount, nSamplePoints);
bool bIsGeographicCoordsDeg = false;
if (bIsGDALGenImgProjTransform)
{
const GDALGenImgProjTransformInfo *pGIPTI =
static_cast<const GDALGenImgProjTransformInfo *>(pTransformArg);
if (pGIPTI->sSrcParams.pTransformer == GDALGeoLocTransform &&
pGIPTI->sDstParams.pTransformer == nullptr &&
pGIPTI->sDstParams.adfGeoTransform[0] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[1] == 1 &&
pGIPTI->sDstParams.adfGeoTransform[2] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[3] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[4] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[5] == 1)
{
/* --------------------------------------------------------------------
*/
/* Special case for geolocation array, to quickly find the
* bounds. */
/* --------------------------------------------------------------------
*/
const GDALGeoLocTransformInfo *pGLTI =
static_cast<const GDALGeoLocTransformInfo *>(
pGIPTI->sSrcParams.pTransformArg);
if (pGIPTI->pReproject == nullptr)
{
const char *pszGLSRS =
CSLFetchNameValue(pGLTI->papszGeolocationInfo, "SRS");
if (pszGLSRS == nullptr)
{
bIsGeographicCoordsDeg = true;
}
else
{
OGRSpatialReference oSRS;
if (oSRS.SetFromUserInput(pszGLSRS) == OGRERR_NONE &&
oSRS.IsGeographic() &&
std::fabs(oSRS.GetAngularUnits() -
CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-9)
{
bIsGeographicCoordsDeg = true;
}
}
}
for (const auto &xy :
{std::pair<double, double>(pGLTI->dfMinX, pGLTI->dfYAtMinX),
std::pair<double, double>(pGLTI->dfXAtMinY, pGLTI->dfMinY),
std::pair<double, double>(pGLTI->dfMaxX, pGLTI->dfYAtMaxX),
std::pair<double, double>(pGLTI->dfXAtMaxY, pGLTI->dfMaxY)})
{
double x = xy.first;
double y = xy.second;
if (pGLTI->bSwapXY)
{
std::swap(x, y);
}
double xOut = std::numeric_limits<double>::quiet_NaN();
double yOut = std::numeric_limits<double>::quiet_NaN();
if (pGIPTI->pReproject == nullptr ||
pGIPTI->pReproject(pGIPTI->pReprojectArg, false, 1, &x, &y,
nullptr, nullptr))
{
xOut = x;
yOut = y;
}
dfMinXOut = std::min(dfMinXOut, xOut);
dfMinYOut = std::min(dfMinYOut, yOut);
dfMaxXOut = std::max(dfMaxXOut, xOut);
dfMaxYOut = std::max(dfMaxYOut, yOut);
}
}
else if (pGIPTI->sSrcParams.pTransformer == nullptr &&
pGIPTI->sDstParams.pTransformer == nullptr &&
pGIPTI->pReproject == GDALReprojectionTransform &&
pGIPTI->sDstParams.adfGeoTransform[0] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[1] == 1 &&
pGIPTI->sDstParams.adfGeoTransform[2] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[3] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[4] == 0 &&
pGIPTI->sDstParams.adfGeoTransform[5] == 1)
{
/* ------------------------------------------------------------- */
/* Special case for warping using source geotransform and */
/* reprojection to deal with the poles. */
/* ------------------------------------------------------------- */
const GDALReprojectionTransformInfo *psRTI =
static_cast<const GDALReprojectionTransformInfo *>(
pGIPTI->pReprojectArg);
const OGRSpatialReference *poSourceCRS =
psRTI->poForwardTransform->GetSourceCS();
const OGRSpatialReference *poTargetCRS =
psRTI->poForwardTransform->GetTargetCS();
if (poTargetCRS != nullptr &&
psRTI->poReverseTransform != nullptr &&
poTargetCRS->IsGeographic() &&
fabs(poTargetCRS->GetAngularUnits() -
CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-9 &&
(!poSourceCRS || !poSourceCRS->IsGeographic()))
{
bIsGeographicCoordsDeg = true;
std::unique_ptr<CPLConfigOptionSetter> poSetter;
if (pGIPTI->bCheckWithInvertPROJ)
{
// CHECK_WITH_INVERT_PROJ=YES prevent reliable
// transformation of poles.
poSetter = std::make_unique<CPLConfigOptionSetter>(
"CHECK_WITH_INVERT_PROJ", "NO", false);
GDALRefreshGenImgProjTransformer(pTransformArg);
// GDALRefreshGenImgProjTransformer() has invalidated psRTI
psRTI = static_cast<const GDALReprojectionTransformInfo *>(
pGIPTI->pReprojectArg);
}
for (const auto &sign : iSignArray)
{
double X = 0.0;
const double Yinit = 90.0 * sign;
double Y = Yinit;
if (psRTI->poReverseTransform->Transform(1, &X, &Y))
{
const auto invGT =
pGIPTI->sSrcParams.adfInvGeoTransform;
const double x = invGT[0] + X * invGT[1] + Y * invGT[2];
const double y = invGT[3] + X * invGT[4] + Y * invGT[5];
constexpr double EPSILON = 1e-5;
if (x >= -EPSILON && x <= nInXSize + EPSILON &&
y >= -EPSILON && y <= nInYSize + EPSILON)
{
if (psRTI->poForwardTransform->Transform(1, &X,
&Y) &&
fabs(Y - Yinit) <= 1e-6)
{
bool bMinXMaxXSet = false;
if (poSourceCRS)
{
const char *pszProjection =
poSourceCRS->GetAttrValue("PROJECTION");
if (pszProjection &&
EQUAL(pszProjection,
SRS_PT_ORTHOGRAPHIC))
{
const double dfLon0 =
poSourceCRS->GetNormProjParm(
SRS_PP_CENTRAL_MERIDIAN, 0.0);
dfMinXOut = dfLon0 - 90;
dfMaxXOut = dfLon0 + 90;
bMinXMaxXSet = true;
}
}
if (!bMinXMaxXSet)
{
dfMinXOut = -180;
dfMaxXOut = 180;
}
if (sign < 0)
dfMinYOut = Yinit;
else
dfMaxYOut = Yinit;
}
}
}
}
if (poSetter)
{
poSetter.reset();
GDALRefreshGenImgProjTransformer(pTransformArg);
pGIPTI = static_cast<const GDALGenImgProjTransformInfo *>(
pTransformArg);
psRTI = static_cast<const GDALReprojectionTransformInfo *>(
pGIPTI->pReprojectArg);
poSourceCRS = psRTI->poForwardTransform->GetSourceCS();
poTargetCRS = psRTI->poForwardTransform->GetTargetCS();
}
}
// Use TransformBounds() to handle more particular cases
if (poSourceCRS != nullptr && poTargetCRS != nullptr &&
pGIPTI->sSrcParams.adfGeoTransform[1] != 0 &&
pGIPTI->sSrcParams.adfGeoTransform[2] == 0 &&
pGIPTI->sSrcParams.adfGeoTransform[4] == 0 &&
pGIPTI->sSrcParams.adfGeoTransform[5] != 0)
{
const double dfULX = pGIPTI->sSrcParams.adfGeoTransform[0];
const double dfULY = pGIPTI->sSrcParams.adfGeoTransform[3];
const double dfLRX =
dfULX + pGIPTI->sSrcParams.adfGeoTransform[1] * nInXSize;
const double dfLRY =
dfULY + pGIPTI->sSrcParams.adfGeoTransform[5] * nInYSize;
const double dfMinSrcX = std::min(dfULX, dfLRX);
const double dfMinSrcY = std::min(dfULY, dfLRY);
const double dfMaxSrcX = std::max(dfULX, dfLRX);
const double dfMaxSrcY = std::max(dfULY, dfLRY);
double dfTmpMinXOut = std::numeric_limits<double>::max();
double dfTmpMinYOut = std::numeric_limits<double>::max();
double dfTmpMaxXOut = std::numeric_limits<double>::min();
double dfTmpMaxYOut = std::numeric_limits<double>::min();
if (psRTI->poForwardTransform->TransformBounds(
dfMinSrcX, dfMinSrcY, dfMaxSrcX, dfMaxSrcY,
&dfTmpMinXOut, &dfTmpMinYOut, &dfTmpMaxXOut,
&dfTmpMaxYOut,
2)) // minimum number of points as we already have a
// logic above to sample
{
dfMinXOut = std::min(dfMinXOut, dfTmpMinXOut);
dfMinYOut = std::min(dfMinYOut, dfTmpMinYOut);
dfMaxXOut = std::max(dfMaxXOut, dfTmpMaxXOut);
dfMaxYOut = std::max(dfMaxYOut, dfTmpMaxYOut);
}
}
}
}
/* -------------------------------------------------------------------- */
/* Compute the distance in "georeferenced" units from the top */
/* corner of the transformed input image to the bottom left */
/* corner of the transformed input. Use this distance to */
/* compute an approximate pixel size in the output */
/* georeferenced coordinates. */
/* -------------------------------------------------------------------- */
double dfDiagonalDist = 0.0;
double dfDeltaX = 0.0;
double dfDeltaY = 0.0;
if (pabSuccess[0] && pabSuccess[nSamplePoints - 1])
{
dfDeltaX = padfX[nSamplePoints - 1] - padfX[0];
dfDeltaY = padfY[nSamplePoints - 1] - padfY[0];
// In some cases this can result in 0 values. See #5980
// Fallback to safer method in that case.
}
if (dfDeltaX == 0.0 || dfDeltaY == 0.0)
{
dfDeltaX = dfMaxXOut - dfMinXOut;
dfDeltaY = dfMaxYOut - dfMinYOut;
}
dfDiagonalDist = sqrt(dfDeltaX * dfDeltaX + dfDeltaY * dfDeltaY);
/* -------------------------------------------------------------------- */
/* Compute a pixel size from this. */
/* -------------------------------------------------------------------- */
double dfPixelSize =
dfDiagonalDist / sqrt(static_cast<double>(nInXSize) * nInXSize +
static_cast<double>(nInYSize) * nInYSize);
double dfPixels = (dfMaxXOut - dfMinXOut) / dfPixelSize;
double dfLines = (dfMaxYOut - dfMinYOut) / dfPixelSize;
const int knIntMaxMinusOne = std::numeric_limits<int>::max() - 1;
if (dfPixels > knIntMaxMinusOne && dfLines <= dfPixels)
{
dfPixels = knIntMaxMinusOne;
dfPixelSize = (dfMaxXOut - dfMinXOut) / dfPixels;
dfLines = (dfMaxYOut - dfMinYOut) / dfPixelSize;
}
else if (dfLines > knIntMaxMinusOne)
{
dfLines = knIntMaxMinusOne;
dfPixelSize = (dfMaxYOut - dfMinYOut) / dfLines;
dfPixels = (dfMaxXOut - dfMinXOut) / dfPixelSize;
}
if (dfPixels > knIntMaxMinusOne || dfLines > knIntMaxMinusOne)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Computed dimensions are too big : %.0f x %.0f",
dfPixels + 0.5, dfLines + 0.5);
CPLFree(padfX);
CPLFree(padfXRevert);
CPLFree(pabSuccess);
return CE_Failure;
}
if ((nOptions & GDAL_SWO_ROUND_UP_SIZE) != 0)
{
constexpr double EPS = 1e-5;
*pnPixels = static_cast<int>(std::ceil(dfPixels - EPS));
*pnLines = static_cast<int>(std::ceil(dfLines - EPS));
}
else
{
*pnPixels = static_cast<int>(dfPixels + 0.5);
*pnLines = static_cast<int>(dfLines + 0.5);
}
double dfPixelSizeX = dfPixelSize;
double dfPixelSizeY = dfPixelSize;
const double adfRatioArray[] = {0.000, 0.001, 0.010, 0.100, 1.000};
/* -------------------------------------------------------------------- */
/* Check that the right border is not completely out of source */
/* image. If so, adjust the x pixel size a bit in the hope it will */
/* fit. */
/* -------------------------------------------------------------------- */
for (const auto &dfRatio : adfRatioArray)
{
const double dfTryPixelSizeX =
dfPixelSizeX - dfPixelSizeX * dfRatio / *pnPixels;
double adfExtent[4] = {dfMinXOut, dfMaxYOut - (*pnLines) * dfPixelSizeY,
dfMinXOut + (*pnPixels) * dfTryPixelSizeX,
dfMaxYOut};
if (!GDALSuggestedWarpOutput2_MustAdjustForRightBorder(
pfnTransformer, pTransformArg, adfExtent, *pnPixels, *pnLines,
dfTryPixelSizeX, dfPixelSizeY))
{
dfPixelSizeX = dfTryPixelSizeX;
break;
}
}
/* -------------------------------------------------------------------- */
/* Check that the bottom border is not completely out of source */
/* image. If so, adjust the y pixel size a bit in the hope it will */
/* fit. */
/* -------------------------------------------------------------------- */
for (const auto &dfRatio : adfRatioArray)
{
const double dfTryPixelSizeY =
dfPixelSizeY - dfPixelSizeY * dfRatio / *pnLines;
double adfExtent[4] = {
dfMinXOut, dfMaxYOut - (*pnLines) * dfTryPixelSizeY,
dfMinXOut + (*pnPixels) * dfPixelSizeX, dfMaxYOut};
if (!GDALSuggestedWarpOutput2_MustAdjustForBottomBorder(
pfnTransformer, pTransformArg, adfExtent, *pnPixels, *pnLines,
dfPixelSizeX, dfTryPixelSizeY))
{
dfPixelSizeY = dfTryPixelSizeY;
break;
}
}
/* -------------------------------------------------------------------- */
/* Recompute some bounds so that all return values are consistent */
/* -------------------------------------------------------------------- */
double dfMaxXOutNew = dfMinXOut + (*pnPixels) * dfPixelSizeX;
if (bIsGeographicCoordsDeg &&
((dfMaxXOut <= 180 && dfMaxXOutNew > 180) || dfMaxXOut == 180))
{
dfMaxXOut = 180;
dfPixelSizeX = (dfMaxXOut - dfMinXOut) / *pnPixels;
}
else
{
dfMaxXOut = dfMaxXOutNew;
}
double dfMinYOutNew = dfMaxYOut - (*pnLines) * dfPixelSizeY;
if (bIsGeographicCoordsDeg && dfMinYOut >= -90 && dfMinYOutNew < -90)
{
dfMinYOut = -90;
dfPixelSizeY = (dfMaxYOut - dfMinYOut) / *pnLines;
}
else
{
dfMinYOut = dfMinYOutNew;
}
/* -------------------------------------------------------------------- */
/* Return raw extents. */
/* -------------------------------------------------------------------- */
padfExtent[0] = dfMinXOut;
padfExtent[1] = dfMinYOut;
padfExtent[2] = dfMaxXOut;
padfExtent[3] = dfMaxYOut;
/* -------------------------------------------------------------------- */
/* Set the output geotransform. */
/* -------------------------------------------------------------------- */
padfGeoTransformOut[0] = dfMinXOut;
padfGeoTransformOut[1] = dfPixelSizeX;
padfGeoTransformOut[2] = 0.0;
padfGeoTransformOut[3] = dfMaxYOut;
padfGeoTransformOut[4] = 0.0;
padfGeoTransformOut[5] = -dfPixelSizeY;
CPLFree(padfX);
CPLFree(padfXRevert);
CPLFree(pabSuccess);
return CE_None;
}
/************************************************************************/
/* GetCurrentCheckWithInvertPROJ() */
/************************************************************************/
static bool GetCurrentCheckWithInvertPROJ()
{
return CPLTestBool(CPLGetConfigOption("CHECK_WITH_INVERT_PROJ", "NO"));
}
/************************************************************************/
/* GDALCreateGenImgProjTransformerInternal() */
/************************************************************************/
static void *GDALCreateSimilarGenImgProjTransformer(void *hTransformArg,
double dfRatioX,
double dfRatioY);
static GDALGenImgProjTransformInfo *GDALCreateGenImgProjTransformerInternal()
{
/* -------------------------------------------------------------------- */
/* Initialize the transform info. */
/* -------------------------------------------------------------------- */
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(
CPLCalloc(sizeof(GDALGenImgProjTransformInfo), 1));
memcpy(psInfo->sTI.abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE));
psInfo->sTI.pszClassName = GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME;
psInfo->sTI.pfnTransform = GDALGenImgProjTransform;
psInfo->sTI.pfnCleanup = GDALDestroyGenImgProjTransformer;
psInfo->sTI.pfnSerialize = GDALSerializeGenImgProjTransformer;
psInfo->sTI.pfnCreateSimilar = GDALCreateSimilarGenImgProjTransformer;
psInfo->bCheckWithInvertPROJ = GetCurrentCheckWithInvertPROJ();
psInfo->bHasCustomTransformationPipeline = false;
return psInfo;
}
/************************************************************************/
/* GDALCreateSimilarGenImgProjTransformer() */
/************************************************************************/
static void *GDALCreateSimilarGenImgProjTransformer(void *hTransformArg,
double dfRatioX,
double dfRatioY)
{
VALIDATE_POINTER1(hTransformArg, "GDALCreateSimilarGenImgProjTransformer",
nullptr);
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(hTransformArg);
GDALGenImgProjTransformInfo *psClonedInfo =
GDALCreateGenImgProjTransformerInternal();
memcpy(psClonedInfo, psInfo, sizeof(GDALGenImgProjTransformInfo));
psClonedInfo->bCheckWithInvertPROJ = GetCurrentCheckWithInvertPROJ();
if (psClonedInfo->sSrcParams.pTransformArg)
psClonedInfo->sSrcParams.pTransformArg = GDALCreateSimilarTransformer(
psInfo->sSrcParams.pTransformArg, dfRatioX, dfRatioY);
else if (dfRatioX != 1.0 || dfRatioY != 1.0)
{
if (psClonedInfo->sSrcParams.adfGeoTransform[2] == 0.0 &&
psClonedInfo->sSrcParams.adfGeoTransform[4] == 0.0)
{
psClonedInfo->sSrcParams.adfGeoTransform[1] *= dfRatioX;
psClonedInfo->sSrcParams.adfGeoTransform[5] *= dfRatioY;
}
else
{
// If the x and y ratios are not equal, then we cannot really
// compute a geotransform.
psClonedInfo->sSrcParams.adfGeoTransform[1] *= dfRatioX;
psClonedInfo->sSrcParams.adfGeoTransform[2] *= dfRatioX;
psClonedInfo->sSrcParams.adfGeoTransform[4] *= dfRatioX;
psClonedInfo->sSrcParams.adfGeoTransform[5] *= dfRatioX;
}
if (!GDALInvGeoTransform(psClonedInfo->sSrcParams.adfGeoTransform,
psClonedInfo->sSrcParams.adfInvGeoTransform))
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot invert geotransform");
GDALDestroyGenImgProjTransformer(psClonedInfo);
return nullptr;
}
}
if (psClonedInfo->pReprojectArg)
psClonedInfo->pReprojectArg =
GDALCloneTransformer(psInfo->pReprojectArg);
if (psClonedInfo->sDstParams.pTransformArg)
psClonedInfo->sDstParams.pTransformArg =
GDALCloneTransformer(psInfo->sDstParams.pTransformArg);
return psClonedInfo;
}
/************************************************************************/
/* GDALCreateGenImgProjTransformer() */
/************************************************************************/
/**
* Create image to image transformer.
*
* This function creates a transformation object that maps from pixel/line
* coordinates on one image to pixel/line coordinates on another image. The
* images may potentially be georeferenced in different coordinate systems,
* and may used GCPs to map between their pixel/line coordinates and
* georeferenced coordinates (as opposed to the default assumption that their
* geotransform should be used).
*
* This transformer potentially performs three concatenated transformations.
*
* The first stage is from source image pixel/line coordinates to source
* image georeferenced coordinates, and may be done using the geotransform,
* or if not defined using a polynomial model derived from GCPs. If GCPs
* are used this stage is accomplished using GDALGCPTransform().
*
* The second stage is to change projections from the source coordinate system
* to the destination coordinate system, assuming they differ. This is
* accomplished internally using GDALReprojectionTransform().
*
* The third stage is converting from destination image georeferenced
* coordinates to destination image coordinates. This is done using the
* destination image geotransform, or if not available, using a polynomial
* model derived from GCPs. If GCPs are used this stage is accomplished using
* GDALGCPTransform(). This stage is skipped if hDstDS is NULL when the
* transformation is created.
*
* @param hSrcDS source dataset, or NULL.
* @param pszSrcWKT the coordinate system for the source dataset. If NULL,
* it will be read from the dataset itself.
* @param hDstDS destination dataset (or NULL).
* @param pszDstWKT the coordinate system for the destination dataset. If
* NULL, and hDstDS not NULL, it will be read from the destination dataset.
* @param bGCPUseOK TRUE if GCPs should be used if the geotransform is not
* available on the source dataset (not destination).
* @param dfGCPErrorThreshold ignored/deprecated.
* @param nOrder the maximum order to use for GCP derived polynomials if
* possible. Use 0 to autoselect, or -1 for thin plate splines.
*
* @return handle suitable for use GDALGenImgProjTransform(), and to be
* deallocated with GDALDestroyGenImgProjTransformer().
*/
void *GDALCreateGenImgProjTransformer(GDALDatasetH hSrcDS,
const char *pszSrcWKT,
GDALDatasetH hDstDS,
const char *pszDstWKT, int bGCPUseOK,
CPL_UNUSED double dfGCPErrorThreshold,
int nOrder)
{
char **papszOptions = nullptr;
if (pszSrcWKT != nullptr)
papszOptions = CSLSetNameValue(papszOptions, "SRC_SRS", pszSrcWKT);
if (pszDstWKT != nullptr)
papszOptions = CSLSetNameValue(papszOptions, "DST_SRS", pszDstWKT);
if (!bGCPUseOK)
papszOptions = CSLSetNameValue(papszOptions, "GCPS_OK", "FALSE");
if (nOrder != 0)
papszOptions = CSLSetNameValue(papszOptions, "MAX_GCP_ORDER",
CPLString().Printf("%d", nOrder));
void *pRet = GDALCreateGenImgProjTransformer2(hSrcDS, hDstDS, papszOptions);
CSLDestroy(papszOptions);
return pRet;
}
/************************************************************************/
/* InsertCenterLong() */
/* */
/* Insert a CENTER_LONG Extension entry on a GEOGCS to indicate */
/* the center longitude of the dataset for wrapping purposes. */
/************************************************************************/
static void InsertCenterLong(GDALDatasetH hDS, const OGRSpatialReference *poSRS,
const OGRSpatialReference *poDstSRS,
const char *pszTargetExtent,
CPLStringList &aosOptions)
{
if (!poSRS->IsGeographic() || std::fabs(poSRS->GetAngularUnits() -
CPLAtof(SRS_UA_DEGREE_CONV)) > 1e-9)
{
return;
}
if (poSRS->GetExtension(nullptr, "CENTER_LONG"))
return;
/* -------------------------------------------------------------------- */
/* For now we only do this if we have a geotransform since */
/* other forms require a bunch of extra work. */
/* -------------------------------------------------------------------- */
double adfGeoTransform[6] = {};
if (GDALGetGeoTransform(hDS, adfGeoTransform) != CE_None)
return;
/* -------------------------------------------------------------------- */
/* Compute min/max longitude based on testing the four corners. */
/* -------------------------------------------------------------------- */
const int nXSize = GDALGetRasterXSize(hDS);
const int nYSize = GDALGetRasterYSize(hDS);
const double dfMinLong =
std::min(std::min(adfGeoTransform[0] + 0 * adfGeoTransform[1] +
0 * adfGeoTransform[2],
adfGeoTransform[0] + nXSize * adfGeoTransform[1] +
0 * adfGeoTransform[2]),
std::min(adfGeoTransform[0] + 0 * adfGeoTransform[1] +
nYSize * adfGeoTransform[2],
adfGeoTransform[0] + nXSize * adfGeoTransform[1] +
nYSize * adfGeoTransform[2]));
const double dfMaxLong =
std::max(std::max(adfGeoTransform[0] + 0 * adfGeoTransform[1] +
0 * adfGeoTransform[2],
adfGeoTransform[0] + nXSize * adfGeoTransform[1] +
0 * adfGeoTransform[2]),
std::max(adfGeoTransform[0] + 0 * adfGeoTransform[1] +
nYSize * adfGeoTransform[2],
adfGeoTransform[0] + nXSize * adfGeoTransform[1] +
nYSize * adfGeoTransform[2]));
// If the raster covers more than 360 degree, give up,
// except is the target SRS is geographic and crossing the antimeridian
if (dfMaxLong - dfMinLong > 360.0)
{
const CPLStringList aosTE(CSLTokenizeString2(pszTargetExtent, ",", 0));
if (aosTE.size() == 4 && poDstSRS->IsGeographic() &&
std::fabs(poDstSRS->GetAngularUnits() -
CPLAtof(SRS_UA_DEGREE_CONV)) <= 1e-9 &&
((CPLAtof(aosTE[0]) >= -179 && CPLAtof(aosTE[0]) < 180 &&
CPLAtof(aosTE[2]) > 180) ||
(CPLAtof(aosTE[0]) < -180 && CPLAtof(aosTE[2]) > -180 &&
CPLAtof(aosTE[2]) <= 179)))
{
// insert CENTER_LONG
}
else
{
return;
}
}
/* -------------------------------------------------------------------- */
/* Insert center long. */
/* -------------------------------------------------------------------- */
const double dfCenterLong = (dfMaxLong + dfMinLong) / 2.0;
aosOptions.SetNameValue("CENTER_LONG", CPLSPrintf("%g", dfCenterLong));
}
/************************************************************************/
/* GDALComputeAreaOfInterest() */
/************************************************************************/
bool GDALComputeAreaOfInterest(const OGRSpatialReference *poSRS,
double adfGT[6], int nXSize, int nYSize,
double &dfWestLongitudeDeg,
double &dfSouthLatitudeDeg,
double &dfEastLongitudeDeg,
double &dfNorthLatitudeDeg)
{
bool ret = false;
if (!poSRS)
return false;
OGRSpatialReference oSrcSRSHoriz(*poSRS);
if (oSrcSRSHoriz.IsCompound())
{
oSrcSRSHoriz.StripVertical();
}
OGRSpatialReference *poGeog = oSrcSRSHoriz.CloneGeogCS();
if (poGeog)
{
poGeog->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
poGeog->SetAngularUnits(SRS_UA_DEGREE, CPLAtof(SRS_UA_DEGREE_CONV));
auto poCT = OGRCreateCoordinateTransformation(&oSrcSRSHoriz, poGeog);
if (poCT)
{
poCT->SetEmitErrors(false);
double x[4], y[4];
x[0] = adfGT[0];
y[0] = adfGT[3];
x[1] = adfGT[0] + nXSize * adfGT[1];
y[1] = adfGT[3];
x[2] = adfGT[0];
y[2] = adfGT[3] + nYSize * adfGT[5];
x[3] = x[1];
y[3] = y[2];
int validity[4] = {false, false, false, false};
poCT->Transform(4, x, y, nullptr, validity);
dfWestLongitudeDeg = std::numeric_limits<double>::max();
dfSouthLatitudeDeg = std::numeric_limits<double>::max();
dfEastLongitudeDeg = -std::numeric_limits<double>::max();
dfNorthLatitudeDeg = -std::numeric_limits<double>::max();
for (int i = 0; i < 4; i++)
{
if (validity[i])
{
ret = true;
dfWestLongitudeDeg = std::min(dfWestLongitudeDeg, x[i]);
dfSouthLatitudeDeg = std::min(dfSouthLatitudeDeg, y[i]);
dfEastLongitudeDeg = std::max(dfEastLongitudeDeg, x[i]);
dfNorthLatitudeDeg = std::max(dfNorthLatitudeDeg, y[i]);
}
}
if (validity[0] && validity[1] && x[0] > x[1])
{
dfWestLongitudeDeg = x[0];
dfEastLongitudeDeg = x[1];
}
if (ret && std::fabs(dfWestLongitudeDeg) <= 180 &&
std::fabs(dfEastLongitudeDeg) <= 180 &&
std::fabs(dfSouthLatitudeDeg) <= 90 &&
std::fabs(dfNorthLatitudeDeg) <= 90)
{
CPLDebug("GDAL", "Computing area of interest: %g, %g, %g, %g",
dfWestLongitudeDeg, dfSouthLatitudeDeg,
dfEastLongitudeDeg, dfNorthLatitudeDeg);
}
else
{
CPLDebug("GDAL", "Could not compute area of interest");
dfWestLongitudeDeg = 0;
dfSouthLatitudeDeg = 0;
dfEastLongitudeDeg = 0;
dfNorthLatitudeDeg = 0;
}
OGRCoordinateTransformation::DestroyCT(poCT);
}
delete poGeog;
}
return ret;
}
bool GDALComputeAreaOfInterest(const OGRSpatialReference *poSRS, double dfX1,
double dfY1, double dfX2, double dfY2,
double &dfWestLongitudeDeg,
double &dfSouthLatitudeDeg,
double &dfEastLongitudeDeg,
double &dfNorthLatitudeDeg)
{
bool ret = false;
if (!poSRS)
return false;
OGRSpatialReference oSrcSRSHoriz(*poSRS);
if (oSrcSRSHoriz.IsCompound())
{
oSrcSRSHoriz.StripVertical();
}
OGRSpatialReference *poGeog = oSrcSRSHoriz.CloneGeogCS();
if (poGeog)
{
poGeog->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
auto poCT = OGRCreateCoordinateTransformation(&oSrcSRSHoriz, poGeog);
if (poCT)
{
double x[4], y[4];
x[0] = dfX1;
y[0] = dfY1;
x[1] = dfX2;
y[1] = dfY1;
x[2] = dfX1;
y[2] = dfY2;
x[3] = dfX2;
y[3] = dfY2;
int validity[4] = {false, false, false, false};
poCT->Transform(4, x, y, nullptr, validity);
dfWestLongitudeDeg = std::numeric_limits<double>::max();
dfSouthLatitudeDeg = std::numeric_limits<double>::max();
dfEastLongitudeDeg = -std::numeric_limits<double>::max();
dfNorthLatitudeDeg = -std::numeric_limits<double>::max();
for (int i = 0; i < 4; i++)
{
if (validity[i])
{
ret = true;
dfWestLongitudeDeg = std::min(dfWestLongitudeDeg, x[i]);
dfSouthLatitudeDeg = std::min(dfSouthLatitudeDeg, y[i]);
dfEastLongitudeDeg = std::max(dfEastLongitudeDeg, x[i]);
dfNorthLatitudeDeg = std::max(dfNorthLatitudeDeg, y[i]);
}
}
if (validity[0] && validity[1] && (dfX1 - dfX2) * (x[0] - x[1]) < 0)
{
dfWestLongitudeDeg = x[0];
dfEastLongitudeDeg = x[1];
}
if (ret)
{
CPLDebug("GDAL", "Computing area of interest: %g, %g, %g, %g",
dfWestLongitudeDeg, dfSouthLatitudeDeg,
dfEastLongitudeDeg, dfNorthLatitudeDeg);
}
else
{
CPLDebug("GDAL", "Could not compute area of interest");
dfWestLongitudeDeg = 0;
dfSouthLatitudeDeg = 0;
dfEastLongitudeDeg = 0;
dfNorthLatitudeDeg = 0;
}
delete poCT;
}
delete poGeog;
}
return ret;
}
/************************************************************************/
/* GDALGCPAntimeridianUnwrap() */
/************************************************************************/
/* Deal with discontinuties of dfGCPX longitudes around the anti-meridian.
* Cf https://github.com/OSGeo/gdal/issues/8371
*/
static void GDALGCPAntimeridianUnwrap(int nGCPCount, GDAL_GCP *pasGCPList,
const OGRSpatialReference &oSRS,
CSLConstList papszOptions)
{
const char *pszGCPAntimeridianUnwrap =
CSLFetchNameValueDef(papszOptions, "GCP_ANTIMERIDIAN_UNWRAP", "AUTO");
const bool bForced = EQUAL(pszGCPAntimeridianUnwrap, "YES") ||
EQUAL(pszGCPAntimeridianUnwrap, "ON") ||
EQUAL(pszGCPAntimeridianUnwrap, "TRUE") ||
EQUAL(pszGCPAntimeridianUnwrap, "1");
if (bForced || (!oSRS.IsEmpty() && oSRS.IsGeographic() &&
fabs(oSRS.GetAngularUnits(nullptr) -
CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-8 &&
EQUAL(pszGCPAntimeridianUnwrap, "AUTO")))
{
if (!bForced)
{
// Proceed to unwrapping only if the longitudes are within
// [-180, -170] or [170, 180]
for (int i = 0; i < nGCPCount; ++i)
{
const double dfLongAbs = fabs(pasGCPList[i].dfGCPX);
if (dfLongAbs > 180 || dfLongAbs < 170)
{
return;
}
}
}
bool bDone = false;
for (int i = 0; i < nGCPCount; ++i)
{
if (pasGCPList[i].dfGCPX < 0)
{
if (!bDone)
{
bDone = true;
CPLDebug("WARP", "GCP longitude unwrapping");
}
pasGCPList[i].dfGCPX += 360;
}
}
}
}
/************************************************************************/
/* GDALGetGenImgProjTranformerOptionList() */
/************************************************************************/
/** Return a XML string describing options accepted by
* GDALCreateGenImgProjTransformer2().
*
* @since 3.11
*/
const char *GDALGetGenImgProjTranformerOptionList(void)
{
return "<OptionList>"
"<Option name='SRC_SRS' type='string' description='WKT SRS, or any "
"string recognized by OGRSpatialReference::SetFromUserInput(), to "
"be used as an override for CRS of input dataset'/>"
"<Option name='DST_SRS' type='string' description='WKT SRS, or any "
"string recognized by OGRSpatialReference::SetFromUserInput(), to "
"be used as an override for CRS of output dataset'/>"
"<Option name='PROMOTE_TO_3D' type='boolean' description='"
"Whether to promote SRC_SRS / DST_SRS to 3D.' "
"default='NO'/>"
"<Option name='COORDINATE_OPERATION' type='string' description='"
"Coordinate operation, as a PROJ or WKT string, used as an override "
"over the normally computed pipeline. The pipeline must take into "
"account the axis order of the source and target SRS.'/>"
"<Option name='ALLOW_BALLPARK' type='boolean' description='"
"Whether ballpark coordinate operations are allowed.' "
"default='YES'/>"
"<Option name='ONLY_BEST' type='string-select' "
"description='"
"By default (at least in the PROJ 9.x series), PROJ may use "
"coordinate operations that are not the \"best\" if resources "
"(typically grids) needed to use them are missing. It will then "
"fallback to other coordinate operations that have a lesser "
"accuracy, for example using Helmert transformations, or in the "
"absence of such operations, to ones with potential very rough "
" accuracy, using \"ballpark\" transformations (see "
"https://proj.org/glossary.html). "
"When calling this method with YES, PROJ will only consider the "
"\"best\" operation, and error out (at Transform() time) if they "
"cannot be used. This method may be used together with "
"ALLOW_BALLPARK=NO to only allow best operations that have a known "
"accuracy. Note that this method has no effect on PROJ versions "
"before 9.2. The default value for this option can be also set with "
"the PROJ_ONLY_BEST_DEFAULT environment variable, or with the "
"\"only_best_default\" setting of proj.ini. Setting "
"ONLY_BEST=YES/NO overrides such default value' default='AUTO'>"
" <Value>AUTO</Value>"
" <Value>YES</Value>"
" <Value>NO</Value>"
"</Option>"
"<Option name='COORDINATE_EPOCH' type='float' description='"
"Coordinate epoch, expressed as a decimal year. Useful for "
"time-dependent coordinate operations.'/>"
"<Option name='SRC_COORDINATE_EPOCH' type='float' description='"
"Coordinate epoch of source CRS, expressed as a decimal year. "
"Useful for time-dependent coordinate operations.'/>"
"<Option name='DST_COORDINATE_EPOCH' type='float' description='"
"Coordinate epoch of target CRS, expressed as a decimal year. "
"Useful for time-dependent coordinate operations.'/>"
"<Option name='GCPS_OK' type='boolean' description='"
"Allow use of GCPs.' default='YES'/>"
"<Option name='REFINE_MINIMUM_GCPS' type='int' description='"
"The minimum amount of GCPs that should be available after the "
"refinement'/>"
"<Option name='REFINE_TOLERANCE' type='float' description='"
"The tolerance that specifies when a GCP will be eliminated.'/>"
"<Option name='MAX_GCP_ORDER' type='int' description='"
"The maximum order to use for GCP derived polynomials if possible. "
"The default is to autoselect based on the number of GCPs. A value "
"of -1 triggers use of Thin Plate Spline instead of polynomials.'/>"
"<Option name='GCP_ANTIMERIDIAN_UNWRAP' type='string-select' "
"description='"
"Whether to \"unwrap\" longitudes of ground control points that "
"span the antimeridian. For datasets with GCPs in "
"longitude/latitude coordinate space spanning the antimeridian, "
"longitudes will have a discontinuity on +/- 180 deg, and will "
"result in a subset of the GCPs with longitude in the [-180,-170] "
"range and another subset in [170, 180]. By default (AUTO), that "
"situation will be detected and longitudes in [-180,-170] will be "
"shifted to [180, 190] to get a continuous set. This option can be "
"set to YES to force that behavior (useful if no SRS information is "
"available), or to NO to disable it.' default='AUTO'>"
" <Value>AUTO</Value>"
" <Value>YES</Value>"
" <Value>NO</Value>"
"</Option>"
"<Option name='SRC_METHOD' alias='METHOD' type='string-select' "
"description='"
"Force only one geolocation method to be considered on the source "
"dataset. Will be used for pixel/line to georef transformation on "
"the source dataset. NO_GEOTRANSFORM can be used to specify the "
"identity geotransform (ungeoreferenced image)'>"
" <Value>GEOTRANSFORM</Value>"
" <Value>GCP_POLYNOMIAL</Value>"
" <Value>GCP_TPS</Value>"
" <Value>GCP_HOMOGRAPHY</Value>"
" <Value>GEOLOC_ARRAY</Value>"
" <Value>RPC</Value>"
" <Value>NO_GEOTRANSFORM</Value>"
"</Option>"
"<Option name='DST_METHOD' type='string-select' description='"
"Force only one geolocation method to be considered on the target "
"dataset. Will be used for pixel/line to georef transformation on "
"the targe dataset. NO_GEOTRANSFORM can be used to specify the "
"identity geotransform (ungeoreferenced image)'>"
" <Value>GEOTRANSFORM</Value>"
" <Value>GCP_POLYNOMIAL</Value>"
" <Value>GCP_TPS</Value>"
" <Value>GCP_HOMOGRAPHY</Value>"
" <Value>GEOLOC_ARRAY</Value>"
" <Value>RPC</Value>"
" <Value>NO_GEOTRANSFORM</Value>"
"</Option>"
"<Option name='RPC_HEIGHT' type='float' description='"
"A fixed height to be used with RPC calculations. If RPC_HEIGHT and "
"RPC_DEM are not specified but that the RPC metadata domain contains"
" a HEIGHT_DEFAULT item (for example, the DIMAP driver may fill it),"
"this value will be used as the RPC_HEIGHT. Otherwise, if none of "
"RPC_HEIGHT and RPC_DEM are specified as transformer options and "
"if HEIGHT_DEFAULT is no available, a height of 0 will be used.'/>"
"<Option name='RPC_DEM' type='string' description='"
"Name of a GDAL dataset (a DEM file typically) used to extract "
"elevation offsets from. In this situation the Z passed into the "
"transformation function is assumed to be height above ground. "
"This option should be used in replacement of RPC_HEIGHT to provide "
"a way of defining a non uniform ground for the target scene.'/>"
"<Option name='RPC_HEIGHT_SCALE' type='float' description='"
"Factor used to multiply heights above ground. Useful when "
"elevation offsets of the DEM are not expressed in meters.'/>"
"<Option name='RPC_DEMINTERPOLATION' type='string-select' "
"description='DEM interpolation method' default='BILINEAR'>"
" <Value>NEAR</Value>"
" <Value>BILINEAR</Value>"
" <Value>CUBIC</Value>"
"</Option>"
"<Option name='RPC_DEM_MISSING_VALUE' type='float' description='"
"Value of DEM height that must be used in case the DEM has nodata "
"value at the sampling point, or if its extent does not cover the "
"requested coordinate. When not specified, missing values will "
"cause a failed transform.'/>"
"<Option name='RPC_DEM_SRS' type='string' description='"
"WKT SRS, or any string recognized by "
"OGRSpatialReference::SetFromUserInput(), to be used as an "
"override for DEM SRS. Useful if DEM SRS does not have an explicit "
"vertical component.'/>"
"<Option name='RPC_DEM_APPLY_VDATUM_SHIFT' type='boolean' "
"description='"
"Whether the vertical component of a compound SRS for the DEM "
"should be used (when it is present). This is useful so as to "
"be able to transform the raw values from the DEM expressed with "
"respect to a geoid to the heights with respect to the WGS84 "
"ellipsoid. When this is enabled, the GTIFF_REPORT_COMPD_CS "
"configuration option will be also set temporarily so as to get "
"the vertical information from GeoTIFF files.' default='YES'/>"
"<Option name='RPC_PIXEL_ERROR_THRESHOLD' type='float' description='"
"Overrides the dfPixErrThreshold parameter, i.e. the error "
"(measured in pixels) allowed in the iterative solution of "
"pixel/line to lat/long computations (the other way is always "
"exact given the equations).'/>"
"<Option name='RPC_MAX_ITERATIONS' type='int' description='"
"Maximum number of iterations allowed in the iterative solution of "
"pixel/line to lat/long computations. Default value is 10 in the "
"absence of a DEM, or 20 if there is a DEM.'/>"
"<Option name='RPC_FOOTPRINT' type='string' description='"
"WKT or GeoJSON polygon (in long / lat coordinate space) with a "
"validity footprint for the RPC. Any coordinate transformation that "
"goes from or arrive outside this footprint will be considered "
"invalid. This* is useful in situations where the RPC values become "
"highly unstable outside of the area on which they have been "
"computed for, potentially leading to undesirable \"echoes\" / "
"false positives. This requires GDAL to be built against GEOS..'/>"
"<Option name='RPC_MAX_ITERATIONS' type='int' description='"
"Maximum number of iterations allowed in the iterative solution of "
"pixel/line to lat/long computations. Default value is 10 in the "
"absence of a DEM, or 20 if there is a DEM.'/>"
"<Option name='INSERT_CENTER_LONG' type='boolean' description='"
"May be set to FALSE to disable setting up a CENTER_LONG value on "
"the coordinate system to rewrap things around the center of the "
"image.' default='YES'/>"
"<Option name='SRC_APPROX_ERROR_IN_SRS_UNIT' type='float' "
"description='"
"Use an approximate transformer for the source transformer. Must be "
"defined together with SRC_APPROX_ERROR_IN_PIXEL to be taken into "
"account.'/>"
"<Option name='SRC_APPROX_ERROR_IN_PIXEL' type='float' "
"description='"
"Use an approximate transformer for the source transformer. Must be "
"defined together with SRC_APPROX_ERROR_IN_SRS_UNIT to be taken "
"into "
"account.'/>"
"<Option name='DST_APPROX_ERROR_IN_SRS_UNIT' type='float' "
"description='"
"Use an approximate transformer for the target transformer. Must be "
"defined together with DST_APPROX_ERROR_IN_PIXEL to be taken into "
"account.'/>"
"<Option name='DST_APPROX_ERROR_IN_PIXEL' type='float' "
"description='"
"Use an approximate transformer for the target transformer. Must be "
"defined together with DST_APPROX_ERROR_IN_SRS_UNIT to be taken "
"into "
"account.'/>"
"<Option name='REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT' "
"type='float' "
"description='"
"Use an approximate transformer for the coordinate reprojection. "
"Must be used together with "
"REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT to be taken into "
"account.'/>"
"<Option name='REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT' "
"type='float' "
"description='"
"Use an approximate transformer for the coordinate reprojection. "
"Must be used together with "
"REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT to be taken into "
"account.'/>"
"<Option name='AREA_OF_INTEREST' type='string' "
"description='"
"Area of interest, as "
"west_lon_deg,south_lat_deg,east_lon_deg,north_lat_deg, used to "
"compute the best coordinate operation between the source and "
"target SRS. If not specified, the bounding box of the source "
"raster will be used.'/>"
"<Option name='TARGET_EXTENT' type='string' "
"description='Target extent as minx,miny,maxx,maxy expressed in "
"target SRS.'/>"
"<Option name='GEOLOC_BACKMAP_OVERSAMPLE_FACTOR' type='float' "
"min='0.1' max='2' description='"
"Oversample factor used to derive the size of the \"backmap\" used "
"for geolocation array transformers.' default='1.3'/>"
"<Option name='GEOLOC_USE_TEMP_DATASETS' type='boolean' "
"description='"
"Whether temporary GeoTIFF datasets should be used to store the "
"backmap. The default is NO, that is to use in-memory arrays, "
"unless the number of pixels of the geolocation array is greater "
"than 16 megapixels.' default='NO'/>"
"<Option name='GEOLOC_ARRAY' alias='SRC_GEOLOC_ARRAY' type='string' "
"description='"
"Name of a GDAL dataset containing a geolocation array and "
"associated metadata. This is an alternative to having geolocation "
"information described in the GEOLOCATION metadata domain of the "
"source dataset. The dataset specified may have a GEOLOCATION "
"metadata domain containing appropriate metadata, however default "
"values are assigned for all omitted items. X_BAND defaults to 1 "
"and Y_BAND to 2, however the dataset must contain exactly 2 bands. "
"PIXEL_OFFSET and LINE_OFFSET default to 0. PIXEL_STEP and "
"LINE_STEP default to the ratio of the width/height of the source "
"dataset divided by the with/height of the geolocation array. "
"SRS defaults to the spatial reference system of the geolocation "
"array dataset, if set, otherwise WGS84 is used. "
"GEOREFERENCING_CONVENTION is selected from the main metadata "
"domain if it is omitted from the GEOLOCATION domain, and if not "
"available TOP_LEFT_CORNER is assigned as a default. "
"If GEOLOC_ARRAY is set SRC_METHOD defaults to GEOLOC_ARRAY.'/>"
"<Option name='DST_GEOLOC_ARRAY' type='string' "
"description='"
"Name of a GDAL dataset that contains at least 2 bands with the X "
"and Y geolocation bands. This is an alternative to having "
"geolocation information described in the GEOLOCATION metadata "
"domain of the destination dataset. See SRC_GEOLOC_ARRAY "
"description for details, assumptions, and defaults. If this "
"option is set, DST_METHOD=GEOLOC_ARRAY will be assumed if not "
"set.'/>"
"<Option name='GEOLOC_NORMALIZE_LONGITUDE_MINUS_180_PLUS_180' "
"type='boolean' "
"description='"
"Force geolocation longitudes into -180,180 when longitude/latitude "
"is the coordinate system of the geolocation arrays' default='NO'>"
" <Value>YES</Value>"
" <Value>NO</Value>"
"</Option>"
"<Option name='NUM_THREADS' type='string' "
"description='Number of threads to use'/>"
"</OptionList>";
}
/************************************************************************/
/* GDALCreateGenImgProjTransformer2() */
/************************************************************************/
/* clang-format off */
/**
* Create image to image transformer.
*
* This function creates a transformation object that maps from pixel/line
* coordinates on one image to pixel/line coordinates on another image. The
* images may potentially be georeferenced in different coordinate systems,
* and may used GCPs to map between their pixel/line coordinates and
* georeferenced coordinates (as opposed to the default assumption that their
* geotransform should be used).
*
* This transformer potentially performs three concatenated transformations.
*
* The first stage is from source image pixel/line coordinates to source
* image georeferenced coordinates, and may be done using the geotransform,
* or if not defined using a polynomial model derived from GCPs. If GCPs
* are used this stage is accomplished using GDALGCPTransform().
*
* The second stage is to change projections from the source coordinate system
* to the destination coordinate system, assuming they differ. This is
* accomplished internally using GDALReprojectionTransform().
*
* The third stage is converting from destination image georeferenced
* coordinates to destination image coordinates. This is done using the
* destination image geotransform, or if not available, using a polynomial
* model derived from GCPs. If GCPs are used this stage is accomplished using
* GDALGCPTransform(). This stage is skipped if hDstDS is NULL when the
* transformation is created.
*
* Supported Options (specified with the -to switch of gdalwarp for example):
* <ul>
* <li> SRC_SRS: WKT SRS, or any string recognized by
* OGRSpatialReference::SetFromUserInput(), to be used as an override for
* hSrcDS.</li>
* <li> DST_SRS: WKT SRS, or any string recognized by
* OGRSpatialReference::SetFromUserInput(), to be used as an override for
* hDstDS.
* </li>
* <li>PROMOTE_TO_3D=YES/NO: whether to promote SRC_SRS / DST_SRS to 3D.
* Default is NO</li>
* <li> COORDINATE_OPERATION: (GDAL >= 3.0) Coordinate operation, as
* a PROJ or WKT string, used as an override over the normally computed
* pipeline. The pipeline must take into account the axis order of the source
* and target SRS.
* </li>
* <li> ALLOW_BALLPARK=YES/NO: (GDAL >= 3.11) Whether ballpark coordinate
* operations are allowed. Defaults to YES.</li>
* <li> ONLY_BEST=YES/NO/AUTO: (GDAL >= 3.11) By default (at least in the
* PROJ 9.x series), PROJ may use coordinate
* operations that are not the "best" if resources (typically grids) needed
* to use them are missing. It will then fallback to other coordinate operations
* that have a lesser accuracy, for example using Helmert transformations,
* or in the absence of such operations, to ones with potential very rough
* accuracy, using "ballpark" transformations
* (see https://proj.org/glossary.html).
* When calling this method with YES, PROJ will only consider the
* "best" operation, and error out (at Transform() time) if they cannot be
* used.
* This method may be used together with ALLOW_BALLPARK=NO to
* only allow best operations that have a known accuracy.
* Note that this method has no effect on PROJ versions before 9.2.
* The default value for this option can be also set with the
* PROJ_ONLY_BEST_DEFAULT environment variable, or with the "only_best_default"
* setting of proj.ini. Calling SetOnlyBest() overrides such default value.</li>
* <li> COORDINATE_EPOCH: (GDAL >= 3.0) Coordinate epoch,
* expressed as a decimal year. Useful for time-dependent coordinate operations.
* </li>
* <li> SRC_COORDINATE_EPOCH: (GDAL >= 3.4) Coordinate epoch of source CRS,
* expressed as a decimal year. Useful for time-dependent coordinate operations.
* </li>
* <li> DST_COORDINATE_EPOCH: (GDAL >= 3.4) Coordinate epoch of target CRS,
* expressed as a decimal year. Useful for time-dependent coordinate operations.
* </li>
* <li> GCPS_OK: If false, GCPs will not be used, default is TRUE.
* </li>
* <li> REFINE_MINIMUM_GCPS: The minimum amount of GCPs that should be available
* after the refinement.
* </li>
* <li> REFINE_TOLERANCE: The tolerance that specifies when a GCP will be
* eliminated.
* </li>
* <li> MAX_GCP_ORDER: the maximum order to use for GCP derived polynomials if
* possible. The default is to autoselect based on the number of GCPs.
* A value of -1 triggers use of Thin Plate Spline instead of polynomials if
* SRC_METHOD/DST_METHOD is not specified.
* </li>
* <li>GCP_ANTIMERIDIAN_UNWRAP=AUTO/YES/NO. (GDAL >= 3.8) Whether to
* "unwrap" longitudes of ground control points that span the antimeridian.
* For datasets with GCPs in longitude/latitude coordinate space spanning the
* antimeridian, longitudes will have a discontinuity on +/- 180 deg, and
* will result in a subset of the GCPs with longitude in the [-180,-170] range
* and another subset in [170, 180]. By default (AUTO), that situation will be
* detected and longitudes in [-180,-170] will be shifted to [180, 190] to get
* a continuous set. This option can be set to YES to force that behavior
* (useful if no SRS information is available), or to NO to disable it.
* </li>
* <li> SRC_METHOD: may have a value which is one of GEOTRANSFORM, GCP_HOMOGRAPHY,
* GCP_POLYNOMIAL, GCP_TPS, GEOLOC_ARRAY, RPC to force only one geolocation
* method to be considered on the source dataset. Will be used for pixel/line
* to georef transformation on the source dataset. NO_GEOTRANSFORM can be
* used to specify the identity geotransform (ungeoreferenced image)
* Note that using GCP_TPS with more than a few thousand GCPs requires significant RAM usage
* (at least numGCPs * numGCPs * 8 bytes) and processing time.
* </li>
* <li> DST_METHOD: may have a value which is one of GEOTRANSFORM,
* GCP_POLYNOMIAL, GCP_HOMOGRAPHY, GCP_TPS, GEOLOC_ARRAY (added in 3.5), RPC to
* force only one
* geolocation method to be considered on the target dataset. Will be used for
* pixel/line to georef transformation on the destination dataset.
* NO_GEOTRANSFORM can be used to specify the identity geotransform
* (ungeoreferenced image)
* Note that using GCP_TPS with more than a few thousand GCPs requires significant RAM usage
* (at least numGCPs * numGCPs * 8 bytes) and processing time.
* </li>
* <li> RPC_HEIGHT: A fixed height to be used with RPC
* calculations. If RPC_HEIGHT and RPC_DEM are not specified but that the RPC
* metadata domain contains a HEIGHT_DEFAULT item (for example, the DIMAP driver
* may fill it), this value will be used as the RPC_HEIGHT. Otherwise, if none
* of RPC_HEIGHT and RPC_DEM are specified as transformer
* options and if HEIGHT_DEFAULT is no available, a height of 0 will be used.
* </li>
* <li> RPC_DEM: The name of a DEM file to be used with RPC
* calculations. See GDALCreateRPCTransformerV2() for more details.
* </li>
* <li> Other RPC related options. See GDALCreateRPCTransformerV2()
* </li>
* <li>
* INSERT_CENTER_LONG: May be set to FALSE to disable setting up a CENTER_LONG
* value on the coordinate system to rewrap things around the center of the
* image.
* </li>
* <li> SRC_APPROX_ERROR_IN_SRS_UNIT=err_threshold_in_SRS_units. (GDAL
* >= 2.2) Use an approximate transformer for the source transformer. Must be
* defined together with SRC_APPROX_ERROR_IN_PIXEL to be taken into account.
* </li>
* <li> SRC_APPROX_ERROR_IN_PIXEL=err_threshold_in_pixel. (GDAL >= 2.2) Use
* an approximate transformer for the source transformer.. Must be defined
* together with SRC_APPROX_ERROR_IN_SRS_UNIT to be taken into account.
* </li>
* <li>
* DST_APPROX_ERROR_IN_SRS_UNIT=err_threshold_in_SRS_units. (GDAL >= 2.2) Use
* an approximate transformer for the destination transformer. Must be defined
* together with DST_APPROX_ERROR_IN_PIXEL to be taken into account.
* </li>
* <li>
* DST_APPROX_ERROR_IN_PIXEL=err_threshold_in_pixel. (GDAL >= 2.2) Use an
* approximate transformer for the destination transformer. Must be defined
* together with DST_APPROX_ERROR_IN_SRS_UNIT to be taken into account.
* </li>
* <li>
* REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT=err_threshold_in_src_SRS_units.
* (GDAL >= 2.2) Use an approximate transformer for the coordinate
* reprojection. Must be used together with
* REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT to be taken into account.
* </li>
* <li>
* REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT=err_threshold_in_dst_SRS_units.
* (GDAL >= 2.2) Use an approximate transformer for the coordinate
* reprojection. Must be used together with
* REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT to be taken into account.
* </li>
* <li>
* AREA_OF_INTEREST=west_lon_deg,south_lat_deg,east_lon_deg,north_lat_deg. (GDAL
* >= 3.0) Area of interest, used to compute the best coordinate operation
* between the source and target SRS. If not specified, the bounding box of the
* source raster will be used.
* </li>
* <li> GEOLOC_BACKMAP_OVERSAMPLE_FACTOR=[0.1,2]. (GDAL >= 3.5) Oversample
* factor used to derive the size of the "backmap" used for geolocation array
* transformers. Default value is 1.3.
* </li>
* <li> GEOLOC_USE_TEMP_DATASETS=YES/NO.
* (GDAL >= 3.5) Whether temporary GeoTIFF datasets should be used to store
* the backmap. The default is NO, that is to use in-memory arrays, unless the
* number of pixels of the geolocation array is greater than 16 megapixels.
* </li>
* <li>
* GEOLOC_ARRAY/SRC_GEOLOC_ARRAY=filename. (GDAL >= 3.5.2) Name of a GDAL
* dataset containing a geolocation array and associated metadata. This is an
* alternative to having geolocation information described in the GEOLOCATION
* metadata domain of the source dataset. The dataset specified may have a
* GEOLOCATION metadata domain containing appropriate metadata, however default
* values are assigned for all omitted items. X_BAND defaults to 1 and Y_BAND to
* 2, however the dataset must contain exactly 2 bands. PIXEL_OFFSET and
* LINE_OFFSET default to 0. PIXEL_STEP and LINE_STEP default to the ratio of
* the width/height of the source dataset divided by the with/height of the
* geolocation array. SRS defaults to the geolocation array dataset's spatial
* reference system if set, otherwise WGS84 is used.
* GEOREFERENCING_CONVENTION is selected from the main metadata domain if it
* is omitted from the GEOLOCATION domain, and if not available
* TOP_LEFT_CORNER is assigned as a default.
* If GEOLOC_ARRAY is set SRC_METHOD
* defaults to GEOLOC_ARRAY.
* </li>
* <li>DST_GEOLOC_ARRAY=filename. (GDAL >= 3.5.2) Name of a
* GDAL dataset that contains at least 2 bands with the X and Y geolocation
* bands. This is an alternative to having geolocation information described in
* the GEOLOCATION metadata domain of the destination dataset. See
* SRC_GEOLOC_ARRAY description for details, assumptions, and defaults. If this
* option is set, DST_METHOD=GEOLOC_ARRAY will be assumed if not set.
* </li>
* <li>GEOLOC_NORMALIZE_LONGITUDE_MINUS_180_PLUS_180=YES/NO. (GDAL >= 3.12.0)
* Whether to force geolocation longitudes into -180,180 when longitude/latitude is
* the coordinate system of the geolocation arrays. The default is to enable this mode
* when the values in the geolocation array are in the -180,180, otherwise NO.
* </li>
* </ul>
*
* The use case for the *_APPROX_ERROR_* options is when defining an approximate
* transformer on top of the GenImgProjTransformer globally is not practical.
* Such a use case is when the source dataset has RPC with a RPC DEM. In such
* case we don't want to use the approximate transformer on the RPC
* transformation, as the RPC DEM generally involves non-linearities that the
* approximate transformer will not detect. In such case, we must a
* non-approximated GenImgProjTransformer, but it might be worthwhile to use
* approximate sub- transformers, for example on coordinate reprojection. For
* example if warping from a source dataset with RPC to a destination dataset
* with a UTM projection, since the inverse UTM transformation is rather costly.
* In which case, one can use the REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT and
* REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT options.
*
* The list of supported options can also be programmatically obtained with
* GDALGetGenImgProjTranformerOptionList().
*
* @param hSrcDS source dataset, or NULL.
* @param hDstDS destination dataset (or NULL).
* @param papszOptions NULL-terminated list of string options (or NULL).
*
* @return handle suitable for use GDALGenImgProjTransform(), and to be
* deallocated with GDALDestroyGenImgProjTransformer() or NULL on failure.
*/
/* clang-format on */
void *GDALCreateGenImgProjTransformer2(GDALDatasetH hSrcDS, GDALDatasetH hDstDS,
CSLConstList papszOptions)
{
GDALValidateOptions(GDALGetGenImgProjTranformerOptionList(), papszOptions,
"option", "transformer options");
double dfWestLongitudeDeg = 0.0;
double dfSouthLatitudeDeg = 0.0;
double dfEastLongitudeDeg = 0.0;
double dfNorthLatitudeDeg = 0.0;
bool bHasAreaOfInterest = false;
if (const char *pszAreaOfInterest =
CSLFetchNameValue(papszOptions, "AREA_OF_INTEREST"))
{
const CPLStringList aosTokens(
CSLTokenizeString2(pszAreaOfInterest, ", ", 0));
if (aosTokens.size() == 4)
{
dfWestLongitudeDeg = CPLAtof(aosTokens[0]);
dfSouthLatitudeDeg = CPLAtof(aosTokens[1]);
dfEastLongitudeDeg = CPLAtof(aosTokens[2]);
dfNorthLatitudeDeg = CPLAtof(aosTokens[3]);
bHasAreaOfInterest = true;
}
}
const char *pszCO = CSLFetchNameValue(papszOptions, "COORDINATE_OPERATION");
const auto SetAxisMapping =
[papszOptions](OGRSpatialReference &oSRS, const char *pszPrefix)
{
const char *pszMapping = CSLFetchNameValue(
papszOptions, std::string(pszPrefix)
.append("_DATA_AXIS_TO_SRS_AXIS_MAPPING")
.c_str());
if (pszMapping)
{
CPLStringList aosTokens(CSLTokenizeString2(pszMapping, ",", 0));
std::vector<int> anMapping;
for (int i = 0; i < aosTokens.size(); ++i)
anMapping.push_back(atoi(aosTokens[i]));
oSRS.SetDataAxisToSRSAxisMapping(anMapping);
}
else
{
const char *pszStrategy = CSLFetchNameValueDef(
papszOptions,
std::string(pszPrefix).append("_AXIS_MAPPING_STRATEGY").c_str(),
"TRADITIONAL_GIS_ORDER");
if (EQUAL(pszStrategy, "TRADITIONAL_GIS_ORDER"))
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
else if (EQUAL(pszStrategy, "AUTHORITY_COMPLIANT"))
oSRS.SetAxisMappingStrategy(OAMS_AUTHORITY_COMPLIANT);
else
{
CPLError(CE_Warning, CPLE_AppDefined,
"Unrecognized value '%s' for %s", pszStrategy,
std::string(pszPrefix)
.append("_AXIS_MAPPING_STRATEGY")
.c_str());
return false;
}
}
return true;
};
/* -------------------------------------------------------------------- */
/* Initialize the transform info. */
/* -------------------------------------------------------------------- */
GDALGenImgProjTransformInfo *psInfo =
GDALCreateGenImgProjTransformerInternal();
const auto DealWithForwardOrInverse =
[bHasAreaOfInterest, &dfWestLongitudeDeg, &dfSouthLatitudeDeg,
&dfEastLongitudeDeg, &dfNorthLatitudeDeg, pszCO, papszOptions,
&SetAxisMapping](GDALGenImgProjTransformPart &part, GDALDatasetH hDS,
const char *pszPrefix, OGRSpatialReference &oSRS,
bool &bCanUseGeoTransform)
{
const int nOrder =
atoi(CSLFetchNameValueDef(papszOptions, "MAX_GCP_ORDER", "0"));
const bool bGCPUseOK =
CPLTestBool(CSLFetchNameValueDef(papszOptions, "GCPS_OK", "YES"));
const int nMinimumGcps = atoi(
CSLFetchNameValueDef(papszOptions, "REFINE_MINIMUM_GCPS", "-1"));
const char *pszRefineTolerance =
CSLFetchNameValue(papszOptions, "REFINE_TOLERANCE");
const bool bRefine = pszRefineTolerance != nullptr;
const double dfTolerance =
pszRefineTolerance ? CPLAtof(pszRefineTolerance) : 0.0;
const std::string osSRSOptionName =
std::string(pszPrefix).append("_SRS");
const char *pszSRS =
CSLFetchNameValue(papszOptions, osSRSOptionName.c_str());
if (pszSRS)
{
if (pszSRS[0] != '\0' &&
oSRS.SetFromUserInput(pszSRS) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to import coordinate system `%s'.", pszSRS);
return false;
}
if (!SetAxisMapping(oSRS, osSRSOptionName.c_str()))
return false;
}
CSLConstList papszMD = nullptr;
GDALRPCInfoV2 sRPCInfo;
bCanUseGeoTransform = false;
const char *pszMethod = CSLFetchNameValue(
papszOptions, std::string(pszPrefix).append("_METHOD").c_str());
if (!pszMethod && EQUAL(pszPrefix, "SRC"))
pszMethod = CSLFetchNameValue(papszOptions, "METHOD");
const char *pszGeolocArray = CSLFetchNameValue(
papszOptions,
std::string(pszPrefix).append("_GEOLOC_ARRAY").c_str());
if (!pszGeolocArray && EQUAL(pszPrefix, "SRC"))
pszGeolocArray = CSLFetchNameValue(papszOptions, "GEOLOC_ARRAY");
if (!pszMethod && pszGeolocArray != nullptr)
pszMethod = "GEOLOC_ARRAY";
/* -------------------------------------------------------------------- */
/* Get forward and inverse geotransform for the source image. */
/* -------------------------------------------------------------------- */
if (hDS == nullptr ||
(pszMethod != nullptr && EQUAL(pszMethod, "NO_GEOTRANSFORM")))
{
part.adfGeoTransform[0] = 0.0;
part.adfGeoTransform[1] = 1.0;
part.adfGeoTransform[2] = 0.0;
part.adfGeoTransform[3] = 0.0;
part.adfGeoTransform[4] = 0.0;
part.adfGeoTransform[5] = 1.0;
memcpy(part.adfInvGeoTransform, part.adfGeoTransform,
sizeof(double) * 6);
}
else if ((pszMethod == nullptr || EQUAL(pszMethod, "GEOTRANSFORM")) &&
GDALGetGeoTransform(hDS, part.adfGeoTransform) == CE_None)
{
if (!GDALInvGeoTransform(part.adfGeoTransform,
part.adfInvGeoTransform))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot invert geotransform");
return false;
}
if (pszSRS == nullptr)
{
auto hSRS = GDALGetSpatialRef(hDS);
if (hSRS)
oSRS = *(OGRSpatialReference::FromHandle(hSRS));
}
if (EQUAL(pszPrefix, "SRC"))
{
if (!bHasAreaOfInterest && pszCO == nullptr && !oSRS.IsEmpty())
{
GDALComputeAreaOfInterest(
&oSRS, part.adfGeoTransform, GDALGetRasterXSize(hDS),
GDALGetRasterYSize(hDS), dfWestLongitudeDeg,
dfSouthLatitudeDeg, dfEastLongitudeDeg,
dfNorthLatitudeDeg);
}
bCanUseGeoTransform = true;
}
}
else if (bGCPUseOK &&
((pszMethod == nullptr && GDALGetGCPCount(hDS) >= 4 &&
GDALGetGCPCount(hDS) < 6) ||
(pszMethod != nullptr &&
EQUAL(pszMethod, "GCP_HOMOGRAPHY"))) &&
GDALGetGCPCount(hDS) > 0)
{
if (pszSRS == nullptr)
{
auto hSRS = GDALGetGCPSpatialRef(hDS);
if (hSRS)
oSRS = *(OGRSpatialReference::FromHandle(hSRS));
}
const auto nGCPCount = GDALGetGCPCount(hDS);
auto pasGCPList = GDALDuplicateGCPs(nGCPCount, GDALGetGCPs(hDS));
GDALGCPAntimeridianUnwrap(nGCPCount, pasGCPList, oSRS,
papszOptions);
part.pTransformArg =
GDALCreateHomographyTransformerFromGCPs(nGCPCount, pasGCPList);
GDALDeinitGCPs(nGCPCount, pasGCPList);
CPLFree(pasGCPList);
if (part.pTransformArg == nullptr)
{
return false;
}
part.pTransformer = GDALHomographyTransform;
}
else if (bGCPUseOK &&
((pszMethod == nullptr && nOrder >= 0) ||
(pszMethod && EQUAL(pszMethod, "GCP_POLYNOMIAL"))) &&
GDALGetGCPCount(hDS) > 0)
{
const int nSanitizedOrder = std::max(0, nOrder);
if (pszSRS == nullptr)
{
auto hSRS = GDALGetGCPSpatialRef(hDS);
if (hSRS)
oSRS = *(OGRSpatialReference::FromHandle(hSRS));
}
const auto nGCPCount = GDALGetGCPCount(hDS);
auto pasGCPList = GDALDuplicateGCPs(nGCPCount, GDALGetGCPs(hDS));
GDALGCPAntimeridianUnwrap(nGCPCount, pasGCPList, oSRS,
papszOptions);
if (bRefine)
{
part.pTransformArg = GDALCreateGCPRefineTransformer(
nGCPCount, pasGCPList, nSanitizedOrder, FALSE, dfTolerance,
nMinimumGcps);
}
else
{
part.pTransformArg = GDALCreateGCPTransformer(
nGCPCount, pasGCPList, nSanitizedOrder, FALSE);
}
GDALDeinitGCPs(nGCPCount, pasGCPList);
CPLFree(pasGCPList);
if (part.pTransformArg == nullptr)
{
return false;
}
part.pTransformer = GDALGCPTransform;
}
else if (bGCPUseOK && GDALGetGCPCount(hDS) > 0 &&
((pszMethod == nullptr && nOrder < 0) ||
(pszMethod && EQUAL(pszMethod, "GCP_TPS"))))
{
if (pszSRS == nullptr)
{
auto hSRS = GDALGetGCPSpatialRef(hDS);
if (hSRS)
oSRS = *(OGRSpatialReference::FromHandle(hSRS));
}
const auto nGCPCount = GDALGetGCPCount(hDS);
auto pasGCPList = GDALDuplicateGCPs(nGCPCount, GDALGetGCPs(hDS));
GDALGCPAntimeridianUnwrap(nGCPCount, pasGCPList, oSRS,
papszOptions);
part.pTransformArg = GDALCreateTPSTransformerInt(
nGCPCount, pasGCPList, FALSE, papszOptions);
GDALDeinitGCPs(nGCPCount, pasGCPList);
CPLFree(pasGCPList);
if (part.pTransformArg == nullptr)
{
return false;
}
part.pTransformer = GDALTPSTransform;
}
else if ((pszMethod == nullptr || EQUAL(pszMethod, "RPC")) &&
(papszMD = GDALGetMetadata(hDS, "RPC")) != nullptr &&
GDALExtractRPCInfoV2(papszMD, &sRPCInfo))
{
CPLStringList aosOptions(papszOptions);
if (!CSLFetchNameValue(papszOptions, "RPC_HEIGHT") &&
!CSLFetchNameValue(papszOptions, "RPC_DEM"))
{
if (const char *pszHEIGHT_DEFAULT =
CSLFetchNameValue(papszMD, "HEIGHT_DEFAULT"))
{
CPLDebug("GDAL",
"For %s, using RPC_HEIGHT = HEIGHT_DEFAULT = %s",
pszPrefix, pszHEIGHT_DEFAULT);
aosOptions.SetNameValue("RPC_HEIGHT", pszHEIGHT_DEFAULT);
}
}
part.pTransformArg = GDALCreateRPCTransformerV2(&sRPCInfo, FALSE, 0,
aosOptions.List());
if (part.pTransformArg == nullptr)
{
return false;
}
part.pTransformer = GDALRPCTransform;
if (pszSRS == nullptr)
{
oSRS.SetFromUserInput(SRS_WKT_WGS84_LAT_LONG);
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
}
}
else if ((pszMethod == nullptr || EQUAL(pszMethod, "GEOLOC_ARRAY")) &&
((papszMD = GDALGetMetadata(hDS, "GEOLOCATION")) != nullptr ||
pszGeolocArray != nullptr))
{
CPLStringList aosGeolocMD; // keep in this scope
if (pszGeolocArray != nullptr)
{
if (papszMD != nullptr)
{
CPLError(
CE_Warning, CPLE_AppDefined,
"Both GEOLOCATION metadata domain on the source "
"dataset "
"and [%s_]GEOLOC_ARRAY transformer option are set. "
"Only using the later.",
pszPrefix);
}
aosGeolocMD = GDALCreateGeolocationMetadata(
hDS, pszGeolocArray,
/* bIsSource= */ EQUAL(pszPrefix, "SRC"));
if (aosGeolocMD.empty())
{
return false;
}
papszMD = aosGeolocMD.List();
}
part.pTransformArg = GDALCreateGeoLocTransformerEx(
hDS, papszMD, FALSE, nullptr, papszOptions);
if (part.pTransformArg == nullptr)
{
return false;
}
part.pTransformer = GDALGeoLocTransform;
if (pszSRS == nullptr)
{
pszSRS = CSLFetchNameValue(papszMD, "SRS");
if (pszSRS)
{
oSRS.SetFromUserInput(pszSRS);
oSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
}
}
}
else if (pszMethod != nullptr && EQUAL(pszPrefix, "SRC"))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unable to compute a %s based transformation between "
"pixel/line and georeferenced coordinates for %s.",
pszMethod, GDALGetDescription(hDS));
return false;
}
else
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unable to compute a transformation between pixel/line "
"and georeferenced coordinates for %s. "
"There is no affine transformation and no GCPs. "
"Specify transformation option %s_METHOD=NO_GEOTRANSFORM "
"to bypass this check.",
GDALGetDescription(hDS), pszPrefix);
return false;
}
/* ---------------------------------------------------------------- */
/* Handle optional source approximation transformer. */
/* ---------------------------------------------------------------- */
if (part.pTransformer)
{
const char *pszApproxErrorFwd = CSLFetchNameValue(
papszOptions, std::string(pszPrefix)
.append("_APPROX_ERROR_IN_SRS_UNIT")
.c_str());
const char *pszApproxErrorReverse = CSLFetchNameValue(
papszOptions, std::string(pszPrefix)
.append("_APPROX_ERROR_IN_PIXEL")
.c_str());
if (pszApproxErrorFwd && pszApproxErrorReverse)
{
void *pArg = GDALCreateApproxTransformer2(
part.pTransformer, part.pTransformArg,
CPLAtof(pszApproxErrorFwd), CPLAtof(pszApproxErrorReverse));
if (pArg == nullptr)
{
return false;
}
part.pTransformArg = pArg;
part.pTransformer = GDALApproxTransform;
GDALApproxTransformerOwnsSubtransformer(part.pTransformArg,
TRUE);
}
}
return true;
};
/* -------------------------------------------------------------------- */
/* Get forward and inverse geotransform for the source image. */
/* -------------------------------------------------------------------- */
bool bCanUseSrcGeoTransform = false;
OGRSpatialReference oSrcSRS;
if (!DealWithForwardOrInverse(psInfo->sSrcParams, hSrcDS, "SRC", oSrcSRS,
bCanUseSrcGeoTransform))
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Get forward and inverse geotransform for destination image. */
/* If we have no destination use a unit transform. */
/* -------------------------------------------------------------------- */
bool bIgnored = false;
OGRSpatialReference oDstSRS;
if (!DealWithForwardOrInverse(psInfo->sDstParams, hDstDS, "DST", oDstSRS,
bIgnored))
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Setup reprojection. */
/* -------------------------------------------------------------------- */
if (CPLFetchBool(papszOptions, "@STRIP_VERT_CS", false))
{
if (oSrcSRS.IsCompound())
{
oSrcSRS.StripVertical();
}
if (oDstSRS.IsCompound())
{
oDstSRS.StripVertical();
}
}
const bool bMayInsertCenterLong =
(bCanUseSrcGeoTransform && !oSrcSRS.IsEmpty() && hSrcDS &&
CPLFetchBool(papszOptions, "INSERT_CENTER_LONG", true));
const char *pszSrcCoordEpoch =
CSLFetchNameValue(papszOptions, "SRC_COORDINATE_EPOCH");
const char *pszDstCoordEpoch =
CSLFetchNameValue(papszOptions, "DST_COORDINATE_EPOCH");
if ((!oSrcSRS.IsEmpty() && !oDstSRS.IsEmpty() &&
(pszSrcCoordEpoch || pszDstCoordEpoch || !oSrcSRS.IsSame(&oDstSRS) ||
(oSrcSRS.IsGeographic() && bMayInsertCenterLong))) ||
pszCO)
{
CPLStringList aosOptions;
if (bMayInsertCenterLong)
{
InsertCenterLong(hSrcDS, &oSrcSRS, &oDstSRS,
CSLFetchNameValue(papszOptions, "TARGET_EXTENT"),
aosOptions);
}
if (CPLFetchBool(papszOptions, "PROMOTE_TO_3D", false))
{
oSrcSRS.PromoteTo3D(nullptr);
oDstSRS.PromoteTo3D(nullptr);
}
if (!(dfWestLongitudeDeg == 0.0 && dfSouthLatitudeDeg == 0.0 &&
dfEastLongitudeDeg == 0.0 && dfNorthLatitudeDeg == 0.0))
{
aosOptions.SetNameValue(
"AREA_OF_INTEREST",
CPLSPrintf("%.16g,%.16g,%.16g,%.16g", dfWestLongitudeDeg,
dfSouthLatitudeDeg, dfEastLongitudeDeg,
dfNorthLatitudeDeg));
}
if (pszCO)
{
aosOptions.SetNameValue("COORDINATE_OPERATION", pszCO);
}
const char *pszCoordEpoch =
CSLFetchNameValue(papszOptions, "COORDINATE_EPOCH");
if (pszCoordEpoch)
{
aosOptions.SetNameValue("COORDINATE_EPOCH", pszCoordEpoch);
}
if (pszSrcCoordEpoch)
{
aosOptions.SetNameValue("SRC_COORDINATE_EPOCH", pszSrcCoordEpoch);
oSrcSRS.SetCoordinateEpoch(CPLAtof(pszSrcCoordEpoch));
}
if (pszDstCoordEpoch)
{
aosOptions.SetNameValue("DST_COORDINATE_EPOCH", pszDstCoordEpoch);
oDstSRS.SetCoordinateEpoch(CPLAtof(pszDstCoordEpoch));
}
if (const char *pszAllowBallpark =
CSLFetchNameValue(papszOptions, "ALLOW_BALLPARK"))
{
aosOptions.SetNameValue("ALLOW_BALLPARK", pszAllowBallpark);
}
if (const char *pszOnlyBest =
CSLFetchNameValue(papszOptions, "ONLY_BEST"))
{
aosOptions.SetNameValue("ONLY_BEST", pszOnlyBest);
}
psInfo->pReprojectArg = GDALCreateReprojectionTransformerEx(
!oSrcSRS.IsEmpty() ? OGRSpatialReference::ToHandle(&oSrcSRS)
: nullptr,
!oDstSRS.IsEmpty() ? OGRSpatialReference::ToHandle(&oDstSRS)
: nullptr,
aosOptions.List());
if (pszCO)
{
psInfo->bHasCustomTransformationPipeline = true;
}
if (psInfo->pReprojectArg == nullptr)
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
psInfo->pReproject = GDALReprojectionTransform;
/* --------------------------------------------------------------------
*/
/* Handle optional reprojection approximation transformer. */
/* --------------------------------------------------------------------
*/
const char *psApproxErrorFwd = CSLFetchNameValue(
papszOptions, "REPROJECTION_APPROX_ERROR_IN_DST_SRS_UNIT");
const char *psApproxErrorReverse = CSLFetchNameValue(
papszOptions, "REPROJECTION_APPROX_ERROR_IN_SRC_SRS_UNIT");
if (psApproxErrorFwd && psApproxErrorReverse)
{
void *pArg = GDALCreateApproxTransformer2(
psInfo->pReproject, psInfo->pReprojectArg,
CPLAtof(psApproxErrorFwd), CPLAtof(psApproxErrorReverse));
if (pArg == nullptr)
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
psInfo->pReprojectArg = pArg;
psInfo->pReproject = GDALApproxTransform;
GDALApproxTransformerOwnsSubtransformer(psInfo->pReprojectArg,
TRUE);
}
}
return psInfo;
}
/************************************************************************/
/* GDALRefreshGenImgProjTransformer() */
/************************************************************************/
void GDALRefreshGenImgProjTransformer(void *hTransformArg)
{
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(hTransformArg);
if (psInfo->pReprojectArg &&
psInfo->bCheckWithInvertPROJ != GetCurrentCheckWithInvertPROJ())
{
psInfo->bCheckWithInvertPROJ = !psInfo->bCheckWithInvertPROJ;
CPLXMLNode *psXML =
GDALSerializeTransformer(psInfo->pReproject, psInfo->pReprojectArg);
GDALDestroyTransformer(psInfo->pReprojectArg);
GDALDeserializeTransformer(psXML, &psInfo->pReproject,
&psInfo->pReprojectArg);
CPLDestroyXMLNode(psXML);
}
}
/************************************************************************/
/* GDALCreateGenImgProjTransformer3() */
/************************************************************************/
/**
* Create image to image transformer.
*
* This function creates a transformation object that maps from pixel/line
* coordinates on one image to pixel/line coordinates on another image. The
* images may potentially be georeferenced in different coordinate systems,
* and may used GCPs to map between their pixel/line coordinates and
* georeferenced coordinates (as opposed to the default assumption that their
* geotransform should be used).
*
* This transformer potentially performs three concatenated transformations.
*
* The first stage is from source image pixel/line coordinates to source
* image georeferenced coordinates, and may be done using the geotransform,
* or if not defined using a polynomial model derived from GCPs. If GCPs
* are used this stage is accomplished using GDALGCPTransform().
*
* The second stage is to change projections from the source coordinate system
* to the destination coordinate system, assuming they differ. This is
* accomplished internally using GDALReprojectionTransform().
*
* The third stage is converting from destination image georeferenced
* coordinates to destination image coordinates. This is done using the
* destination image geotransform, or if not available, using a polynomial
* model derived from GCPs. If GCPs are used this stage is accomplished using
* GDALGCPTransform(). This stage is skipped if hDstDS is NULL when the
* transformation is created.
*
* @param pszSrcWKT source WKT (or NULL).
* @param padfSrcGeoTransform source geotransform (or NULL).
* @param pszDstWKT destination WKT (or NULL).
* @param padfDstGeoTransform destination geotransform (or NULL).
*
* @return handle suitable for use GDALGenImgProjTransform(), and to be
* deallocated with GDALDestroyGenImgProjTransformer() or NULL on failure.
*/
void *GDALCreateGenImgProjTransformer3(const char *pszSrcWKT,
const double *padfSrcGeoTransform,
const char *pszDstWKT,
const double *padfDstGeoTransform)
{
OGRSpatialReference oSrcSRS;
if (pszSrcWKT)
{
oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (pszSrcWKT[0] != '\0' &&
oSrcSRS.importFromWkt(pszSrcWKT) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to import coordinate system `%s'.", pszSrcWKT);
return nullptr;
}
}
OGRSpatialReference oDstSRS;
if (pszDstWKT)
{
oDstSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (pszDstWKT[0] != '\0' &&
oDstSRS.importFromWkt(pszDstWKT) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to import coordinate system `%s'.", pszDstWKT);
return nullptr;
}
}
return GDALCreateGenImgProjTransformer4(
OGRSpatialReference::ToHandle(&oSrcSRS), padfSrcGeoTransform,
OGRSpatialReference::ToHandle(&oDstSRS), padfDstGeoTransform, nullptr);
}
/************************************************************************/
/* GDALCreateGenImgProjTransformer4() */
/************************************************************************/
/**
* Create image to image transformer.
*
* Similar to GDALCreateGenImgProjTransformer3(), except that it takes
* OGRSpatialReferenceH objects and options.
* The options are the ones supported by GDALCreateReprojectionTransformerEx()
*
* @since GDAL 3.0
*/
void *GDALCreateGenImgProjTransformer4(OGRSpatialReferenceH hSrcSRS,
const double *padfSrcGeoTransform,
OGRSpatialReferenceH hDstSRS,
const double *padfDstGeoTransform,
const char *const *papszOptions)
{
/* -------------------------------------------------------------------- */
/* Initialize the transform info. */
/* -------------------------------------------------------------------- */
GDALGenImgProjTransformInfo *psInfo =
GDALCreateGenImgProjTransformerInternal();
/* -------------------------------------------------------------------- */
/* Get forward and inverse geotransform for the source image. */
/* -------------------------------------------------------------------- */
const auto SetParams =
[](GDALGenImgProjTransformPart &part, const double *padfGT)
{
if (padfGT)
{
memcpy(part.adfGeoTransform, padfGT, sizeof(part.adfGeoTransform));
if (!GDALInvGeoTransform(part.adfGeoTransform,
part.adfInvGeoTransform))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot invert geotransform");
return false;
}
}
else
{
part.adfGeoTransform[0] = 0.0;
part.adfGeoTransform[1] = 1.0;
part.adfGeoTransform[2] = 0.0;
part.adfGeoTransform[3] = 0.0;
part.adfGeoTransform[4] = 0.0;
part.adfGeoTransform[5] = 1.0;
memcpy(part.adfInvGeoTransform, part.adfGeoTransform,
sizeof(double) * 6);
}
return true;
};
if (!SetParams(psInfo->sSrcParams, padfSrcGeoTransform))
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
/* -------------------------------------------------------------------- */
/* Setup reprojection. */
/* -------------------------------------------------------------------- */
OGRSpatialReference *poSrcSRS = OGRSpatialReference::FromHandle(hSrcSRS);
OGRSpatialReference *poDstSRS = OGRSpatialReference::FromHandle(hDstSRS);
if (!poSrcSRS->IsEmpty() && !poDstSRS->IsEmpty() &&
!poSrcSRS->IsSame(poDstSRS))
{
psInfo->pReprojectArg =
GDALCreateReprojectionTransformerEx(hSrcSRS, hDstSRS, papszOptions);
if (psInfo->pReprojectArg == nullptr)
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
psInfo->pReproject = GDALReprojectionTransform;
}
/* -------------------------------------------------------------------- */
/* Get forward and inverse geotransform for destination image. */
/* If we have no destination matrix use a unit transform. */
/* -------------------------------------------------------------------- */
if (!SetParams(psInfo->sDstParams, padfDstGeoTransform))
{
GDALDestroyGenImgProjTransformer(psInfo);
return nullptr;
}
return psInfo;
}
/************************************************************************/
/* GDALSetGenImgProjTransformerDstGeoTransform() */
/************************************************************************/
/**
* Set GenImgProj output geotransform.
*
* Normally the "destination geotransform", or transformation between
* georeferenced output coordinates and pixel/line coordinates on the
* destination file is extracted from the destination file by
* GDALCreateGenImgProjTransformer() and stored in the GenImgProj private
* info. However, sometimes it is inconvenient to have an output file
* handle with appropriate geotransform information when creating the
* transformation. For these cases, this function can be used to apply
* the destination geotransform.
*
* @param hTransformArg the handle to update.
* @param padfGeoTransform the destination geotransform to apply (six doubles).
*/
void GDALSetGenImgProjTransformerDstGeoTransform(void *hTransformArg,
const double *padfGeoTransform)
{
VALIDATE_POINTER0(hTransformArg,
"GDALSetGenImgProjTransformerDstGeoTransform");
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(hTransformArg);
memcpy(psInfo->sDstParams.adfGeoTransform, padfGeoTransform,
sizeof(double) * 6);
if (!GDALInvGeoTransform(psInfo->sDstParams.adfGeoTransform,
psInfo->sDstParams.adfInvGeoTransform))
{
CPLError(CE_Failure, CPLE_AppDefined, "Cannot invert geotransform");
}
}
/************************************************************************/
/* GDALDestroyGenImgProjTransformer() */
/************************************************************************/
/**
* GenImgProjTransformer deallocator.
*
* This function is used to deallocate the handle created with
* GDALCreateGenImgProjTransformer().
*
* @param hTransformArg the handle to deallocate.
*/
void GDALDestroyGenImgProjTransformer(void *hTransformArg)
{
if (hTransformArg == nullptr)
return;
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(hTransformArg);
if (psInfo->sSrcParams.pTransformArg != nullptr)
GDALDestroyTransformer(psInfo->sSrcParams.pTransformArg);
if (psInfo->sDstParams.pTransformArg != nullptr)
GDALDestroyTransformer(psInfo->sDstParams.pTransformArg);
if (psInfo->pReprojectArg != nullptr)
GDALDestroyTransformer(psInfo->pReprojectArg);
CPLFree(psInfo);
}
/************************************************************************/
/* GDALGenImgProjTransform() */
/************************************************************************/
/**
* Perform general image reprojection transformation.
*
* Actually performs the transformation setup in
* GDALCreateGenImgProjTransformer(). This function matches the signature
* required by the GDALTransformerFunc(), and more details on the arguments
* can be found in that topic.
*/
#ifdef DEBUG_APPROX_TRANSFORMER
int countGDALGenImgProjTransform = 0;
#endif
int GDALGenImgProjTransform(void *pTransformArgIn, int bDstToSrc,
int nPointCount, double *padfX, double *padfY,
double *padfZ, int *panSuccess)
{
// Sanity check (see issue GH #13498)
if (nullptr == pTransformArgIn)
return FALSE;
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(pTransformArgIn);
#ifdef DEBUG_APPROX_TRANSFORMER
CPLAssert(nPointCount > 0);
countGDALGenImgProjTransform += nPointCount;
#endif
for (int i = 0; i < nPointCount; i++)
{
panSuccess[i] = (padfX[i] != HUGE_VAL && padfY[i] != HUGE_VAL);
}
int ret = TRUE;
/* -------------------------------------------------------------------- */
/* Convert from src (dst) pixel/line to src (dst) */
/* georeferenced coordinates. */
/* -------------------------------------------------------------------- */
{
const auto params = bDstToSrc ? psInfo->sDstParams : psInfo->sSrcParams;
const double *padfGeoTransform = params.adfGeoTransform;
void *pTransformArg = params.pTransformArg;
GDALTransformerFunc pTransformer = params.pTransformer;
if (pTransformArg != nullptr)
{
if (!pTransformer(pTransformArg, FALSE, nPointCount, padfX, padfY,
padfZ, panSuccess))
ret = FALSE;
}
else
{
for (int i = 0; i < nPointCount; i++)
{
if (!panSuccess[i])
continue;
const double dfNewX = padfGeoTransform[0] +
padfX[i] * padfGeoTransform[1] +
padfY[i] * padfGeoTransform[2];
const double dfNewY = padfGeoTransform[3] +
padfX[i] * padfGeoTransform[4] +
padfY[i] * padfGeoTransform[5];
padfX[i] = dfNewX;
padfY[i] = dfNewY;
}
}
}
/* -------------------------------------------------------------------- */
/* Reproject if needed. */
/* -------------------------------------------------------------------- */
if (psInfo->pReprojectArg)
{
if (!psInfo->pReproject(psInfo->pReprojectArg, bDstToSrc, nPointCount,
padfX, padfY, padfZ, panSuccess))
ret = FALSE;
}
/* -------------------------------------------------------------------- */
/* Convert dst (src) georef coordinates back to pixel/line. */
/* -------------------------------------------------------------------- */
{
const auto params = bDstToSrc ? psInfo->sSrcParams : psInfo->sDstParams;
const double *padfInvGeoTransform = params.adfInvGeoTransform;
void *pTransformArg = params.pTransformArg;
GDALTransformerFunc pTransformer = params.pTransformer;
if (pTransformArg != nullptr)
{
if (!pTransformer(pTransformArg, TRUE, nPointCount, padfX, padfY,
padfZ, panSuccess))
ret = FALSE;
}
else
{
for (int i = 0; i < nPointCount; i++)
{
if (!panSuccess[i])
continue;
const double dfNewX = padfInvGeoTransform[0] +
padfX[i] * padfInvGeoTransform[1] +
padfY[i] * padfInvGeoTransform[2];
const double dfNewY = padfInvGeoTransform[3] +
padfX[i] * padfInvGeoTransform[4] +
padfY[i] * padfInvGeoTransform[5];
padfX[i] = dfNewX;
padfY[i] = dfNewY;
}
}
}
return ret;
}
/************************************************************************/
/* GDALTransformLonLatToDestGenImgProjTransformer() */
/************************************************************************/
int GDALTransformLonLatToDestGenImgProjTransformer(void *hTransformArg,
double *pdfX, double *pdfY)
{
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(hTransformArg);
if (psInfo->pReprojectArg == nullptr ||
psInfo->pReproject != GDALReprojectionTransform)
return false;
GDALReprojectionTransformInfo *psReprojInfo =
static_cast<GDALReprojectionTransformInfo *>(psInfo->pReprojectArg);
if (psReprojInfo->poForwardTransform == nullptr ||
psReprojInfo->poForwardTransform->GetSourceCS() == nullptr)
return false;
double z = 0;
int success = true;
auto poSourceCRS = psReprojInfo->poForwardTransform->GetSourceCS();
if (poSourceCRS->IsGeographic() &&
std::fabs(poSourceCRS->GetAngularUnits() -
CPLAtof(SRS_UA_DEGREE_CONV)) < 1e-9)
{
// Optimization to avoid creating a OGRCoordinateTransformation
OGRAxisOrientation eSourceFirstAxisOrient = OAO_Other;
poSourceCRS->GetAxis(nullptr, 0, &eSourceFirstAxisOrient);
const auto &mapping = poSourceCRS->GetDataAxisToSRSAxisMapping();
if ((mapping[0] == 2 && eSourceFirstAxisOrient == OAO_East) ||
(mapping[0] == 1 && eSourceFirstAxisOrient != OAO_East))
{
std::swap(*pdfX, *pdfY);
}
}
else
{
auto poLongLat =
std::unique_ptr<OGRSpatialReference>(poSourceCRS->CloneGeogCS());
if (poLongLat == nullptr)
return false;
poLongLat->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
const bool bCurrentCheckWithInvertProj =
GetCurrentCheckWithInvertPROJ();
if (!bCurrentCheckWithInvertProj)
CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ", "YES");
auto poCT = std::unique_ptr<OGRCoordinateTransformation>(
OGRCreateCoordinateTransformation(poLongLat.get(), poSourceCRS));
if (!bCurrentCheckWithInvertProj)
CPLSetThreadLocalConfigOption("CHECK_WITH_INVERT_PROJ", nullptr);
if (poCT == nullptr)
return false;
poCT->SetEmitErrors(false);
if (!poCT->Transform(1, pdfX, pdfY))
return false;
if (!psInfo->pReproject(psInfo->pReprojectArg, false, 1, pdfX, pdfY, &z,
&success) ||
!success)
{
return false;
}
}
double *padfGeoTransform = psInfo->sDstParams.adfInvGeoTransform;
void *pTransformArg = psInfo->sDstParams.pTransformArg;
GDALTransformerFunc pTransformer = psInfo->sDstParams.pTransformer;
if (pTransformArg != nullptr)
{
if (!pTransformer(pTransformArg, TRUE, 1, pdfX, pdfY, &z, &success) ||
!success)
{
return false;
}
}
else
{
const double dfNewX = padfGeoTransform[0] +
pdfX[0] * padfGeoTransform[1] +
pdfY[0] * padfGeoTransform[2];
const double dfNewY = padfGeoTransform[3] +
pdfX[0] * padfGeoTransform[4] +
pdfY[0] * padfGeoTransform[5];
pdfX[0] = dfNewX;
pdfY[0] = dfNewY;
}
return true;
}
/************************************************************************/
/* GDALSerializeGenImgProjTransformer() */
/************************************************************************/
static CPLXMLNode *GDALSerializeGenImgProjTransformer(void *pTransformArg)
{
GDALGenImgProjTransformInfo *psInfo =
static_cast<GDALGenImgProjTransformInfo *>(pTransformArg);
CPLXMLNode *psTree =
CPLCreateXMLNode(nullptr, CXT_Element, "GenImgProjTransformer");
const auto SerializePart =
[psTree](const char *pszPrefix, const GDALGenImgProjTransformPart &part)
{
char szWork[200] = {};
/* ------------------------------------------------------------- */
/* Handle transformation. */
/* ------------------------------------------------------------- */
if (part.pTransformArg != nullptr)
{
CPLXMLNode *psTransformer =
GDALSerializeTransformer(part.pTransformer, part.pTransformArg);
if (psTransformer != nullptr)
{
CPLXMLNode *psTransformerContainer = CPLCreateXMLNode(
psTree, CXT_Element,
CPLSPrintf("%s%s", pszPrefix, psTransformer->pszValue));
CPLAddXMLChild(psTransformerContainer, psTransformer);
}
}
/* ------------------------------------------------------------- */
/* Handle geotransforms. */
/* ------------------------------------------------------------- */
else
{
CPLsnprintf(szWork, sizeof(szWork),
"%.17g,%.17g,%.17g,%.17g,%.17g,%.17g",
part.adfGeoTransform[0], part.adfGeoTransform[1],
part.adfGeoTransform[2], part.adfGeoTransform[3],
part.adfGeoTransform[4], part.adfGeoTransform[5]);
CPLCreateXMLElementAndValue(
psTree, CPLSPrintf("%sGeoTransform", pszPrefix), szWork);
CPLsnprintf(szWork, sizeof(szWork),
"%.17g,%.17g,%.17g,%.17g,%.17g,%.17g",
part.adfInvGeoTransform[0], part.adfInvGeoTransform[1],
part.adfInvGeoTransform[2], part.adfInvGeoTransform[3],
part.adfInvGeoTransform[4], part.adfInvGeoTransform[5]);
CPLCreateXMLElementAndValue(
psTree, CPLSPrintf("%sInvGeoTransform", pszPrefix), szWork);
}
};
SerializePart("Src", psInfo->sSrcParams);
SerializePart("Dst", psInfo->sDstParams);
/* -------------------------------------------------------------------- */
/* Do we have a reprojection transformer? */
/* -------------------------------------------------------------------- */
if (psInfo->pReprojectArg != nullptr)
{
CPLXMLNode *psTransformerContainer =
CPLCreateXMLNode(psTree, CXT_Element, "ReprojectTransformer");
CPLXMLNode *psTransformer =
GDALSerializeTransformer(psInfo->pReproject, psInfo->pReprojectArg);
if (psTransformer != nullptr)
CPLAddXMLChild(psTransformerContainer, psTransformer);
}
return psTree;
}
/************************************************************************/
/* GDALDeserializeGeoTransform() */
/************************************************************************/
static void GDALDeserializeGeoTransform(const char *pszGT,
double adfGeoTransform[6])
{
CPLsscanf(pszGT, "%lf,%lf,%lf,%lf,%lf,%lf", adfGeoTransform + 0,
adfGeoTransform + 1, adfGeoTransform + 2, adfGeoTransform + 3,
adfGeoTransform + 4, adfGeoTransform + 5);
}
/************************************************************************/
/* GDALDeserializeGenImgProjTransformer() */
/************************************************************************/
void *GDALDeserializeGenImgProjTransformer(CPLXMLNode *psTree)
{
/* -------------------------------------------------------------------- */
/* Initialize the transform info. */
/* -------------------------------------------------------------------- */
GDALGenImgProjTransformInfo *psInfo =
GDALCreateGenImgProjTransformerInternal();
const auto DeserializePart =
[psTree](const char *pszPrefix, GDALGenImgProjTransformPart &part)
{
/* ----------------------------------------------------------------- */
/* Geotransform */
/* ----------------------------------------------------------------- */
if (const auto psGTNode =
CPLGetXMLNode(psTree, CPLSPrintf("%sGeoTransform", pszPrefix)))
{
GDALDeserializeGeoTransform(CPLGetXMLValue(psGTNode, "", ""),
part.adfGeoTransform);
if (const auto psInvGTNode = CPLGetXMLNode(
psTree, CPLSPrintf("%sInvGeoTransform", pszPrefix)))
{
GDALDeserializeGeoTransform(CPLGetXMLValue(psInvGTNode, "", ""),
part.adfInvGeoTransform);
}
else
{
if (!GDALInvGeoTransform(part.adfGeoTransform,
part.adfInvGeoTransform))
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot invert geotransform");
}
}
}
/* ---------------------------------------------------------------- */
/* Transform */
/* ---------------------------------------------------------------- */
else
{
for (CPLXMLNode *psIter = psTree->psChild; psIter != nullptr;
psIter = psIter->psNext)
{
if (psIter->eType == CXT_Element &&
STARTS_WITH_CI(psIter->pszValue, pszPrefix))
{
GDALDeserializeTransformer(psIter->psChild,
&part.pTransformer,
&part.pTransformArg);
break;
}
}
}
};
DeserializePart("Src", psInfo->sSrcParams);
DeserializePart("Dst", psInfo->sDstParams);
/* -------------------------------------------------------------------- */
/* Reproject transformer */
/* -------------------------------------------------------------------- */
CPLXMLNode *psSubtree = CPLGetXMLNode(psTree, "ReprojectTransformer");
if (psSubtree != nullptr && psSubtree->psChild != nullptr)
{
GDALDeserializeTransformer(psSubtree->psChild, &psInfo->pReproject,
&psInfo->pReprojectArg);
}
return psInfo;
}
/************************************************************************/
/* GDALCreateReprojectionTransformer() */
/************************************************************************/
/**
* Create reprojection transformer.
*
* Creates a callback data structure suitable for use with
* GDALReprojectionTransformation() to represent a transformation from
* one geographic or projected coordinate system to another. On input
* the coordinate systems are described in OpenGIS WKT format.
*
* Internally the OGRCoordinateTransformation object is used to implement
* the reprojection.
*
* @param pszSrcWKT the coordinate system for the source coordinate system.
* @param pszDstWKT the coordinate system for the destination coordinate
* system.
*
* @return Handle for use with GDALReprojectionTransform(), or NULL if the
* system fails to initialize the reprojection.
**/
void *GDALCreateReprojectionTransformer(const char *pszSrcWKT,
const char *pszDstWKT)
{
/* -------------------------------------------------------------------- */
/* Ingest the SRS definitions. */
/* -------------------------------------------------------------------- */
OGRSpatialReference oSrcSRS;
oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (oSrcSRS.importFromWkt(pszSrcWKT) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to import coordinate system `%s'.", pszSrcWKT);
return nullptr;
}
OGRSpatialReference oDstSRS;
oDstSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (oDstSRS.importFromWkt(pszDstWKT) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Failed to import coordinate system `%s'.", pszSrcWKT);
return nullptr;
}
return GDALCreateReprojectionTransformerEx(
OGRSpatialReference::ToHandle(&oSrcSRS),
OGRSpatialReference::ToHandle(&oDstSRS), nullptr);
}
/************************************************************************/
/* GDALCreateReprojectionTransformerEx() */
/************************************************************************/
/**
* Create reprojection transformer.
*
* Creates a callback data structure suitable for use with
* GDALReprojectionTransformation() to represent a transformation from
* one geographic or projected coordinate system to another.
*
* Internally the OGRCoordinateTransformation object is used to implement
* the reprojection.
*
* @param hSrcSRS the coordinate system for the source coordinate system.
* @param hDstSRS the coordinate system for the destination coordinate
* system.
* @param papszOptions NULL-terminated list of options, or NULL. Currently
* supported options are:
* <ul>
* <li>AREA_OF_INTEREST=west_long,south_lat,east_long,north_lat: Values in
* degrees. longitudes in [-180,180], latitudes in [-90,90].</li>
* <li>COORDINATE_OPERATION=string: PROJ or WKT string representing a
* coordinate operation, overriding the default computed transformation.</li>
* <li>COORDINATE_EPOCH=decimal_year: Coordinate epoch, expressed as a
* decimal year. Useful for time-dependent coordinate operations.</li>
* <li> SRC_COORDINATE_EPOCH: (GDAL >= 3.4) Coordinate epoch of source CRS,
* expressed as a decimal year. Useful for time-dependent coordinate
*operations.</li>
* <li> DST_COORDINATE_EPOCH: (GDAL >= 3.4) Coordinate epoch
*of target CRS, expressed as a decimal year. Useful for time-dependent
*coordinate operations.</li>
* <li> ALLOW_BALLPARK=YES/NO: (GDAL >= 3.11) Whether ballpark coordinate
* operations are allowed. Defaults to YES.</li>
* <li> ONLY_BEST=YES/NO/AUTO: (GDAL >= 3.11) By default (at least in the
* PROJ 9.x series), PROJ may use coordinate
* operations that are not the "best" if resources (typically grids) needed
* to use them are missing. It will then fallback to other coordinate operations
* that have a lesser accuracy, for example using Helmert transformations,
* or in the absence of such operations, to ones with potential very rough
* accuracy, using "ballpark" transformations
* (see https://proj.org/glossary.html).
* When calling this method with YES, PROJ will only consider the
* "best" operation, and error out (at Transform() time) if they cannot be
* used.
* This method may be used together with ALLOW_BALLPARK=NO to
* only allow best operations that have a known accuracy.
* Note that this method has no effect on PROJ versions before 9.2.
* The default value for this option can be also set with the
* PROJ_ONLY_BEST_DEFAULT environment variable, or with the "only_best_default"
* setting of proj.ini. Calling SetOnlyBest() overrides such default value.</li>
* </ul>
*
* @return Handle for use with GDALReprojectionTransform(), or NULL if the
* system fails to initialize the reprojection.
*
* @since GDAL 3.0
**/
void *GDALCreateReprojectionTransformerEx(OGRSpatialReferenceH hSrcSRS,
OGRSpatialReferenceH hDstSRS,
const char *const *papszOptions)
{
OGRSpatialReference *poSrcSRS = OGRSpatialReference::FromHandle(hSrcSRS);
OGRSpatialReference *poDstSRS = OGRSpatialReference::FromHandle(hDstSRS);
/* -------------------------------------------------------------------- */
/* Build the forward coordinate transformation. */
/* -------------------------------------------------------------------- */
double dfWestLongitudeDeg = 0.0;
double dfSouthLatitudeDeg = 0.0;
double dfEastLongitudeDeg = 0.0;
double dfNorthLatitudeDeg = 0.0;
const char *pszBBOX = CSLFetchNameValue(papszOptions, "AREA_OF_INTEREST");
if (pszBBOX)
{
char **papszTokens = CSLTokenizeString2(pszBBOX, ",", 0);
if (CSLCount(papszTokens) == 4)
{
dfWestLongitudeDeg = CPLAtof(papszTokens[0]);
dfSouthLatitudeDeg = CPLAtof(papszTokens[1]);
dfEastLongitudeDeg = CPLAtof(papszTokens[2]);
dfNorthLatitudeDeg = CPLAtof(papszTokens[3]);
}
CSLDestroy(papszTokens);
}
const char *pszCO = CSLFetchNameValue(papszOptions, "COORDINATE_OPERATION");
OGRCoordinateTransformationOptions optionsFwd;
if (!(dfWestLongitudeDeg == 0.0 && dfSouthLatitudeDeg == 0.0 &&
dfEastLongitudeDeg == 0.0 && dfNorthLatitudeDeg == 0.0))
{
optionsFwd.SetAreaOfInterest(dfWestLongitudeDeg, dfSouthLatitudeDeg,
dfEastLongitudeDeg, dfNorthLatitudeDeg);
}
if (pszCO)
{
optionsFwd.SetCoordinateOperation(pszCO, false);
}
const char *pszCENTER_LONG = CSLFetchNameValue(papszOptions, "CENTER_LONG");
if (pszCENTER_LONG)
{
optionsFwd.SetSourceCenterLong(CPLAtof(pszCENTER_LONG));
}
optionsFwd.SetBallparkAllowed(CPLTestBool(
CSLFetchNameValueDef(papszOptions, "ALLOW_BALLPARK", "YES")));
const char *pszOnlyBest =
CSLFetchNameValueDef(papszOptions, "ONLY_BEST", "AUTO");
if (!EQUAL(pszOnlyBest, "AUTO"))
{
optionsFwd.SetOnlyBest(CPLTestBool(pszOnlyBest));
}
OGRCoordinateTransformation *poForwardTransform =
OGRCreateCoordinateTransformation(poSrcSRS, poDstSRS, optionsFwd);
if (poForwardTransform == nullptr)
// OGRCreateCoordinateTransformation() will report errors on its own.
return nullptr;
poForwardTransform->SetEmitErrors(false);
/* -------------------------------------------------------------------- */
/* Create a structure to hold the transform info, and also */
/* build reverse transform. We assume that if the forward */
/* transform can be created, then so can the reverse one. */
/* -------------------------------------------------------------------- */
GDALReprojectionTransformInfo *psInfo = new GDALReprojectionTransformInfo();
psInfo->papszOptions = CSLDuplicate(papszOptions);
psInfo->poForwardTransform = poForwardTransform;
psInfo->dfTime = CPLAtof(CSLFetchNameValueDef(
papszOptions, "COORDINATE_EPOCH",
CSLFetchNameValueDef(
papszOptions, "DST_COORDINATE_EPOCH",
CSLFetchNameValueDef(papszOptions, "SRC_COORDINATE_EPOCH", "0"))));
psInfo->poReverseTransform = poForwardTransform->GetInverse();
if (psInfo->poReverseTransform)
psInfo->poReverseTransform->SetEmitErrors(false);
memcpy(psInfo->sTI.abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE));
psInfo->sTI.pszClassName = GDAL_REPROJECTION_TRANSFORMER_CLASS_NAME;
psInfo->sTI.pfnTransform = GDALReprojectionTransform;
psInfo->sTI.pfnCleanup = GDALDestroyReprojectionTransformer;
psInfo->sTI.pfnSerialize = GDALSerializeReprojectionTransformer;
return psInfo;
}
/************************************************************************/
/* GDALDestroyReprojectionTransformer() */
/************************************************************************/
/**
* Destroy reprojection transformation.
*
* @param pTransformArg the transformation handle returned by
* GDALCreateReprojectionTransformer().
*/
void GDALDestroyReprojectionTransformer(void *pTransformArg)
{
if (pTransformArg == nullptr)
return;
GDALReprojectionTransformInfo *psInfo =
static_cast<GDALReprojectionTransformInfo *>(pTransformArg);
if (psInfo->poForwardTransform)
OGRCoordinateTransformation::DestroyCT(psInfo->poForwardTransform);
if (psInfo->poReverseTransform)
OGRCoordinateTransformation::DestroyCT(psInfo->poReverseTransform);
CSLDestroy(psInfo->papszOptions);
delete psInfo;
}
/************************************************************************/
/* GDALReprojectionTransform() */
/************************************************************************/
/**
* Perform reprojection transformation.
*
* Actually performs the reprojection transformation described in
* GDALCreateReprojectionTransformer(). This function matches the
* GDALTransformerFunc() signature. Details of the arguments are described
* there.
*/
int GDALReprojectionTransform(void *pTransformArg, int bDstToSrc,
int nPointCount, double *padfX, double *padfY,
double *padfZ, int *panSuccess)
{
GDALReprojectionTransformInfo *psInfo =
static_cast<GDALReprojectionTransformInfo *>(pTransformArg);
int bSuccess;
std::vector<double> adfTime;
double *padfT = nullptr;
if (psInfo->dfTime != 0.0 && nPointCount > 0)
{
adfTime.resize(nPointCount, psInfo->dfTime);
padfT = &adfTime[0];
}
if (bDstToSrc)
{
if (psInfo->poReverseTransform == nullptr)
{
CPLError(
CE_Failure, CPLE_AppDefined,
"Inverse coordinate transformation cannot be instantiated");
if (panSuccess)
{
for (int i = 0; i < nPointCount; i++)
panSuccess[i] = FALSE;
}
bSuccess = false;
}
else
{
bSuccess = psInfo->poReverseTransform->Transform(
nPointCount, padfX, padfY, padfZ, padfT, panSuccess);
}
}
else
bSuccess = psInfo->poForwardTransform->Transform(
nPointCount, padfX, padfY, padfZ, padfT, panSuccess);
return bSuccess;
}
/************************************************************************/
/* GDALSerializeReprojectionTransformer() */
/************************************************************************/
static CPLXMLNode *GDALSerializeReprojectionTransformer(void *pTransformArg)
{
CPLXMLNode *psTree;
GDALReprojectionTransformInfo *psInfo =
static_cast<GDALReprojectionTransformInfo *>(pTransformArg);
psTree = CPLCreateXMLNode(nullptr, CXT_Element, "ReprojectionTransformer");
/* -------------------------------------------------------------------- */
/* Handle SourceCS. */
/* -------------------------------------------------------------------- */
const auto ExportToWkt = [](const OGRSpatialReference *poSRS)
{
// Try first in WKT1 for backward compat
{
char *pszWKT = nullptr;
const char *const apszOptions[] = {"FORMAT=WKT1", nullptr};
CPLErrorHandlerPusher oHandler(CPLQuietErrorHandler);
CPLErrorStateBackuper oBackuper;
if (poSRS->exportToWkt(&pszWKT, apszOptions) == OGRERR_NONE)
{
std::string osRet(pszWKT);
CPLFree(pszWKT);
return osRet;
}
CPLFree(pszWKT);
}
char *pszWKT = nullptr;
const char *const apszOptions[] = {"FORMAT=WKT2_2019", nullptr};
if (poSRS->exportToWkt(&pszWKT, apszOptions) == OGRERR_NONE)
{
std::string osRet(pszWKT);
CPLFree(pszWKT);
return osRet;
}
CPLFree(pszWKT);
return std::string();
};
auto poSRS = psInfo->poForwardTransform->GetSourceCS();
if (poSRS)
{
const auto osWKT = ExportToWkt(poSRS);
CPLCreateXMLElementAndValue(psTree, "SourceSRS", osWKT.c_str());
}
/* -------------------------------------------------------------------- */
/* Handle DestinationCS. */
/* -------------------------------------------------------------------- */
poSRS = psInfo->poForwardTransform->GetTargetCS();
if (poSRS)
{
const auto osWKT = ExportToWkt(poSRS);
CPLCreateXMLElementAndValue(psTree, "TargetSRS", osWKT.c_str());
}
/* -------------------------------------------------------------------- */
/* Serialize options. */
/* -------------------------------------------------------------------- */
if (psInfo->papszOptions)
{
CPLXMLNode *psOptions =
CPLCreateXMLNode(psTree, CXT_Element, "Options");
for (auto iter = psInfo->papszOptions; *iter != nullptr; ++iter)
{
char *pszKey = nullptr;
const char *pszValue = CPLParseNameValue(*iter, &pszKey);
if (pszKey && pszValue)
{
auto elt =
CPLCreateXMLElementAndValue(psOptions, "Option", pszValue);
CPLAddXMLAttributeAndValue(elt, "key", pszKey);
}
CPLFree(pszKey);
}
}
return psTree;
}
/************************************************************************/
/* GDALDeserializeReprojectionTransformer() */
/************************************************************************/
static void *GDALDeserializeReprojectionTransformer(CPLXMLNode *psTree)
{
const char *pszSourceSRS = CPLGetXMLValue(psTree, "SourceSRS", nullptr);
const char *pszTargetSRS = CPLGetXMLValue(psTree, "TargetSRS", nullptr);
char *pszSourceWKT = nullptr, *pszTargetWKT = nullptr;
void *pResult = nullptr;
OGRSpatialReference oSrcSRS;
OGRSpatialReference oDstSRS;
oSrcSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
oDstSRS.SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
if (pszSourceSRS != nullptr)
{
oSrcSRS.SetFromUserInput(pszSourceSRS);
}
if (pszTargetSRS != nullptr)
{
oDstSRS.SetFromUserInput(pszTargetSRS);
}
CPLStringList aosList;
const CPLXMLNode *psOptions = CPLGetXMLNode(psTree, "Options");
if (psOptions)
{
for (auto iter = psOptions->psChild; iter; iter = iter->psNext)
{
if (iter->eType == CXT_Element &&
strcmp(iter->pszValue, "Option") == 0)
{
const char *pszKey = CPLGetXMLValue(iter, "key", nullptr);
const char *pszValue = CPLGetXMLValue(iter, nullptr, nullptr);
if (pszKey && pszValue)
{
aosList.SetNameValue(pszKey, pszValue);
}
}
}
}
pResult = GDALCreateReprojectionTransformerEx(
!oSrcSRS.IsEmpty() ? OGRSpatialReference::ToHandle(&oSrcSRS) : nullptr,
!oDstSRS.IsEmpty() ? OGRSpatialReference::ToHandle(&oDstSRS) : nullptr,
aosList.List());
CPLFree(pszSourceWKT);
CPLFree(pszTargetWKT);
return pResult;
}
/************************************************************************/
/* ==================================================================== */
/* Approximate transformer. */
/* ==================================================================== */
/************************************************************************/
/************************************************************************/
/* GDALCreateSimilarApproxTransformer() */
/************************************************************************/
static void *GDALCreateSimilarApproxTransformer(void *hTransformArg,
double dfSrcRatioX,
double dfSrcRatioY)
{
VALIDATE_POINTER1(hTransformArg, "GDALCreateSimilarApproxTransformer",
nullptr);
GDALApproxTransformInfo *psInfo =
static_cast<GDALApproxTransformInfo *>(hTransformArg);
void *pBaseCBData = GDALCreateSimilarTransformer(psInfo->pBaseCBData,
dfSrcRatioX, dfSrcRatioY);
if (pBaseCBData == nullptr)
{
return nullptr;
}
GDALApproxTransformInfo *psClonedInfo =
static_cast<GDALApproxTransformInfo *>(GDALCreateApproxTransformer2(
psInfo->pfnBaseTransformer, pBaseCBData, psInfo->dfMaxErrorForward,
psInfo->dfMaxErrorReverse));
psClonedInfo->bOwnSubtransformer = TRUE;
return psClonedInfo;
}
/************************************************************************/
/* GDALSerializeApproxTransformer() */
/************************************************************************/
static CPLXMLNode *GDALSerializeApproxTransformer(void *pTransformArg)
{
CPLXMLNode *psTree;
GDALApproxTransformInfo *psInfo =
static_cast<GDALApproxTransformInfo *>(pTransformArg);
psTree = CPLCreateXMLNode(nullptr, CXT_Element, "ApproxTransformer");
/* -------------------------------------------------------------------- */
/* Attach max error. */
/* -------------------------------------------------------------------- */
if (psInfo->dfMaxErrorForward == psInfo->dfMaxErrorReverse)
{
CPLCreateXMLElementAndValue(
psTree, "MaxError",
CPLString().Printf("%g", psInfo->dfMaxErrorForward));
}
else
{
CPLCreateXMLElementAndValue(
psTree, "MaxErrorForward",
CPLString().Printf("%g", psInfo->dfMaxErrorForward));
CPLCreateXMLElementAndValue(
psTree, "MaxErrorReverse",
CPLString().Printf("%g", psInfo->dfMaxErrorReverse));
}
/* -------------------------------------------------------------------- */
/* Capture underlying transformer. */
/* -------------------------------------------------------------------- */
CPLXMLNode *psTransformerContainer =
CPLCreateXMLNode(psTree, CXT_Element, "BaseTransformer");
CPLXMLNode *psTransformer = GDALSerializeTransformer(
psInfo->pfnBaseTransformer, psInfo->pBaseCBData);
if (psTransformer != nullptr)
CPLAddXMLChild(psTransformerContainer, psTransformer);
return psTree;
}
/************************************************************************/
/* GDALCreateApproxTransformer() */
/************************************************************************/
/**
* Create an approximating transformer.
*
* This function creates a context for an approximated transformer. Basically
* a high precision transformer is supplied as input and internally linear
* approximations are computed to generate results to within a defined
* precision.
*
* The approximation is actually done at the point where GDALApproxTransform()
* calls are made, and depend on the assumption that they are roughly linear.
* The first and last point passed in must be the extreme values and the
* intermediate values should describe a curve between the end points. The
* approximator transforms and centers using the approximate transformer, and
* then compares the true middle transformed value to a linear approximation
* based on the end points. If the error is within the supplied threshold then
* the end points are used to linearly approximate all the values otherwise the
* input points are split into two smaller sets, and the function is recursively
* called until a sufficiently small set of points is found that the linear
* approximation is OK, or that all the points are exactly computed.
*
* This function is very suitable for approximating transformation results
* from output pixel/line space to input coordinates for warpers that operate
* on one input scanline at a time. Care should be taken using it in other
* circumstances as little internal validation is done in order to keep things
* fast.
*
* @param pfnBaseTransformer the high precision transformer which should be
* approximated.
* @param pBaseTransformArg the callback argument for the high precision
* transformer.
* @param dfMaxError the maximum cartesian error in the "output" space that
* is to be accepted in the linear approximation, evaluated as a Manhattan
* distance.
*
* @return callback pointer suitable for use with GDALApproxTransform(). It
* should be deallocated with GDALDestroyApproxTransformer().
*/
void *GDALCreateApproxTransformer(GDALTransformerFunc pfnBaseTransformer,
void *pBaseTransformArg, double dfMaxError)
{
return GDALCreateApproxTransformer2(pfnBaseTransformer, pBaseTransformArg,
dfMaxError, dfMaxError);
}
static void *
GDALCreateApproxTransformer2(GDALTransformerFunc pfnBaseTransformer,
void *pBaseTransformArg, double dfMaxErrorForward,
double dfMaxErrorReverse)
{
GDALApproxTransformInfo *psATInfo = new GDALApproxTransformInfo;
psATInfo->pfnBaseTransformer = pfnBaseTransformer;
psATInfo->pBaseCBData = pBaseTransformArg;
psATInfo->dfMaxErrorForward = dfMaxErrorForward;
psATInfo->dfMaxErrorReverse = dfMaxErrorReverse;
psATInfo->bOwnSubtransformer = FALSE;
memcpy(psATInfo->sTI.abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE));
psATInfo->sTI.pszClassName = GDAL_APPROX_TRANSFORMER_CLASS_NAME;
psATInfo->sTI.pfnTransform = GDALApproxTransform;
psATInfo->sTI.pfnCleanup = GDALDestroyApproxTransformer;
psATInfo->sTI.pfnSerialize = GDALSerializeApproxTransformer;
psATInfo->sTI.pfnCreateSimilar = GDALCreateSimilarApproxTransformer;
return psATInfo;
}
/************************************************************************/
/* GDALApproxTransformerOwnsSubtransformer() */
/************************************************************************/
/** Set bOwnSubtransformer flag */
void GDALApproxTransformerOwnsSubtransformer(void *pCBData, int bOwnFlag)
{
GDALApproxTransformInfo *psATInfo =
static_cast<GDALApproxTransformInfo *>(pCBData);
psATInfo->bOwnSubtransformer = bOwnFlag;
}
/************************************************************************/
/* GDALDestroyApproxTransformer() */
/************************************************************************/
/**
* Cleanup approximate transformer.
*
* Deallocates the resources allocated by GDALCreateApproxTransformer().
*
* @param pCBData callback data originally returned by
* GDALCreateApproxTransformer().
*/
void GDALDestroyApproxTransformer(void *pCBData)
{
if (pCBData == nullptr)
return;
GDALApproxTransformInfo *psATInfo =
static_cast<GDALApproxTransformInfo *>(pCBData);
if (psATInfo->bOwnSubtransformer)
GDALDestroyTransformer(psATInfo->pBaseCBData);
delete psATInfo;
}
/************************************************************************/
/* GDALRefreshApproxTransformer() */
/************************************************************************/
void GDALRefreshApproxTransformer(void *hTransformArg)
{
GDALApproxTransformInfo *psInfo =
static_cast<GDALApproxTransformInfo *>(hTransformArg);
if (GDALIsTransformer(psInfo->pBaseCBData,
GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
GDALRefreshGenImgProjTransformer(psInfo->pBaseCBData);
}
}
/************************************************************************/
/* GDALApproxTransformInternal() */
/************************************************************************/
static int GDALApproxTransformInternal(void *pCBData, int bDstToSrc,
int nPoints, double *x, double *y,
double *z, int *panSuccess,
// SME = Start, Middle, End.
const double xSMETransformed[3],
const double ySMETransformed[3],
const double zSMETransformed[3])
{
GDALApproxTransformInfo *psATInfo =
static_cast<GDALApproxTransformInfo *>(pCBData);
const int nMiddle = (nPoints - 1) / 2;
#ifdef notdef_sanify_check
{
double x2[3] = {x[0], x[nMiddle], x[nPoints - 1]};
double y2[3] = {y[0], y[nMiddle], y[nPoints - 1]};
double z2[3] = {z[0], z[nMiddle], z[nPoints - 1]};
int anSuccess2[3] = {};
const int bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, 3, x2, y2, z2, anSuccess2);
CPLAssert(bSuccess);
CPLAssert(anSuccess2[0]);
CPLAssert(anSuccess2[1]);
CPLAssert(anSuccess2[2]);
CPLAssert(x2[0] == xSMETransformed[0]);
CPLAssert(y2[0] == ySMETransformed[0]);
CPLAssert(z2[0] == zSMETransformed[0]);
CPLAssert(x2[1] == xSMETransformed[1]);
CPLAssert(y2[1] == ySMETransformed[1]);
CPLAssert(z2[1] == zSMETransformed[1]);
CPLAssert(x2[2] == xSMETransformed[2]);
CPLAssert(y2[2] == ySMETransformed[2]);
CPLAssert(z2[2] == zSMETransformed[2]);
}
#endif
#ifdef DEBUG_APPROX_TRANSFORMER
fprintf(stderr, "start (%.3f,%.3f) -> (%.3f,%.3f)\n", /*ok*/
x[0], y[0], xSMETransformed[0], ySMETransformed[0]);
fprintf(stderr, "middle (%.3f,%.3f) -> (%.3f,%.3f)\n", /*ok*/
x[nMiddle], y[nMiddle], xSMETransformed[1], ySMETransformed[1]);
fprintf(stderr, "end (%.3f,%.3f) -> (%.3f,%.3f)\n", /*ok*/
x[nPoints - 1], y[nPoints - 1], xSMETransformed[2],
ySMETransformed[2]);
#endif
/* -------------------------------------------------------------------- */
/* Is the error at the middle acceptable relative to an */
/* interpolation of the middle position? */
/* -------------------------------------------------------------------- */
const double dfDeltaX =
(xSMETransformed[2] - xSMETransformed[0]) / (x[nPoints - 1] - x[0]);
const double dfDeltaY =
(ySMETransformed[2] - ySMETransformed[0]) / (x[nPoints - 1] - x[0]);
const double dfDeltaZ =
(zSMETransformed[2] - zSMETransformed[0]) / (x[nPoints - 1] - x[0]);
const double dfError =
fabs((xSMETransformed[0] + dfDeltaX * (x[nMiddle] - x[0])) -
xSMETransformed[1]) +
fabs((ySMETransformed[0] + dfDeltaY * (x[nMiddle] - x[0])) -
ySMETransformed[1]);
const double dfMaxError =
(bDstToSrc) ? psATInfo->dfMaxErrorReverse : psATInfo->dfMaxErrorForward;
if (dfError > dfMaxError)
{
#if DEBUG_VERBOSE
CPLDebug("GDAL",
"ApproxTransformer - "
"error %g over threshold %g, subdivide %d points.",
dfError, dfMaxError, nPoints);
#endif
double xMiddle[3] = {x[(nMiddle - 1) / 2], x[nMiddle - 1],
x[nMiddle + (nPoints - nMiddle - 1) / 2]};
double yMiddle[3] = {y[(nMiddle - 1) / 2], y[nMiddle - 1],
y[nMiddle + (nPoints - nMiddle - 1) / 2]};
double zMiddle[3] = {z[(nMiddle - 1) / 2], z[nMiddle - 1],
z[nMiddle + (nPoints - nMiddle - 1) / 2]};
const bool bUseBaseTransformForHalf1 =
nMiddle <= 5 || y[0] != y[nMiddle - 1] ||
y[0] != y[(nMiddle - 1) / 2] || x[0] == x[nMiddle - 1] ||
x[0] == x[(nMiddle - 1) / 2];
const bool bUseBaseTransformForHalf2 =
nPoints - nMiddle <= 5 || y[nMiddle] != y[nPoints - 1] ||
y[nMiddle] != y[nMiddle + (nPoints - nMiddle - 1) / 2] ||
x[nMiddle] == x[nPoints - 1] ||
x[nMiddle] == x[nMiddle + (nPoints - nMiddle - 1) / 2];
int anSuccess2[3] = {};
int bSuccess = FALSE;
if (!bUseBaseTransformForHalf1 && !bUseBaseTransformForHalf2)
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, 3, xMiddle, yMiddle, zMiddle,
anSuccess2);
else if (!bUseBaseTransformForHalf1)
{
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, 2, xMiddle, yMiddle, zMiddle,
anSuccess2);
anSuccess2[2] = TRUE;
}
else if (!bUseBaseTransformForHalf2)
{
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, 1, xMiddle + 2, yMiddle + 2,
zMiddle + 2, anSuccess2 + 2);
anSuccess2[0] = TRUE;
anSuccess2[1] = TRUE;
}
if (!bSuccess || !anSuccess2[0] || !anSuccess2[1] || !anSuccess2[2])
{
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, nMiddle - 1, x + 1, y + 1,
z + 1, panSuccess + 1);
bSuccess &= psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, nPoints - nMiddle - 2,
x + nMiddle + 1, y + nMiddle + 1, z + nMiddle + 1,
panSuccess + nMiddle + 1);
x[0] = xSMETransformed[0];
y[0] = ySMETransformed[0];
z[0] = zSMETransformed[0];
panSuccess[0] = TRUE;
x[nMiddle] = xSMETransformed[1];
y[nMiddle] = ySMETransformed[1];
z[nMiddle] = zSMETransformed[1];
panSuccess[nMiddle] = TRUE;
x[nPoints - 1] = xSMETransformed[2];
y[nPoints - 1] = ySMETransformed[2];
z[nPoints - 1] = zSMETransformed[2];
panSuccess[nPoints - 1] = TRUE;
return bSuccess;
}
double x2[3] = {};
double y2[3] = {};
double z2[3] = {};
if (!bUseBaseTransformForHalf1)
{
x2[0] = xSMETransformed[0];
y2[0] = ySMETransformed[0];
z2[0] = zSMETransformed[0];
x2[1] = xMiddle[0];
y2[1] = yMiddle[0];
z2[1] = zMiddle[0];
x2[2] = xMiddle[1];
y2[2] = yMiddle[1];
z2[2] = zMiddle[1];
bSuccess = GDALApproxTransformInternal(
psATInfo, bDstToSrc, nMiddle, x, y, z, panSuccess, x2, y2, z2);
}
else
{
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, nMiddle - 1, x + 1, y + 1,
z + 1, panSuccess + 1);
x[0] = xSMETransformed[0];
y[0] = ySMETransformed[0];
z[0] = zSMETransformed[0];
panSuccess[0] = TRUE;
}
if (!bSuccess)
return FALSE;
if (!bUseBaseTransformForHalf2)
{
x2[0] = xSMETransformed[1];
y2[0] = ySMETransformed[1];
z2[0] = zSMETransformed[1];
x2[1] = xMiddle[2];
y2[1] = yMiddle[2];
z2[1] = zMiddle[2];
x2[2] = xSMETransformed[2];
y2[2] = ySMETransformed[2];
z2[2] = zSMETransformed[2];
bSuccess = GDALApproxTransformInternal(
psATInfo, bDstToSrc, nPoints - nMiddle, x + nMiddle,
y + nMiddle, z + nMiddle, panSuccess + nMiddle, x2, y2, z2);
}
else
{
bSuccess = psATInfo->pfnBaseTransformer(
psATInfo->pBaseCBData, bDstToSrc, nPoints - nMiddle - 2,
x + nMiddle + 1, y + nMiddle + 1, z + nMiddle + 1,
panSuccess + nMiddle + 1);
x[nMiddle] = xSMETransformed[1];
y[nMiddle] = ySMETransformed[1];
z[nMiddle] = zSMETransformed[1];
panSuccess[nMiddle] = TRUE;
x[nPoints - 1] = xSMETransformed[2];
y[nPoints - 1] = ySMETransformed[2];
z[nPoints - 1] = zSMETransformed[2];
panSuccess[nPoints - 1] = TRUE;
}
if (!bSuccess)
return FALSE;
return TRUE;
}
/* -------------------------------------------------------------------- */
/* Error is OK since this is just used to compute output bounds */
/* of newly created file for gdalwarper. So just use affine */
/* approximation of the reverse transform. Eventually we */
/* should implement iterative searching to find a result within */
/* our error threshold. */
/* NOTE: the above comment is not true: gdalwarp uses approximator */
/* also to compute the source pixel of each target pixel. */
/* -------------------------------------------------------------------- */
for (int i = nPoints - 1; i >= 0; i--)
{
#ifdef check_error
double xtemp = x[i];
double ytemp = y[i];
double ztemp = z[i];
double x_ori = xtemp;
double y_ori = ytemp;
int btemp = FALSE;
psATInfo->pfnBaseTransformer(psATInfo->pBaseCBData, bDstToSrc, 1,
&xtemp, &ytemp, &ztemp, &btemp);
#endif
const double dfDist = (x[i] - x[0]);
x[i] = xSMETransformed[0] + dfDeltaX * dfDist;
y[i] = ySMETransformed[0] + dfDeltaY * dfDist;
z[i] = zSMETransformed[0] + dfDeltaZ * dfDist;
#ifdef check_error
const double dfError2 = fabs(x[i] - xtemp) + fabs(y[i] - ytemp);
if (dfError2 > 4 /*10 * dfMaxError*/)
{
/*ok*/ printf("Error = %f on (%f, %f)\n", dfError2, x_ori, y_ori);
}
#endif
panSuccess[i] = TRUE;
}
return TRUE;
}
/************************************************************************/
/* GDALApproxTransform() */
/************************************************************************/
/**
* Perform approximate transformation.
*
* Actually performs the approximate transformation described in
* GDALCreateApproxTransformer(). This function matches the
* GDALTransformerFunc() signature. Details of the arguments are described
* there.
*/
int GDALApproxTransform(void *pCBData, int bDstToSrc, int nPoints, double *x,
double *y, double *z, int *panSuccess)
{
GDALApproxTransformInfo *psATInfo =
static_cast<GDALApproxTransformInfo *>(pCBData);
double x2[3] = {};
double y2[3] = {};
double z2[3] = {};
int anSuccess2[3] = {};
int bSuccess;
const int nMiddle = (nPoints - 1) / 2;
/* -------------------------------------------------------------------- */
/* Bail if our preconditions are not met, or if error is not */
/* acceptable. */
/* -------------------------------------------------------------------- */
int bRet = FALSE;
if (y[0] != y[nPoints - 1] || y[0] != y[nMiddle] ||
x[0] == x[nPoints - 1] || x[0] == x[nMiddle] ||
(psATInfo->dfMaxErrorForward == 0.0 &&
psATInfo->dfMaxErrorReverse == 0.0) ||
nPoints <= 5)
{
bRet = psATInfo->pfnBaseTransformer(psATInfo->pBaseCBData, bDstToSrc,
nPoints, x, y, z, panSuccess);
goto end;
}
/* -------------------------------------------------------------------- */
/* Transform first, last and middle point. */
/* -------------------------------------------------------------------- */
x2[0] = x[0];
y2[0] = y[0];
z2[0] = z[0];
x2[1] = x[nMiddle];
y2[1] = y[nMiddle];
z2[1] = z[nMiddle];
x2[2] = x[nPoints - 1];
y2[2] = y[nPoints - 1];
z2[2] = z[nPoints - 1];
bSuccess = psATInfo->pfnBaseTransformer(psATInfo->pBaseCBData, bDstToSrc, 3,
x2, y2, z2, anSuccess2);
if (!bSuccess || !anSuccess2[0] || !anSuccess2[1] || !anSuccess2[2])
{
bRet = psATInfo->pfnBaseTransformer(psATInfo->pBaseCBData, bDstToSrc,
nPoints, x, y, z, panSuccess);
goto end;
}
bRet = GDALApproxTransformInternal(pCBData, bDstToSrc, nPoints, x, y, z,
panSuccess, x2, y2, z2);
end:
#ifdef DEBUG_APPROX_TRANSFORMER
for (int i = 0; i < nPoints; i++)
fprintf(stderr, "[%d] (%.10f,%.10f) %d\n", /*ok*/
i, x[i], y[i], panSuccess[i]);
#endif
return bRet;
}
/************************************************************************/
/* GDALDeserializeApproxTransformer() */
/************************************************************************/
static void *GDALDeserializeApproxTransformer(CPLXMLNode *psTree)
{
double dfMaxErrorForward = 0.25;
double dfMaxErrorReverse = 0.25;
const char *pszMaxError = CPLGetXMLValue(psTree, "MaxError", nullptr);
if (pszMaxError != nullptr)
{
dfMaxErrorForward = CPLAtof(pszMaxError);
dfMaxErrorReverse = dfMaxErrorForward;
}
const char *pszMaxErrorForward =
CPLGetXMLValue(psTree, "MaxErrorForward", nullptr);
if (pszMaxErrorForward != nullptr)
{
dfMaxErrorForward = CPLAtof(pszMaxErrorForward);
}
const char *pszMaxErrorReverse =
CPLGetXMLValue(psTree, "MaxErrorReverse", nullptr);
if (pszMaxErrorReverse != nullptr)
{
dfMaxErrorReverse = CPLAtof(pszMaxErrorReverse);
}
GDALTransformerFunc pfnBaseTransform = nullptr;
void *pBaseCBData = nullptr;
CPLXMLNode *psContainer = CPLGetXMLNode(psTree, "BaseTransformer");
if (psContainer != nullptr && psContainer->psChild != nullptr)
{
GDALDeserializeTransformer(psContainer->psChild, &pfnBaseTransform,
&pBaseCBData);
}
if (pfnBaseTransform == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Cannot get base transform for approx transformer.");
return nullptr;
}
void *pApproxCBData = GDALCreateApproxTransformer2(
pfnBaseTransform, pBaseCBData, dfMaxErrorForward, dfMaxErrorReverse);
GDALApproxTransformerOwnsSubtransformer(pApproxCBData, TRUE);
return pApproxCBData;
}
/************************************************************************/
/* GDALTransformLonLatToDestApproxTransformer() */
/************************************************************************/
int GDALTransformLonLatToDestApproxTransformer(void *hTransformArg,
double *pdfX, double *pdfY)
{
GDALApproxTransformInfo *psInfo =
static_cast<GDALApproxTransformInfo *>(hTransformArg);
if (GDALIsTransformer(psInfo->pBaseCBData,
GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
return GDALTransformLonLatToDestGenImgProjTransformer(
psInfo->pBaseCBData, pdfX, pdfY);
}
return false;
}
/************************************************************************/
/* GDALApplyGeoTransform() */
/************************************************************************/
/**
* Apply GeoTransform to x/y coordinate.
*
* Applies the following computation, converting a (pixel, line) coordinate
* into a georeferenced (geo_x, geo_y) location.
* \code{.c}
* *pdfGeoX = padfGeoTransform[0] + dfPixel * padfGeoTransform[1]
* + dfLine * padfGeoTransform[2];
* *pdfGeoY = padfGeoTransform[3] + dfPixel * padfGeoTransform[4]
* + dfLine * padfGeoTransform[5];
* \endcode
*
* @param padfGeoTransform Six coefficient GeoTransform to apply.
* @param dfPixel Input pixel position.
* @param dfLine Input line position.
* @param pdfGeoX output location where geo_x (easting/longitude)
* location is placed.
* @param pdfGeoY output location where geo_y (northing/latitude)
* location is placed.
*/
void CPL_STDCALL GDALApplyGeoTransform(const double *padfGeoTransform,
double dfPixel, double dfLine,
double *pdfGeoX, double *pdfGeoY)
{
*pdfGeoX = padfGeoTransform[0] + dfPixel * padfGeoTransform[1] +
dfLine * padfGeoTransform[2];
*pdfGeoY = padfGeoTransform[3] + dfPixel * padfGeoTransform[4] +
dfLine * padfGeoTransform[5];
}
/************************************************************************/
/* GDALInvGeoTransform() */
/************************************************************************/
/**
* Invert Geotransform.
*
* This function will invert a standard 3x2 set of GeoTransform coefficients.
* This converts the equation from being pixel to geo to being geo to pixel.
*
* @param gt_in Input geotransform (six doubles - unaltered).
* @param gt_out Output geotransform (six doubles - updated).
*
* @return TRUE on success or FALSE if the equation is uninvertable.
*/
int CPL_STDCALL GDALInvGeoTransform(const double *gt_in, double *gt_out)
{
// Special case - no rotation - to avoid computing determinate
// and potential precision issues.
if (gt_in[2] == 0.0 && gt_in[4] == 0.0 && gt_in[1] != 0.0 &&
gt_in[5] != 0.0)
{
/*X = gt_in[0] + x * gt_in[1]
Y = gt_in[3] + y * gt_in[5]
-->
x = -gt_in[0] / gt_in[1] + (1 / gt_in[1]) * X
y = -gt_in[3] / gt_in[5] + (1 / gt_in[5]) * Y
*/
gt_out[0] = -gt_in[0] / gt_in[1];
gt_out[1] = 1.0 / gt_in[1];
gt_out[2] = 0.0;
gt_out[3] = -gt_in[3] / gt_in[5];
gt_out[4] = 0.0;
gt_out[5] = 1.0 / gt_in[5];
return 1;
}
// Assume a 3rd row that is [1 0 0].
// Compute determinate.
const double det = gt_in[1] * gt_in[5] - gt_in[2] * gt_in[4];
const double magnitude = std::max(std::max(fabs(gt_in[1]), fabs(gt_in[2])),
std::max(fabs(gt_in[4]), fabs(gt_in[5])));
if (fabs(det) <= 1e-10 * magnitude * magnitude)
return 0;
const double inv_det = 1.0 / det;
// Compute adjoint, and divide by determinate.
gt_out[1] = gt_in[5] * inv_det;
gt_out[4] = -gt_in[4] * inv_det;
gt_out[2] = -gt_in[2] * inv_det;
gt_out[5] = gt_in[1] * inv_det;
gt_out[0] = (gt_in[2] * gt_in[3] - gt_in[0] * gt_in[5]) * inv_det;
gt_out[3] = (-gt_in[1] * gt_in[3] + gt_in[0] * gt_in[4]) * inv_det;
return 1;
}
/************************************************************************/
/* GDALSerializeTransformer() */
/************************************************************************/
CPLXMLNode *GDALSerializeTransformer(GDALTransformerFunc /* pfnFunc */,
void *pTransformArg)
{
VALIDATE_POINTER1(pTransformArg, "GDALSerializeTransformer", nullptr);
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (psInfo == nullptr || memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to serialize non-GTI2 transformer.");
return nullptr;
}
else if (psInfo->pfnSerialize == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"No serialization function available for this transformer.");
return nullptr;
}
return psInfo->pfnSerialize(pTransformArg);
}
/************************************************************************/
/* GDALRegisterTransformDeserializer() */
/************************************************************************/
static CPLList *psListDeserializer = nullptr;
static CPLMutex *hDeserializerMutex = nullptr;
typedef struct
{
char *pszTransformName;
GDALTransformerFunc pfnTransformerFunc;
GDALTransformDeserializeFunc pfnDeserializeFunc;
} TransformDeserializerInfo;
void *GDALRegisterTransformDeserializer(
const char *pszTransformName, GDALTransformerFunc pfnTransformerFunc,
GDALTransformDeserializeFunc pfnDeserializeFunc)
{
TransformDeserializerInfo *psInfo =
static_cast<TransformDeserializerInfo *>(
CPLMalloc(sizeof(TransformDeserializerInfo)));
psInfo->pszTransformName = CPLStrdup(pszTransformName);
psInfo->pfnTransformerFunc = pfnTransformerFunc;
psInfo->pfnDeserializeFunc = pfnDeserializeFunc;
CPLMutexHolderD(&hDeserializerMutex);
psListDeserializer = CPLListInsert(psListDeserializer, psInfo, 0);
return psInfo;
}
/************************************************************************/
/* GDALUnregisterTransformDeserializer() */
/************************************************************************/
void GDALUnregisterTransformDeserializer(void *pData)
{
CPLMutexHolderD(&hDeserializerMutex);
CPLList *psList = psListDeserializer;
CPLList *psLast = nullptr;
while (psList)
{
if (psList->pData == pData)
{
TransformDeserializerInfo *psInfo =
static_cast<TransformDeserializerInfo *>(pData);
CPLFree(psInfo->pszTransformName);
CPLFree(pData);
if (psLast)
psLast->psNext = psList->psNext;
else
psListDeserializer = nullptr;
CPLFree(psList);
break;
}
psLast = psList;
psList = psList->psNext;
}
}
/************************************************************************/
/* GDALUnregisterTransformDeserializer() */
/************************************************************************/
void GDALCleanupTransformDeserializerMutex()
{
if (hDeserializerMutex != nullptr)
{
CPLDestroyMutex(hDeserializerMutex);
hDeserializerMutex = nullptr;
}
}
/************************************************************************/
/* GDALDeserializeTransformer() */
/************************************************************************/
CPLErr GDALDeserializeTransformer(CPLXMLNode *psTree,
GDALTransformerFunc *ppfnFunc,
void **ppTransformArg)
{
*ppfnFunc = nullptr;
*ppTransformArg = nullptr;
CPLErrorReset();
if (psTree == nullptr || psTree->eType != CXT_Element)
CPLError(CE_Failure, CPLE_AppDefined,
"Malformed element in GDALDeserializeTransformer");
else if (EQUAL(psTree->pszValue, "GenImgProjTransformer"))
{
*ppfnFunc = GDALGenImgProjTransform;
*ppTransformArg = GDALDeserializeGenImgProjTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "ReprojectionTransformer"))
{
*ppfnFunc = GDALReprojectionTransform;
*ppTransformArg = GDALDeserializeReprojectionTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "GCPTransformer"))
{
*ppfnFunc = GDALGCPTransform;
*ppTransformArg = GDALDeserializeGCPTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "TPSTransformer"))
{
*ppfnFunc = GDALTPSTransform;
*ppTransformArg = GDALDeserializeTPSTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "GeoLocTransformer"))
{
*ppfnFunc = GDALGeoLocTransform;
*ppTransformArg = GDALDeserializeGeoLocTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "RPCTransformer"))
{
*ppfnFunc = GDALRPCTransform;
*ppTransformArg = GDALDeserializeRPCTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "ApproxTransformer"))
{
*ppfnFunc = GDALApproxTransform;
*ppTransformArg = GDALDeserializeApproxTransformer(psTree);
}
else if (EQUAL(psTree->pszValue, "HomographyTransformer"))
{
*ppfnFunc = GDALHomographyTransform;
*ppTransformArg = GDALDeserializeHomographyTransformer(psTree);
}
else
{
GDALTransformDeserializeFunc pfnDeserializeFunc = nullptr;
{
CPLMutexHolderD(&hDeserializerMutex);
CPLList *psList = psListDeserializer;
while (psList)
{
TransformDeserializerInfo *psInfo =
static_cast<TransformDeserializerInfo *>(psList->pData);
if (strcmp(psInfo->pszTransformName, psTree->pszValue) == 0)
{
*ppfnFunc = psInfo->pfnTransformerFunc;
pfnDeserializeFunc = psInfo->pfnDeserializeFunc;
break;
}
psList = psList->psNext;
}
}
if (pfnDeserializeFunc != nullptr)
{
*ppTransformArg = pfnDeserializeFunc(psTree);
}
else
{
CPLError(CE_Failure, CPLE_AppDefined,
"Unrecognized element '%s' GDALDeserializeTransformer",
psTree->pszValue);
}
}
return CPLGetLastErrorType();
}
/************************************************************************/
/* GDALDestroyTransformer() */
/************************************************************************/
void GDALDestroyTransformer(void *pTransformArg)
{
if (pTransformArg == nullptr)
return;
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to destroy non-GTI2 transformer.");
return;
}
psInfo->pfnCleanup(pTransformArg);
}
/************************************************************************/
/* GDALUseTransformer() */
/************************************************************************/
int GDALUseTransformer(void *pTransformArg, int bDstToSrc, int nPointCount,
double *x, double *y, double *z, int *panSuccess)
{
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (psInfo == nullptr || memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to use non-GTI2 transformer.");
return FALSE;
}
return psInfo->pfnTransform(pTransformArg, bDstToSrc, nPointCount, x, y, z,
panSuccess);
}
/************************************************************************/
/* GDALCloneTransformer() */
/************************************************************************/
void *GDALCloneTransformer(void *pTransformArg)
{
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (psInfo == nullptr || memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to clone non-GTI2 transformer.");
return nullptr;
}
if (psInfo->pfnCreateSimilar != nullptr)
{
return psInfo->pfnCreateSimilar(psInfo, 1.0, 1.0);
}
if (psInfo->pfnSerialize == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"No serialization function available for this transformer.");
return nullptr;
}
CPLXMLNode *pSerialized = psInfo->pfnSerialize(pTransformArg);
if (pSerialized == nullptr)
return nullptr;
GDALTransformerFunc pfnTransformer = nullptr;
void *pClonedTransformArg = nullptr;
if (GDALDeserializeTransformer(pSerialized, &pfnTransformer,
&pClonedTransformArg) != CE_None)
{
CPLDestroyXMLNode(pSerialized);
CPLFree(pClonedTransformArg);
return nullptr;
}
CPLDestroyXMLNode(pSerialized);
return pClonedTransformArg;
}
/************************************************************************/
/* GDALCreateSimilarTransformer() */
/************************************************************************/
void *GDALCreateSimilarTransformer(void *pTransformArg, double dfRatioX,
double dfRatioY)
{
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (psInfo == nullptr || memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to call CreateSimilar on a non-GTI2 transformer.");
return nullptr;
}
if (psInfo->pfnCreateSimilar == nullptr)
{
CPLError(CE_Failure, CPLE_AppDefined,
"No CreateSimilar function available for this transformer.");
return nullptr;
}
return psInfo->pfnCreateSimilar(psInfo, dfRatioX, dfRatioY);
}
/************************************************************************/
/* GetGenImgProjTransformInfo() */
/************************************************************************/
static GDALTransformerInfo *GetGenImgProjTransformInfo(const char *pszFunc,
void *pTransformArg)
{
GDALTransformerInfo *psInfo =
static_cast<GDALTransformerInfo *>(pTransformArg);
if (psInfo == nullptr || memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to call %s on "
"a non-GTI2 transformer.",
pszFunc);
return nullptr;
}
if (EQUAL(psInfo->pszClassName, GDAL_APPROX_TRANSFORMER_CLASS_NAME))
{
GDALApproxTransformInfo *psATInfo =
static_cast<GDALApproxTransformInfo *>(pTransformArg);
psInfo = static_cast<GDALTransformerInfo *>(psATInfo->pBaseCBData);
if (psInfo == nullptr ||
memcmp(psInfo->abySignature, GDAL_GTI2_SIGNATURE,
strlen(GDAL_GTI2_SIGNATURE)) != 0)
{
CPLError(CE_Failure, CPLE_AppDefined,
"Attempt to call %s on "
"a non-GTI2 transformer.",
pszFunc);
return nullptr;
}
}
if (EQUAL(psInfo->pszClassName, GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
return psInfo;
}
return nullptr;
}
/************************************************************************/
/* GDALSetTransformerDstGeoTransform() */
/************************************************************************/
/**
* Set ApproxTransformer or GenImgProj output geotransform.
*
* This is a layer above GDALSetGenImgProjTransformerDstGeoTransform() that
* checks that the passed hTransformArg is compatible.
*
* Normally the "destination geotransform", or transformation between
* georeferenced output coordinates and pixel/line coordinates on the
* destination file is extracted from the destination file by
* GDALCreateGenImgProjTransformer() and stored in the GenImgProj private
* info. However, sometimes it is inconvenient to have an output file
* handle with appropriate geotransform information when creating the
* transformation. For these cases, this function can be used to apply
* the destination geotransform.
*
* @param pTransformArg the handle to update.
* @param padfGeoTransform the destination geotransform to apply (six doubles).
*/
void GDALSetTransformerDstGeoTransform(void *pTransformArg,
const double *padfGeoTransform)
{
VALIDATE_POINTER0(pTransformArg, "GDALSetTransformerDstGeoTransform");
GDALTransformerInfo *psInfo = GetGenImgProjTransformInfo(
"GDALSetTransformerDstGeoTransform", pTransformArg);
if (psInfo)
{
GDALSetGenImgProjTransformerDstGeoTransform(psInfo, padfGeoTransform);
}
}
/************************************************************************/
/* GDALGetTransformerDstGeoTransform() */
/************************************************************************/
/**
* Get ApproxTransformer or GenImgProj output geotransform.
*
* @param pTransformArg transformer handle.
* @param padfGeoTransform (output) the destination geotransform to return (six
* doubles).
*/
void GDALGetTransformerDstGeoTransform(void *pTransformArg,
double *padfGeoTransform)
{
VALIDATE_POINTER0(pTransformArg, "GDALGetTransformerDstGeoTransform");
GDALTransformerInfo *psInfo = GetGenImgProjTransformInfo(
"GDALGetTransformerDstGeoTransform", pTransformArg);
if (psInfo)
{
GDALGenImgProjTransformInfo *psGenImgProjInfo =
reinterpret_cast<GDALGenImgProjTransformInfo *>(psInfo);
memcpy(padfGeoTransform, psGenImgProjInfo->sDstParams.adfGeoTransform,
sizeof(double) * 6);
}
}
/************************************************************************/
/* GDALTransformIsTranslationOnPixelBoundaries() */
/************************************************************************/
bool GDALTransformIsTranslationOnPixelBoundaries(GDALTransformerFunc,
void *pTransformerArg)
{
if (GDALIsTransformer(pTransformerArg, GDAL_APPROX_TRANSFORMER_CLASS_NAME))
{
const auto *pApproxInfo =
static_cast<const GDALApproxTransformInfo *>(pTransformerArg);
pTransformerArg = pApproxInfo->pBaseCBData;
}
if (GDALIsTransformer(pTransformerArg, GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
const auto *pGenImgpProjInfo =
static_cast<GDALGenImgProjTransformInfo *>(pTransformerArg);
const auto IsCloseToInteger = [](double dfVal)
{ return std::fabs(dfVal - std::round(dfVal)) <= 1e-6; };
return pGenImgpProjInfo->sSrcParams.pTransformArg == nullptr &&
pGenImgpProjInfo->sDstParams.pTransformArg == nullptr &&
pGenImgpProjInfo->pReproject == nullptr &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[1] ==
pGenImgpProjInfo->sDstParams.adfGeoTransform[1] &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[5] ==
pGenImgpProjInfo->sDstParams.adfGeoTransform[5] &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[2] ==
pGenImgpProjInfo->sDstParams.adfGeoTransform[2] &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[4] ==
pGenImgpProjInfo->sDstParams.adfGeoTransform[4] &&
// Check that the georeferenced origin of the destination
// geotransform is close to be an integer value when transformed
// to source image coordinates
IsCloseToInteger(
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[0] +
pGenImgpProjInfo->sDstParams.adfGeoTransform[0] *
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[1] +
pGenImgpProjInfo->sDstParams.adfGeoTransform[3] *
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[2]) &&
IsCloseToInteger(
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[3] +
pGenImgpProjInfo->sDstParams.adfGeoTransform[0] *
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[4] +
pGenImgpProjInfo->sDstParams.adfGeoTransform[3] *
pGenImgpProjInfo->sSrcParams.adfInvGeoTransform[5]);
}
return false;
}
/************************************************************************/
/* GDALTransformIsAffineNoRotation() */
/************************************************************************/
bool GDALTransformIsAffineNoRotation(GDALTransformerFunc, void *pTransformerArg)
{
if (GDALIsTransformer(pTransformerArg, GDAL_APPROX_TRANSFORMER_CLASS_NAME))
{
const auto *pApproxInfo =
static_cast<const GDALApproxTransformInfo *>(pTransformerArg);
pTransformerArg = pApproxInfo->pBaseCBData;
}
if (GDALIsTransformer(pTransformerArg, GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
const auto *pGenImgpProjInfo =
static_cast<GDALGenImgProjTransformInfo *>(pTransformerArg);
return pGenImgpProjInfo->sSrcParams.pTransformArg == nullptr &&
pGenImgpProjInfo->sDstParams.pTransformArg == nullptr &&
pGenImgpProjInfo->pReproject == nullptr &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[2] == 0 &&
pGenImgpProjInfo->sSrcParams.adfGeoTransform[4] == 0 &&
pGenImgpProjInfo->sDstParams.adfGeoTransform[2] == 0 &&
pGenImgpProjInfo->sDstParams.adfGeoTransform[4] == 0;
}
return false;
}
/************************************************************************/
/* GDALTransformHasFastClone() */
/************************************************************************/
/** Returns whether GDALCloneTransformer() on this transformer is
* "fast"
* Counter-examples are GCPs or TPSs transformers.
*/
bool GDALTransformHasFastClone(void *pTransformerArg)
{
if (GDALIsTransformer(pTransformerArg, GDAL_APPROX_TRANSFORMER_CLASS_NAME))
{
const auto *pApproxInfo =
static_cast<const GDALApproxTransformInfo *>(pTransformerArg);
pTransformerArg = pApproxInfo->pBaseCBData;
// Fallback to next lines
}
if (GDALIsTransformer(pTransformerArg, GDAL_GEN_IMG_TRANSFORMER_CLASS_NAME))
{
const auto *pGenImgpProjInfo =
static_cast<GDALGenImgProjTransformInfo *>(pTransformerArg);
return (pGenImgpProjInfo->sSrcParams.pTransformArg == nullptr ||
GDALTransformHasFastClone(
pGenImgpProjInfo->sSrcParams.pTransformArg)) &&
(pGenImgpProjInfo->sDstParams.pTransformArg == nullptr ||
GDALTransformHasFastClone(
pGenImgpProjInfo->sDstParams.pTransformArg));
}
else if (GDALIsTransformer(pTransformerArg,
GDAL_RPC_TRANSFORMER_CLASS_NAME))
{
return true;
}
else
{
return false;
}
}
|