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
//! Matrix types.

use std::mem;
use std::ptr;
use std::slice;
use std::ops::Add;
use std::fmt::{self, Display, Formatter, Debug};
use std::ops::*;
use num_traits::{Zero, One, real::Real, FloatConst, NumCast, AsPrimitive};
use approx::{AbsDiffEq, RelativeEq, UlpsEq};
use crate::ops::MulAdd;
use crate::vec;
use crate::geom::{Rect, FrustumPlanes}; // NOTE: Rect is therefore always repr_c here
use crate::quaternion;
use crate::transform;

// Needed because mem::transmute() isn't clever enough to figure out that e.g [T; 16] and [[T; 4]; 4]
// always have the exact same size and layout, regardless of T. The opposite is impossible.
// See https://github.com/rust-lang/rust/issues/47966
#[inline(always)]
unsafe fn transmute_unchecked<S, D>(s: S) -> D {
    debug_assert_eq!(mem::size_of::<S>(), mem::size_of::<D>());
    let d = ptr::read(&s as *const _ as *const D);
    mem::forget(s);
    d
}

macro_rules! mat_impl_mat {
    (rows $Mat:ident $MintRowMat:ident $MintColMat:ident $CVec:ident $Vec:ident ($nrows:tt x $ncols:tt) ($($get:tt)+)) => {

        mat_impl_mat!{common rows $Mat $CVec $Vec ($nrows x $ncols) ($($get)+)}

        use super::column_major::$Mat as Transpose;

        #[cfg(feature = "mint")]
        impl<T> From<mint::$MintRowMat<T>> for $Mat<T> {
            fn from(m: mint::$MintRowMat<T>) -> Self {
                Self {
                    rows: $CVec {
                        $($get : m.$get.into()),+
                    }
                }
            }
        }

        #[cfg(feature = "mint")]
        impl<T> Into<mint::$MintRowMat<T>> for $Mat<T> {
            fn into(self) -> mint::$MintRowMat<T> {
                mint::$MintRowMat {
                    $($get: self.rows.$get.into()),+
                }
            }
        }

        #[cfg(feature = "mint")]
        impl<T> From<mint::$MintColMat<T>> for $Mat<T> {
            fn from(m: mint::$MintColMat<T>) -> Self {
                Transpose::from(m).into()
            }
        }

        #[cfg(feature = "mint")]
        impl<T> Into<mint::$MintColMat<T>> for $Mat<T> {
            fn into(self) -> mint::$MintColMat<T> {
                Transpose::from(self).into()
            }
        }

        impl<T> $Mat<T> {
            /// Returns a row-wise-converted copy of this matrix, using the given conversion
            /// closure.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<f32>::new(
            ///     0.25, 1.25, 5.56, 8.66,
            ///     8.53, 2.92, 3.86, 9.36,
            ///     1.02, 0.28, 5.52, 6.06,
            ///     6.20, 7.01, 4.90, 5.26
            /// );
            /// let m = m.map_rows(|row| row.map(|x| x.round() as i32));
            /// assert_eq!(m, Mat4::new(
            ///     0, 1, 6, 9,
            ///     9, 3, 4, 9,
            ///     1, 0, 6, 6,
            ///     6, 7, 5, 5
            /// ));
            /// ```
            pub fn map_rows<D,F>(self, mut f: F) -> $Mat<D> where F: FnMut($Vec<T>) -> $Vec<D> {
                $Mat { rows: $CVec::new($(f(self.rows.$get)),+) }
            }

            /// Converts this matrix into a fixed-size array of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// ];
            /// assert_eq!(m.into_row_array(), array);
            /// ```
            pub fn into_row_array(self) -> [T; $nrows*$ncols] {
                let m = mem::ManuallyDrop::new(self);
                let mut cur = 0;
                unsafe {
                    let mut array: mem::MaybeUninit<[T; $nrows*$ncols]> = mem::MaybeUninit::uninit();
                    for i in 0..$nrows {
                        let row = m.rows.get_unchecked(i);
                        $(
                            mem::forget(mem::replace((&mut *array.as_mut_ptr()).get_unchecked_mut(cur), ptr::read(&row.$get)));
                            cur += 1;
                        )+
                    }
                    array.assume_init()
                }
            }
            /// Converts this matrix into a fixed-size array of fixed-size arrays of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [  0,  1,  2,  3, ],
            ///     [  4,  5,  6,  7, ],
            ///     [  8,  9, 10, 11, ],
            ///     [ 12, 13, 14, 15, ],
            /// ];
            /// assert_eq!(m.into_row_arrays(), array);
            /// ```
            pub fn into_row_arrays(self) -> [[T; $ncols]; $nrows] {
                unsafe {
                    transmute_unchecked(self.into_row_array())
                }
            }
            /// Converts a fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// ];
            /// assert_eq!(m, Mat4::from_row_array(array));
            /// ```
            pub fn from_row_array(array: [T; $nrows*$ncols]) -> Self {
                let array = mem::ManuallyDrop::new(array);
                let mut cur = 0;
                unsafe {
                    let mut m: mem::MaybeUninit<Self> = mem::MaybeUninit::uninit();
                    for i in 0..$nrows {
                        let row = (&mut *m.as_mut_ptr()).rows.get_unchecked_mut(i);
                        $(
                            mem::forget(mem::replace(&mut row.$get, ptr::read(array.get_unchecked(cur))));
                            cur += 1;
                        )+
                    }
                    m.assume_init()
                }
            }
            /// Converts a fixed-size array of fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [  0,  1,  2,  3, ],
            ///     [  4,  5,  6,  7, ],
            ///     [  8,  9, 10, 11, ],
            ///     [ 12, 13, 14, 15, ],
            /// ];
            /// assert_eq!(m, Mat4::from_row_arrays(array));
            /// ```
            pub fn from_row_arrays(array: [[T; $ncols]; $nrows]) -> Self {
                Self::from_row_array(unsafe { transmute_unchecked(array) })
            }
            /// Converts this matrix into a fixed-size array of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     0, 4, 8, 12,
            ///     1, 5, 9, 13,
            ///     2, 6, 10, 14,
            ///     3, 7, 11, 15
            /// ];
            /// assert_eq!(m.into_col_array(), array);
            /// ```
            pub fn into_col_array(self) -> [T; $nrows*$ncols] {
                let m = mem::ManuallyDrop::new(self);
                let mut cur = 0;
                unsafe {
                    let mut array: mem::MaybeUninit<[T; $nrows*$ncols]> = mem::MaybeUninit::uninit();
                    $(
                        for i in 0..$nrows {
                            mem::forget(mem::replace((&mut *array.as_mut_ptr()).get_unchecked_mut(cur), ptr::read(&m.rows.get_unchecked(i).$get)));
                            cur += 1;
                        }
                    )+
                    array.assume_init()
                }
            }
            /// Converts this matrix into a fixed-size array of fixed-size arrays of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [ 0, 4,  8, 12, ],
            ///     [ 1, 5,  9, 13, ],
            ///     [ 2, 6, 10, 14, ],
            ///     [ 3, 7, 11, 15, ],
            /// ];
            /// assert_eq!(m.into_col_arrays(), array);
            /// ```
            pub fn into_col_arrays(self) -> [[T; $nrows]; $ncols] {
                unsafe {
                    transmute_unchecked(self.into_col_array())
                }
            }
            /// Converts a fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     0, 4, 8, 12,
            ///     1, 5, 9, 13,
            ///     2, 6, 10, 14,
            ///     3, 7, 11, 15
            /// ];
            /// assert_eq!(m, Mat4::from_col_array(array));
            /// ```
            pub fn from_col_array(array: [T; $nrows*$ncols]) -> Self {
                let array = mem::ManuallyDrop::new(array);
                let mut cur = 0;
                unsafe {
                    let mut m: mem::MaybeUninit<Self> = mem::MaybeUninit::uninit();
                    $(
                        for i in 0..$nrows {
                            mem::forget(mem::replace(&mut (&mut *m.as_mut_ptr()).rows.get_unchecked_mut(i).$get, ptr::read(array.get_unchecked(cur))));
                            cur += 1;
                        }
                    )+
                    m.assume_init()
                }
            }
            /// Converts a fixed-size array of fixed-size arrays of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [ 0, 4,  8, 12, ],
            ///     [ 1, 5,  9, 13, ],
            ///     [ 2, 6, 10, 14, ],
            ///     [ 3, 7, 11, 15, ],
            /// ];
            /// assert_eq!(m, Mat4::from_col_arrays(array));
            /// ```
            pub fn from_col_arrays(array: [[T; $nrows]; $ncols]) -> Self {
                Self::from_col_array(unsafe { transmute_unchecked(array) })
            }
            /// Gets a const pointer to this matrix's elements.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_row_ptr(&self) -> *const T {
                debug_assert!(self.is_packed());
                self.rows.as_ptr() as *const _ as *const T
            }
            /// Gets a mut pointer to this matrix's elements.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_mut_row_ptr(&mut self) -> *mut T {
                debug_assert!(self.is_packed());
                self.rows.as_mut_ptr() as *mut _ as *mut T
            }
            /// View this matrix as an immutable slice.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_row_slice(&self) -> &[T] {
                unsafe {
                    slice::from_raw_parts(self.as_row_ptr(), $nrows*$ncols)
                }
            }
            /// View this matrix as a mutable slice.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_mut_row_slice(&mut self) -> &mut [T] {
                unsafe {
                    slice::from_raw_parts_mut(self.as_mut_row_ptr(), $nrows*$ncols)
                }
            }
        }


        /// Displays this matrix using the following format:
        ///
        /// (`i` being the number of rows and `j` the number of columns)
        ///
        /// ```text
        /// ( m00 ... m0j
        ///   ... ... ...
        ///   mi0 ... mij )
        /// ```
        ///
        /// Note that elements are not comma-separated.
        /// This format doesn't depend on the matrix's storage layout.
        impl<T: Display> Display for $Mat<T> {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                write!(f, "(")?;
                let mut rows = self.rows.iter();
                // first row goes after the opening paren
                if let Some(row) = rows.next(){
                    for elem in row {
                        write!(f, " ")?;
                        elem.fmt(f)?;
                    }
                }
                // subsequent rows start on a new line
                for row in rows{
                    write!(f, "\n ")?;
                    for elem in row {
                        write!(f, " ")?;
                        elem.fmt(f)?;
                    }
                }
                write!(f, " )")
            }
        }

        /// Index this matrix in a layout-agnostic way with an `(i, j)` (row index, column index) tuple.
        ///
        /// Matrices cannot be indexed by `Vec2`s because that would be likely to cause confusion:
        /// should `x` be the row index (because it's the first element) or the column index
        /// (because it's a horizontal position) ?
        impl<T> Index<(usize, usize)> for $Mat<T> {
            type Output = T;
            fn index(&self, t: (usize, usize)) -> &Self::Output {
                let (i, j) = t;
                &self.rows[i][j]
            }
        }
        impl<T> IndexMut<(usize, usize)> for $Mat<T> {
            fn index_mut(&mut self, t: (usize, usize)) -> &mut Self::Output {
                let (i, j) = t;
                &mut self.rows[i][j]
            }
        }

        impl<T> $Mat<T> {
            /// Gets the `transpose` parameter to pass to OpenGL `glUniformMatrix*()` functions.
            ///
            /// The return value is a plain `bool` which you may directly cast
            /// to a `GLboolean`.
            ///
            /// This takes `&self` to prevent surprises when changing the type
            /// of matrix you plan to send.
            pub fn gl_should_transpose(&self) -> bool {
                true
            }
            /// The `transpose` parameter to pass to OpenGL `glUniformMatrix*()` functions.
            pub const GL_SHOULD_TRANSPOSE: bool = true;
        }

        /// Multiplies a row vector with a row-major matrix, giving a row vector.
        ///
        /// With SIMD vectors, this is the most efficient way.
        ///
        /// ```
        /// use vek::mat::row_major::Mat4;
        /// use vek::vec::Vec4;
        ///
        /// let m = Mat4::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let v = Vec4::new(0, 1, 2, 3);
        /// let r = Vec4::new(26, 32, 18, 24);
        /// assert_eq!(v * m, r);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<$Mat<T>> for $Vec<T> {
            type Output = Self;
            fn mul(self, rhs: $Mat<T>) -> Self::Output {
                let mut out = rhs.rows[0] * $Vec::broadcast(self[0]);
                for i in 1..$nrows {
                    out = rhs.rows[i].mul_add($Vec::broadcast(self[i]), out);
                }
                out
            }
        }
        /// Multiplies a row-major matrix with a column vector, giving a column vector.
        ///
        /// ```
        /// use vek::mat::row_major::Mat4;
        /// use vek::vec::Vec4;
        ///
        /// let m = Mat4::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let v = Vec4::new(0, 1, 2, 3);
        /// let r = Vec4::new(14, 38, 12, 26);
        /// assert_eq!(m * v, r);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<$Vec<T>> for $Mat<T> {
            type Output = $Vec<T>;
            fn mul(self, v: $Vec<T>) -> Self::Output {
                // PERF: This transposes the matrix, but we could do better.
                Transpose::from(self) * v
            }
        }
        /// Multiplies a row-major matrix with another.
        ///
        /// ```
        /// use vek::mat::row_major::Mat4;
        ///
        /// let m = Mat4::<u32>::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let r = Mat4::<u32>::new(
        ///     26, 32, 18, 24,
        ///     82, 104, 66, 88,
        ///     38, 56, 74, 92,
        ///     54, 68, 42, 56
        /// );
        /// assert_eq!(m * m, r);
        /// assert_eq!(m, m * Mat4::<u32>::identity());
        /// assert_eq!(m, Mat4::<u32>::identity() * m);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul for $Mat<T> {
            type Output = Self;
            fn mul(self, rhs: Self) -> Self::Output {
                Self {
                    rows: $CVec {
                        $($get: self.rows.$get * rhs,)+
                    }
                }
            }
        }
        /// Multiplies a row-major matrix with a column-major matrix,
        /// producing a column-major matrix.
        ///
        /// ```
        /// use vek::mat::row_major::Mat4 as Rows4;
        /// use vek::mat::column_major::Mat4 as Cols4;
        ///
        /// let m = Rows4::<u32>::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let b = Cols4::from(m);
        /// let r = Cols4::<u32>::new(
        ///     26, 32, 18, 24,
        ///     82, 104, 66, 88,
        ///     38, 56, 74, 92,
        ///     54, 68, 42, 56
        /// );
        /// assert_eq!(m * b, r);
        /// assert_eq!(m * Cols4::<u32>::identity(), m.into());
        /// assert_eq!(Rows4::<u32>::identity() * b, m.into());
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<Transpose<T>> for $Mat<T> {
            type Output = Transpose<T>;
            fn mul(self, rhs: Transpose<T>) -> Self::Output {
                // PERF: This transposes the matrix, but we could do better.
                Transpose::from(self) * rhs
            }
        }
        impl<T> From<Transpose<T>> for $Mat<T> {
            fn from(m: Transpose<T>) -> Self {
                Self {
                    rows: m.transposed().cols
                }
            }
        }
    };
    (cols $Mat:ident $MintRowMat:ident $MintColMat:ident $CVec:ident $Vec:ident ($nrows:tt x $ncols:tt) ($($get:tt)+)) => {

        mat_impl_mat!{common cols $Mat $CVec $Vec ($nrows x $ncols) ($($get)+)}

        use super::row_major::$Mat as Transpose;

        #[cfg(feature = "mint")]
        impl<T> From<mint::$MintColMat<T>> for $Mat<T> {
            fn from(m: mint::$MintColMat<T>) -> Self {
                Self {
                    cols: $CVec {
                        $($get : m.$get.into()),+
                    }
                }
            }
        }

        #[cfg(feature = "mint")]
        impl<T> Into<mint::$MintColMat<T>> for $Mat<T> {
            fn into(self) -> mint::$MintColMat<T> {
                mint::$MintColMat {
                    $($get: self.cols.$get.into()),+
                }
            }
        }

        #[cfg(feature = "mint")]
        impl<T> From<mint::$MintRowMat<T>> for $Mat<T> {
            fn from(m: mint::$MintRowMat<T>) -> Self {
                Transpose::from(m).into()
            }
        }

        #[cfg(feature = "mint")]
        impl<T> Into<mint::$MintRowMat<T>> for $Mat<T> {
            fn into(self) -> mint::$MintRowMat<T> {
                Transpose::from(self).into()
            }
        }


        impl<T> $Mat<T> {
            /// Returns a column-wise-converted copy of this matrix, using the given conversion
            /// closure.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<f32>::new(
            ///     0.25, 1.25, 5.56, 8.66,
            ///     8.53, 2.92, 3.86, 9.36,
            ///     1.02, 0.28, 5.52, 6.06,
            ///     6.20, 7.01, 4.90, 5.26
            /// );
            /// let m = m.map_cols(|col| col.map(|x| x.round() as i32));
            /// assert_eq!(m, Mat4::new(
            ///     0, 1, 6, 9,
            ///     9, 3, 4, 9,
            ///     1, 0, 6, 6,
            ///     6, 7, 5, 5
            /// ));
            /// ```
            pub fn map_cols<D,F>(self, mut f: F) -> $Mat<D> where F: FnMut($Vec<T>) -> $Vec<D> {
                $Mat { cols: $CVec::new($(f(self.cols.$get)),+) }
            }


            /// Converts this matrix into a fixed-size array of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     0, 4, 8, 12,
            ///     1, 5, 9, 13,
            ///     2, 6, 10, 14,
            ///     3, 7, 11, 15
            /// ];
            /// assert_eq!(m.into_col_array(), array);
            /// ```
            pub fn into_col_array(self) -> [T; $nrows*$ncols] {
                let m = mem::ManuallyDrop::new(self);
                let mut cur = 0;
                unsafe {
                    let mut array: mem::MaybeUninit<[T; $nrows*$ncols]> = mem::MaybeUninit::uninit();
                    for i in 0..$ncols {
                        let col = m.cols.get_unchecked(i);
                        $(
                            mem::forget(mem::replace((&mut *array.as_mut_ptr()).get_unchecked_mut(cur), ptr::read(&col.$get)));
                            cur += 1;
                        )+
                    }
                    array.assume_init()
                }
            }
            /// Converts this matrix into a fixed-size array of fixed-size arrays of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [ 0, 4,  8, 12, ],
            ///     [ 1, 5,  9, 13, ],
            ///     [ 2, 6, 10, 14, ],
            ///     [ 3, 7, 11, 15, ],
            /// ];
            /// assert_eq!(m.into_col_arrays(), array);
            /// ```
            pub fn into_col_arrays(self) -> [[T; $nrows]; $ncols] {
                unsafe {
                    transmute_unchecked(self.into_col_array())
                }
            }
            /// Converts a fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     0, 4, 8, 12,
            ///     1, 5, 9, 13,
            ///     2, 6, 10, 14,
            ///     3, 7, 11, 15
            /// ];
            /// assert_eq!(m, Mat4::from_col_array(array));
            /// ```
            pub fn from_col_array(array: [T; $nrows*$ncols]) -> Self {
                let array = mem::ManuallyDrop::new(array);
                let mut cur = 0;
                unsafe {
                    let mut m: mem::MaybeUninit<Self> = mem::MaybeUninit::uninit();
                    for i in 0..$ncols {
                        let col = (&mut *m.as_mut_ptr()).cols.get_unchecked_mut(i);
                        $(
                            mem::forget(mem::replace(&mut col.$get, ptr::read(array.get_unchecked(cur))));
                            cur += 1;
                        )+
                    }
                    m.assume_init()
                }
            }
            /// Converts a fixed-size array of fixed-size arrays of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [ 0, 4,  8, 12, ],
            ///     [ 1, 5,  9, 13, ],
            ///     [ 2, 6, 10, 14, ],
            ///     [ 3, 7, 11, 15, ],
            /// ];
            /// assert_eq!(m, Mat4::from_col_arrays(array));
            /// ```
            pub fn from_col_arrays(array: [[T; $nrows]; $ncols]) -> Self {
                Self::from_col_array(unsafe { transmute_unchecked(array) })
            }
            /// Converts this matrix into a fixed-size array of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// ];
            /// assert_eq!(m.into_row_array(), array);
            /// ```
            pub fn into_row_array(self) -> [T; $nrows*$ncols] {
                let m = mem::ManuallyDrop::new(self);
                let mut cur = 0;
                unsafe {
                    let mut array: mem::MaybeUninit<[T; $nrows*$ncols]> = mem::MaybeUninit::uninit();
                    $(
                        for i in 0..$ncols {
                            mem::forget(mem::replace((&mut *array.as_mut_ptr()).get_unchecked_mut(cur), ptr::read(&m.cols.get_unchecked(i).$get)));
                            cur += 1;
                        }
                    )+
                    array.assume_init()
                }
            }
            /// Converts this matrix into a fixed-size array of fixed-size arrays of elements.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [  0,  1,  2,  3, ],
            ///     [  4,  5,  6,  7, ],
            ///     [  8,  9, 10, 11, ],
            ///     [ 12, 13, 14, 15, ],
            /// ];
            /// assert_eq!(m.into_row_arrays(), array);
            /// ```
            pub fn into_row_arrays(self) -> [[T; $ncols]; $nrows] {
                unsafe {
                    transmute_unchecked(self.into_row_array())
                }
            }
            /// Converts a fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// ];
            /// assert_eq!(m, Mat4::from_row_array(array));
            /// ```
            pub fn from_row_array(array: [T; $nrows*$ncols]) -> Self {
                let array = mem::ManuallyDrop::new(array);
                let mut cur = 0;
                unsafe {
                    let mut m: mem::MaybeUninit<Self> = mem::MaybeUninit::uninit();
                    $(
                        for i in 0..$ncols {
                            mem::forget(mem::replace(&mut (&mut *m.as_mut_ptr()).cols.get_unchecked_mut(i).$get, ptr::read(array.get_unchecked(cur))));
                            cur += 1;
                        }
                    )+
                    m.assume_init()
                }
            }
            /// Converts a fixed-size array of fixed-size array of elements into a matrix.
            ///
            /// ```
            /// use vek::mat::repr_c::column_major::Mat4;
            ///
            /// let m = Mat4::<u32>::new(
            ///      0,  1,  2,  3,
            ///      4,  5,  6,  7,
            ///      8,  9, 10, 11,
            ///     12, 13, 14, 15
            /// );
            /// let array = [
            ///     [  0,  1,  2,  3, ],
            ///     [  4,  5,  6,  7, ],
            ///     [  8,  9, 10, 11, ],
            ///     [ 12, 13, 14, 15, ],
            /// ];
            /// assert_eq!(m, Mat4::from_row_arrays(array));
            /// ```
            pub fn from_row_arrays(array: [[T; $ncols]; $nrows]) -> Self {
                Self::from_row_array(unsafe { transmute_unchecked(array) })
            }

            /// Gets a const pointer to this matrix's elements.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_col_ptr(&self) -> *const T {
                debug_assert!(self.is_packed());
                self.cols.as_ptr() as *const _ as *const T
            }
            /// Gets a mut pointer to this matrix's elements.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_mut_col_ptr(&mut self) -> *mut T {
                debug_assert!(self.is_packed());
                self.cols.as_mut_ptr() as *mut _ as *mut T
            }
            /// View this matrix as an immutable slice.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_col_slice(&self) -> &[T] {
                unsafe {
                    slice::from_raw_parts(self.as_col_ptr(), $nrows*$ncols)
                }
            }
            /// View this matrix as a mutable slice.
            ///
            /// # Panics
            /// Panics if the matrix's elements are not tightly packed in memory,
            /// which may be the case for matrices in the `repr_simd` module.
            /// You may check this with the `is_packed()` method.
            pub fn as_mut_col_slice(&mut self) -> &mut [T] {
                unsafe {
                    slice::from_raw_parts_mut(self.as_mut_col_ptr(), $nrows*$ncols)
                }
            }
        }


        /// Displays this matrix using the following format:
        ///
        /// (`i` being the number of rows and `j` the number of columns)
        ///
        /// ```text
        /// ( m00 ... m0j
        ///   ... ... ...
        ///   mi0 ... mij )
        /// ```
        ///
        /// Note that elements are not comma-separated.
        /// This format doesn't depend on the matrix's storage layout.
        impl<T: Display> Display for $Mat<T> {
            fn fmt(&self, f: &mut Formatter) -> fmt::Result {
                write!(f, "(")?;
                // first row goes after the opening paren
                for x in 0..$ncols {
                    write!(f, " ")?;
                    let elem = unsafe {
                        self.cols.get_unchecked(x).get_unchecked(0)
                    };
                    elem.fmt(f)?;
                }
                // subsequent rows start on a new line
                for y in 1..$nrows {
                    write!(f, "\n ")?;
                    for x in 0..$ncols {
                        write!(f, " ")?;
                        let elem = unsafe {
                            self.cols.get_unchecked(x).get_unchecked(y)
                        };
                        elem.fmt(f)?;
                    }
                }
                write!(f, " )")
            }
        }

        /// Index this matrix in a layout-agnostic way with an `(i, j)` (row index, column index) tuple.
        ///
        /// Matrices cannot be indexed by `Vec2`s because that would be likely to cause confusion:
        /// should `x` be the row index (because it's the first element) or the column index
        /// (because it's a horizontal position) ?
        impl<T> Index<(usize, usize)> for $Mat<T> {
            type Output = T;
            fn index(&self, t: (usize, usize)) -> &Self::Output {
                let (i, j) = t;
                &self.cols[j][i]
            }
        }
        impl<T> IndexMut<(usize, usize)> for $Mat<T> {
            fn index_mut(&mut self, t: (usize, usize)) -> &mut Self::Output {
                let (i, j) = t;
                &mut self.cols[j][i]
            }
        }


        impl<T> $Mat<T> {
            /// Gets the `transpose` parameter to pass to OpenGL `glUniformMatrix*()` functions.
            ///
            /// The return value is a plain `bool` which you may directly cast
            /// to a `GLboolean`.
            ///
            /// This takes `&self` to prevent surprises when changing the type
            /// of matrix you plan to send.
            pub fn gl_should_transpose(&self) -> bool {
                false
            }
            /// The `transpose` parameter to pass to OpenGL `glUniformMatrix*()` functions.
            pub const GL_SHOULD_TRANSPOSE: bool = false;
        }

        /// Multiplies a row vector with a column-major matrix, giving a row vector.
        ///
        /// ```
        /// use vek::mat::column_major::Mat4;
        /// use vek::vec::Vec4;
        ///
        /// let m = Mat4::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let v = Vec4::new(0, 1, 2, 3);
        /// let r = Vec4::new(26, 32, 18, 24);
        /// assert_eq!(v * m, r);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<$Mat<T>> for $Vec<T> {
            type Output = Self;
            fn mul(self, rhs: $Mat<T>) -> Self::Output {
                // PERF: This transposes the matrix, but we could do better.
                self * Transpose::from(rhs)
            }
        }
        /// Multiplies a column-major matrix with a column vector, giving a column vector.
        ///
        /// With SIMD vectors, this is the most efficient way.
        ///
        /// ```
        /// use vek::mat::column_major::Mat4;
        /// use vek::vec::Vec4;
        ///
        /// let m = Mat4::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let v = Vec4::new(0, 1, 2, 3);
        /// let r = Vec4::new(14, 38, 12, 26);
        /// assert_eq!(m * v, r);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<$Vec<T>> for $Mat<T> {
            type Output = $Vec<T>;
            fn mul(self, v: $Vec<T>) -> Self::Output {
                let mut out = self.cols[0] * $Vec::broadcast(v[0]);
                for i in 1..$ncols {
                    out = self.cols[i].mul_add($Vec::broadcast(v[i]), out);
                }
                out
            }
        }
        /// Multiplies a column-major matrix with another.
        ///
        /// ```
        /// use vek::mat::column_major::Mat4;
        ///
        /// let m = Mat4::<u32>::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let r = Mat4::<u32>::new(
        ///     26, 32, 18, 24,
        ///     82, 104, 66, 88,
        ///     38, 56, 74, 92,
        ///     54, 68, 42, 56
        /// );
        /// assert_eq!(m * m, r);
        /// assert_eq!(m, m * Mat4::<u32>::identity());
        /// assert_eq!(m, Mat4::<u32>::identity() * m);
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul for $Mat<T> {
            type Output = Self;
            fn mul(self, rhs: Self) -> Self::Output {
                Self {
                    cols: $CVec {
                        $($get: self * rhs.cols.$get,)+
                    }
                }
            }
        }
        /// Multiplies a column-major matrix with a row-major matrix.
        ///
        /// ```
        /// use vek::mat::row_major::Mat4 as Rows4;
        /// use vek::mat::column_major::Mat4 as Cols4;
        ///
        /// let m = Cols4::<u32>::new(
        ///     0, 1, 2, 3,
        ///     4, 5, 6, 7,
        ///     8, 9, 0, 1,
        ///     2, 3, 4, 5
        /// );
        /// let b = Rows4::from(m);
        /// let r = Rows4::<u32>::new(
        ///     26, 32, 18, 24,
        ///     82, 104, 66, 88,
        ///     38, 56, 74, 92,
        ///     54, 68, 42, 56
        /// );
        /// assert_eq!(m * b, r);
        /// assert_eq!(m * Rows4::<u32>::identity(), m.into());
        /// assert_eq!(Cols4::<u32>::identity() * b, m.into());
        /// ```
        impl<T: MulAdd<T,T,Output=T> + Mul<Output=T> + Copy> Mul<Transpose<T>> for $Mat<T> {
            type Output = Transpose<T>;
            fn mul(self, rhs: Transpose<T>) -> Self::Output {
                // PERF: This transposes the matrix, but we could do better.
                Transpose::from(self) * rhs
            }
        }
        impl<T> From<Transpose<T>> for $Mat<T> {
            fn from(m: Transpose<T>) -> Self {
                Self {
                    cols: m.transposed().rows
                }
            }
        }
    };
    (common $lines:ident $Mat:ident $CVec:ident $Vec:ident ($nrows:tt x $ncols:tt) ($($get:tt)+)) => {

        /// The default value for a square matrix is the identity.
        ///
        /// ```
        /// # use vek::mat::Mat4;
        /// assert_eq!(Mat4::<f32>::default(), Mat4::<f32>::identity());
        /// ```
        impl<T: Zero + One> Default for $Mat<T> {
            fn default() -> Self {
                Self::identity()
            }
        }
        // Welp, not using RelativeEq here - integers don't implement it :(
        impl<T: Zero + PartialEq> Zero for $Mat<T> {
            fn zero() -> Self { Self::zero() }
            fn is_zero(&self) -> bool { self == &Self::zero() }
        }
        impl<T: Zero + One + Copy + MulAdd<T,T,Output=T>> One for $Mat<T> {
            fn one() -> Self { Self::identity() }
        }
        impl<T> $Mat<T> {
            /// The identity matrix, which is also the default value for square matrices.
            ///
            /// ```
            /// # use vek::mat::Mat4;
            /// assert_eq!(Mat4::<f32>::default(), Mat4::<f32>::identity());
            /// ```
            pub fn identity() -> Self where T: Zero + One {
                let mut out = Self::zero();
                $(out.$lines.$get.$get = T::one();)+
                out
            }
            /// The matrix with all elements set to zero.
            pub fn zero() -> Self where T: Zero {
                Self {
                    $lines: $CVec {
                        $($get: $Vec::zero(),)+
                    }
                }
            }
            /// Applies the function f to each element of this matrix, in-place.
            ///
            /// For an example, see the `map()` method.
            pub fn apply<F>(&mut self, f: F) where T: Copy, F: FnMut(T) -> T {
                *self = self.map(f);
            }
            /// Applies the function f to each element of this matrix, in-place.
            ///
            /// For an example, see the `map2()` method.
            pub fn apply2<F, S>(&mut self, other: $Mat<S>, f: F) where T: Copy, F: FnMut(T, S) -> T {
                *self = self.map2(other, f);
            }
            /// Returns a memberwise-converted copy of this matrix, using `NumCast`.
            ///
            /// ```
            /// # use vek::Mat4;
            /// let m = Mat4::<f32>::identity();
            /// let m: Mat4<i32> = m.numcast().unwrap();
            /// assert_eq!(m, Mat4::identity());
            /// ```
            pub fn numcast<D>(self) -> Option<$Mat<D>> where T: NumCast, D: NumCast {
                // NOTE: Should use `?` for conciseness, but docs.rs uses rustc 1.22 and doesn't seem to like that.
                Some($Mat {
                    $lines: $CVec {
                        $($get: match self.$lines.$get.numcast() {
                            Some(x) => x,
                            None => return None,
                        },)+
                    }
                })
            }
            /// Initializes a new matrix with elements of the diagonal set to `val`
            /// and the other to zero.
            ///
            /// In a way, this is the same as single-argument matrix constructors
            /// in GLSL and GLM.
            ///
            /// ```
            /// # use vek::Mat4;
            /// assert_eq!(Mat4::broadcast_diagonal(0), Mat4::zero());
            /// assert_eq!(Mat4::broadcast_diagonal(1), Mat4::identity());
            /// assert_eq!(Mat4::broadcast_diagonal(2), Mat4::new(
            ///     2,0,0,0,
            ///     0,2,0,0,
            ///     0,0,2,0,
            ///     0,0,0,2,
            /// ));
            /// ```
            pub fn broadcast_diagonal(val: T) -> Self where T: Zero + Copy {
                let mut out = Self::zero();
                $(out.$lines.$get.$get = val;)+
                out
            }
            /// Initializes a matrix by its diagonal, setting other elements to zero.
            pub fn with_diagonal(d: $Vec<T>) -> Self where T: Zero + Copy {
                let mut out = Self::zero();
                $(out.$lines.$get.$get = d.$get;)+
                out
            }
            /// Gets the matrix's diagonal into a vector.
            ///
            /// ```
            /// # use vek::{Mat4, Vec4};
            /// assert_eq!(Mat4::<u32>::zero().diagonal(), Vec4::zero());
            /// assert_eq!(Mat4::<u32>::identity().diagonal(), Vec4::one());
            ///
            /// let mut m = Mat4::zero();
            /// m[(0, 0)] = 1;
            /// m[(1, 1)] = 2;
            /// m[(2, 2)] = 3;
            /// m[(3, 3)] = 4;
            /// assert_eq!(m.diagonal(), Vec4::new(1, 2, 3, 4));
            /// assert_eq!(m.diagonal(), Vec4::iota() + 1);
            pub fn diagonal(self) -> $Vec<T> {
                $Vec::new($(self.$lines.$get.$get),+)
            }
            /// The sum of the diagonal's elements.
            ///
            /// ```
            /// # use vek::Mat4;
            /// assert_eq!(Mat4::<u32>::zero().trace(), 0);
            /// assert_eq!(Mat4::<u32>::identity().trace(), 4);
            /// ```
            pub fn trace(self) -> T where T: Add<T, Output=T> {
                self.diagonal().sum()
            }
            /// Multiply elements of this matrix with another's.
            ///
            /// ```
            /// # use vek::mat::Mat4;
            ///
            /// let m = Mat4::new(
            ///     0, 1, 2, 3,
            ///     1, 2, 3, 4,
            ///     2, 3, 4, 5,
            ///     3, 4, 5, 6,
            /// );
            /// let r = Mat4::new(
            ///     0, 1, 4, 9,
            ///     1, 4, 9, 16,
            ///     4, 9, 16, 25,
            ///     9, 16, 25, 36,
            /// );
            /// assert_eq!(m.mul_memberwise(m), r);
            /// ```
            pub fn mul_memberwise(self, m: Self) -> Self where T: Mul<Output=T> {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get * m.$lines.$get),+
                    )
                }
            }
            /// Convenience for getting the number of rows of this matrix.
            pub fn row_count(&self) -> usize {
                $nrows
            }
            /// Convenience for getting the number of columns of this matrix.
            pub fn col_count(&self) -> usize {
                $ncols
            }
            /// Convenience constant representing the number of rows for matrices of this type.
            pub const ROW_COUNT: usize = $nrows;
            /// Convenience constant representing the number of columns for matrices of this type.
            pub const COL_COUNT: usize = $ncols;

            /// Are all elements of this matrix tightly packed together in memory ?
            ///
            /// This might not be the case for matrices in the `repr_simd` module
            /// (it depends on the target architecture).
            pub fn is_packed(&self) -> bool {
                mem::size_of::<Self>() == $nrows*$ncols*mem::size_of::<T>()
            }
        }

        impl<T> Mul<T> for $Mat<T>
            where T: Copy + Zero + Add<Output=T> + Mul<Output=T>
        {
            type Output = Self;
            fn mul(self, rhs: T) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get * rhs),+
                    )
                }
            }
        }

        impl<T> MulAssign for $Mat<T>
            where T: Copy + Zero + Add<Output=T> + Mul<Output=T> + MulAdd<T,T,Output=T>
        {
            fn mul_assign(&mut self, rhs: Self) { *self = *self * rhs; }
        }

        impl<T> MulAssign<T> for $Mat<T>
            where T: Copy + Zero + Add<Output=T> + Mul<Output=T>
        {
            fn mul_assign(&mut self, rhs: T) { *self = *self * rhs; }
        }


        impl<T> Add for $Mat<T> where T: Add<Output=T> {
            type Output = Self;
            fn add(self, rhs: Self) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get + rhs.$lines.$get),+
                    )
                }
            }
        }
        impl<T> Sub for $Mat<T> where T: Sub<Output=T> {
            type Output = Self;
            fn sub(self, rhs: Self) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get - rhs.$lines.$get),+
                    )
                }
            }
        }
        impl<T> Div for $Mat<T> where T: Div<Output=T> {
            type Output = Self;
            fn div(self, rhs: Self) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get / rhs.$lines.$get),+
                    )
                }
            }
        }
        impl<T> Rem for $Mat<T> where T: Rem<Output=T> {
            type Output = Self;
            fn rem(self, rhs: Self) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get % rhs.$lines.$get),+
                    )
                }
            }
        }
        impl<T> Neg for $Mat<T> where T: Neg<Output=T> {
            type Output = Self;
            fn neg(self) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(-self.$lines.$get),+
                    )
                }
            }
        }

        impl<T> Add<T> for $Mat<T> where T: Copy + Add<Output=T> {
            type Output = Self;
            fn add(self, rhs: T) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get + rhs),+
                    )
                }
            }
        }
        impl<T> Sub<T> for $Mat<T> where T: Copy + Sub<Output=T> {
            type Output = Self;
            fn sub(self, rhs: T) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get - rhs),+
                    )
                }
            }
        }
        impl<T> Div<T> for $Mat<T> where T: Copy + Div<Output=T> {
            type Output = Self;
            fn div(self, rhs: T) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get / rhs),+
                    )
                }
            }
        }
        impl<T> Rem<T> for $Mat<T> where T: Copy + Rem<Output=T> {
            type Output = Self;
            fn rem(self, rhs: T) -> Self::Output {
                Self {
                    $lines: $CVec::new(
                        $(self.$lines.$get % rhs),+
                    )
                }
            }
        }

        impl<T: Add<Output=T> + Copy> AddAssign    for $Mat<T> { fn add_assign(&mut self, rhs: Self) { *self = *self + rhs; } }
        impl<T: Add<Output=T> + Copy> AddAssign<T> for $Mat<T> { fn add_assign(&mut self, rhs: T   ) { *self = *self + rhs; } }
        impl<T: Sub<Output=T> + Copy> SubAssign    for $Mat<T> { fn sub_assign(&mut self, rhs: Self) { *self = *self - rhs; } }
        impl<T: Sub<Output=T> + Copy> SubAssign<T> for $Mat<T> { fn sub_assign(&mut self, rhs: T   ) { *self = *self - rhs; } }
        impl<T: Div<Output=T> + Copy> DivAssign    for $Mat<T> { fn div_assign(&mut self, rhs: Self) { *self = *self / rhs; } }
        impl<T: Div<Output=T> + Copy> DivAssign<T> for $Mat<T> { fn div_assign(&mut self, rhs: T   ) { *self = *self / rhs; } }
        impl<T: Rem<Output=T> + Copy> RemAssign    for $Mat<T> { fn rem_assign(&mut self, rhs: Self) { *self = *self % rhs; } }
        impl<T: Rem<Output=T> + Copy> RemAssign<T> for $Mat<T> { fn rem_assign(&mut self, rhs: T   ) { *self = *self % rhs; } }

        impl<T: AbsDiffEq> AbsDiffEq for $Mat<T> where T::Epsilon: Copy {
            type Epsilon = T::Epsilon;

            fn default_epsilon() -> T::Epsilon {
                T::default_epsilon()
            }

            fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
                for (l, r) in self.$lines.iter().zip(other.$lines.iter()) {
                    if !AbsDiffEq::abs_diff_eq(l, r, epsilon) {
                        return false;
                    }
                }
                true
            }
        }

        impl<T: UlpsEq> UlpsEq for $Mat<T> where T::Epsilon: Copy {
            fn default_max_ulps() -> u32 {
                T::default_max_ulps()
            }

            fn ulps_eq(&self, other: &Self, epsilon: T::Epsilon, max_ulps: u32) -> bool {
                for (l, r) in self.$lines.iter().zip(other.$lines.iter()) {
                    if !UlpsEq::ulps_eq(l, r, epsilon, max_ulps) {
                        return false;
                    }
                }
                true
            }
        }

        impl<T: RelativeEq> RelativeEq for $Mat<T> where T::Epsilon: Copy {
            fn default_max_relative() -> T::Epsilon {
                T::default_max_relative()
            }

            fn relative_eq(&self, other: &Self, epsilon: T::Epsilon, max_relative: T::Epsilon) -> bool {
                for (l, r) in self.$lines.iter().zip(other.$lines.iter()) {
                    if !RelativeEq::relative_eq(l, r, epsilon, max_relative) {
                        return false;
                    }
                }
                true
            }
        }

    };
}


macro_rules! mat_impl_mat4 {
    (rows) => {

        impl<T> Mat4<T> {
            /// Creates a new 4x4 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T, m02: T, m03: T,
                m10: T, m11: T, m12: T, m13: T,
                m20: T, m21: T, m22: T, m23: T,
                m30: T, m31: T, m32: T, m33: T
            ) -> Self {
                Self {
                    rows: CVec4::new(
                        Vec4::new(m00, m01, m02, m03),
                        Vec4::new(m10, m11, m12, m13),
                        Vec4::new(m20, m21, m22, m23),
                        Vec4::new(m30, m31, m32, m33)
                    )
                }
            }
        }
        mat_impl_mat4!{common rows}
    };
    (cols) => {
        impl<T> Mat4<T> {
            /// Creates a new 4x4 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T, m02: T, m03: T,
                m10: T, m11: T, m12: T, m13: T,
                m20: T, m21: T, m22: T, m23: T,
                m30: T, m31: T, m32: T, m33: T
            ) -> Self {
                Self {
                    cols: CVec4::new(
                        Vec4::new(m00, m10, m20, m30),
                        Vec4::new(m01, m11, m21, m31),
                        Vec4::new(m02, m12, m22, m32),
                        Vec4::new(m03, m13, m23, m33)
                    )
                }
            }
        }
        mat_impl_mat4!{common cols}
    };
    (common $lines:ident) => {

        use super::row_major::Mat4 as Rows4;
        use super::column_major::Mat4 as Cols4;

        impl<T> Mat4<T> {
            /// Returns an element-wise-converted copy of this matrix, using the given conversion
            /// closure.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<f32>::new(
            ///     0.25, 1.25, 5.56, 8.66,
            ///     8.53, 2.92, 3.86, 9.36,
            ///     1.02, 0.28, 5.52, 6.06,
            ///     6.20, 7.01, 4.90, 5.26
            /// );
            /// let m = m.map(|x| x.round() as i32);
            /// assert_eq!(m, Mat4::new(
            ///     0, 1, 6, 9,
            ///     9, 3, 4, 9,
            ///     1, 0, 6, 6,
            ///     6, 7, 5, 5
            /// ));
            /// ```
            pub fn map<D,F>(self, mut f: F) -> Mat4<D> where F: FnMut(T) -> D {
                let m = self.$lines;
                Mat4 {
                    $lines: CVec4::new(
                        Vec4::new(f(m.x.x), f(m.x.y), f(m.x.z), f(m.x.w)),
                        Vec4::new(f(m.y.x), f(m.y.y), f(m.y.z), f(m.y.w)),
                        Vec4::new(f(m.z.x), f(m.z.y), f(m.z.z), f(m.z.w)),
                        Vec4::new(f(m.w.x), f(m.w.y), f(m.w.z), f(m.w.w))
                    )
                }
            }

            /// Returns a memberwise-converted copy of this matrix, using `AsPrimitive`.
            ///
            /// # Examples
            ///
            /// ```
            /// # use vek::vec::Vec4;
            /// let v = Vec4::new(0_f32, 1., 2., 3.);
            /// let i: Vec4<i32> = v.as_();
            /// assert_eq!(i, Vec4::new(0, 1, 2, 3));
            /// ```
            ///
            /// # Safety
            ///
            /// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe.
            /// In particular, it was undefined behavior if
            /// a truncated floating point value could not fit in the target integer
            /// type ([#10184](https://github.com/rust-lang/rust/issues/10184));
            ///
            /// ```ignore
            /// # use num_traits::AsPrimitive;
            /// let x: u8 = (1.04E+17).as_(); // UB
            /// ```
            pub fn as_<D>(self) -> Mat4<D> where T: AsPrimitive<D>, D: 'static + Copy {
                let m = self.$lines;
                Mat4 {
                    $lines: CVec4::new(
                        Vec4::new(m.x.x.as_(), m.x.y.as_(), m.x.z.as_(), m.x.w.as_()),
                        Vec4::new(m.y.x.as_(), m.y.y.as_(), m.y.z.as_(), m.y.w.as_()),
                        Vec4::new(m.z.x.as_(), m.z.y.as_(), m.z.z.as_(), m.z.w.as_()),
                        Vec4::new(m.w.x.as_(), m.w.y.as_(), m.w.z.as_(), m.w.w.as_())
                    )
                }
            }

            /// Applies the function f to each element of two matrices, pairwise, and returns the result.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let a = Mat4::<f32>::new(
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99
            /// );
            /// let b = Mat4::<i32>::new(
            ///     0, 1, 0, 0,
            ///     1, 0, 0, 0,
            ///     0, 0, 1, 0,
            ///     0, 0, 0, 1
            /// );
            /// let m = a.map2(b, |a, b| a.round() as i32 + b);
            /// assert_eq!(m, Mat4::new(
            ///     0, 2, 3, 3,
            ///     1, 1, 3, 3,
            ///     0, 1, 4, 3,
            ///     0, 1, 3, 4
            /// ));
            /// ```
            pub fn map2<D,F,S>(self, other: Mat4<S>, mut f: F) -> Mat4<D> where F: FnMut(T, S) -> D {
                let m = self.$lines;
                let o = other.$lines;
                Mat4 {
                    $lines: CVec4::new(
                        Vec4::new(f(m.x.x, o.x.x), f(m.x.y, o.x.y), f(m.x.z, o.x.z), f(m.x.w, o.x.w)),
                        Vec4::new(f(m.y.x, o.y.x), f(m.y.y, o.y.y), f(m.y.z, o.y.z), f(m.y.w, o.y.w)),
                        Vec4::new(f(m.z.x, o.z.x), f(m.z.y, o.z.y), f(m.z.z, o.z.z), f(m.z.w, o.z.w)),
                        Vec4::new(f(m.w.x, o.w.x), f(m.w.y, o.w.y), f(m.w.z, o.w.z), f(m.w.w, o.w.w))
                    )
                }
            }

            /// The matrix's transpose.
            ///
            /// For orthogonal matrices, the transpose is the same as the inverse.
            /// All pure rotation matrices are orthogonal, and therefore can be inverted
            /// faster by simply computing their transpose.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::Mat4;
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let m = Mat4::new(
            ///     0, 1, 2, 3,
            ///     4, 5, 6, 7,
            ///     8, 9, 0, 1,
            ///     2, 3, 4, 5
            /// );
            /// let t = Mat4::new(
            ///     0, 4, 8, 2,
            ///     1, 5, 9, 3,
            ///     2, 6, 0, 4,
            ///     3, 7, 1, 5
            /// );
            /// assert_eq!(m.transposed(), t);
            /// assert_eq!(m, m.transposed().transposed());
            ///
            /// // By the way, demonstrate ways to invert a rotation matrix,
            /// // from fastest (specific) to slowest (general-purpose).
            /// let m = Mat4::rotation_x(PI/7.);
            /// let id = Mat4::identity();
            /// assert_relative_eq!(id, m * m.transposed());
            /// assert_relative_eq!(id, m.transposed() * m);
            /// assert_relative_eq!(id, m * m.inverted_affine_transform_no_scale());
            /// assert_relative_eq!(id, m.inverted_affine_transform_no_scale() * m);
            /// assert_relative_eq!(id, m * m.inverted_affine_transform());
            /// assert_relative_eq!(id, m.inverted_affine_transform() * m);
            /// assert_relative_eq!(id, m * m.inverted());
            /// assert_relative_eq!(id, m.inverted() * m);
            /// # }
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transposed(self) -> Self {
                let s = self.$lines;
                Self {
                    $lines: CVec4::new(
                        Vec4::new(s.x.x, s.y.x, s.z.x, s.w.x),
                        Vec4::new(s.x.y, s.y.y, s.z.y, s.w.y),
                        Vec4::new(s.x.z, s.y.z, s.z.z, s.w.z),
                        Vec4::new(s.x.w, s.y.w, s.z.w, s.w.w)
                    )
                }
            }
            /// Transpose this matrix.
            ///
            /// ```
            /// # use vek::mat::Mat4;
            ///
            /// let mut m = Mat4::new(
            ///     0, 1, 2, 3,
            ///     4, 5, 6, 7,
            ///     8, 9, 0, 1,
            ///     2, 3, 4, 5
            /// );
            /// let t = Mat4::new(
            ///     0, 4, 8, 2,
            ///     1, 5, 9, 3,
            ///     2, 6, 0, 4,
            ///     3, 7, 1, 5
            /// );
            /// m.transpose();
            /// assert_eq!(m, t);
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transpose(&mut self) {
                mem::swap(&mut self.$lines.x.y, &mut self.$lines.y.x);
                mem::swap(&mut self.$lines.x.z, &mut self.$lines.z.x);
                mem::swap(&mut self.$lines.x.w, &mut self.$lines.w.x);
                mem::swap(&mut self.$lines.y.z, &mut self.$lines.z.y);
                mem::swap(&mut self.$lines.y.w, &mut self.$lines.w.y);
                mem::swap(&mut self.$lines.z.w, &mut self.$lines.w.z);
            }

            /// Get this matrix's determinant.
            ///
            /// A matrix is invertible if its determinant is non-zero.
            pub fn determinant(self) -> T where T: Copy + Mul<T,Output=T> + Sub<T,Output=T> + Add<T, Output=T> {
                // http://www.euclideanspace.com/maths/algebra/matrix/functions/determinant/fourD/index.htm
                let CVec4 {
                    x: Vec4 { x: m00, y: m01, z: m02, w: m03 },
                    y: Vec4 { x: m10, y: m11, z: m12, w: m13 },
                    z: Vec4 { x: m20, y: m21, z: m22, w: m23 },
                    w: Vec4 { x: m30, y: m31, z: m32, w: m33 },
                } = Rows4::from(self).rows;
                m03 * m12 * m21 * m30 - m02 * m13 * m21 * m30 -
                m03 * m11 * m22 * m30 + m01 * m13 * m22 * m30 +
                m02 * m11 * m23 * m30 - m01 * m12 * m23 * m30 -
                m03 * m12 * m20 * m31 + m02 * m13 * m20 * m31 +
                m03 * m10 * m22 * m31 - m00 * m13 * m22 * m31 -
                m02 * m10 * m23 * m31 + m00 * m12 * m23 * m31 +
                m03 * m11 * m20 * m32 - m01 * m13 * m20 * m32 -
                m03 * m10 * m21 * m32 + m00 * m13 * m21 * m32 +
                m01 * m10 * m23 * m32 - m00 * m11 * m23 * m32 -
                m02 * m11 * m20 * m33 + m01 * m12 * m20 * m33 +
                m02 * m10 * m21 * m33 - m00 * m12 * m21 * m33 -
                m01 * m10 * m22 * m33 + m00 * m11 * m22 * m33
            }

            //
            // BASIC
            //

            /// Inverts this matrix, blindly assuming that it is invertible.
            /// See `inverted()` for more info.
            pub fn invert(&mut self) where T: Real {
                *self = self.inverted()
            }
            /// Returns this matrix's inverse, blindly assuming that it is invertible.
            ///
            /// All affine matrices have inverses; Your matrices may be affine
            /// as long as they consist of any combination of pure rotations,
            /// translations, scales and shears.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// use vek::vec::repr_c::Vec3;
            /// use vek::mat::repr_c::row_major::Mat4 as Rows4;
            /// use vek::mat::repr_c::column_major::Mat4 as Cols4;
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let a = Rows4::scaling_3d(1.77_f32)
            ///     .rotated_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted();
            /// assert_relative_eq!(a*b, Rows4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Rows4::identity(), epsilon = 0.000001);
            ///
            /// let a = Cols4::scaling_3d(1.77_f32)
            ///     .rotated_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted();
            /// assert_relative_eq!(a*b, Cols4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Cols4::identity(), epsilon = 0.000001);
            ///
            /// // Beware, projection matrices are not invertible!
            /// // Notice that we assert _inequality_ below.
            /// let a = Cols4::perspective_rh_zo(60_f32.to_radians(), 16./9., 0.001, 1000.) * a;
            /// let b = a.inverted();
            /// assert_relative_ne!(a*b, Cols4::identity(), epsilon = 0.000001);
            /// assert_relative_ne!(b*a, Cols4::identity(), epsilon = 0.000001);
            /// # }
            /// ```
            // NOTE: Stolen from
            // https://lxjk.github.io/2017/09/03/Fast-4x4-Matrix-Inverse-with-SSE-SIMD-Explained.html
            pub fn inverted(self) -> Self where T: Real
            {
                // NOTE: The VecShuffle_2323() macro in the article swaps its arguments
                let m = self.$lines;
                let a = Vec4::shuffle_lo_hi_0101(m.x, m.y);
                let b = Vec4::shuffle_hi_lo_2323(m.y, m.x);
                let c = Vec4::shuffle_lo_hi_0101(m.z, m.w);
                let d = Vec4::shuffle_hi_lo_2323(m.w, m.z);

                let det_a = Vec4::broadcast(m.x.x * m.y.y - m.x.y * m.y.x);
                let det_b = Vec4::broadcast(m.x.z * m.y.w - m.x.w * m.y.z);
                let det_c = Vec4::broadcast(m.z.x * m.w.y - m.z.y * m.w.x);
                let det_d = Vec4::broadcast(m.z.z * m.w.w - m.z.w * m.w.z);

                let d_c = d.mat2_rows_adj_mul(c);
                let a_b = a.mat2_rows_adj_mul(b);
                let x_ = det_d * a - b.mat2_rows_mul(d_c);
                let w_ = det_a * d - c.mat2_rows_mul(a_b);
                let y_ = det_b * c - d.mat2_rows_mul_adj(a_b);
                let z_ = det_c * b - a.mat2_rows_mul_adj(d_c);

                let tr = a_b * d_c.shuffled((0,2,1,3));
                let tr = tr.hadd(tr);
                let tr = tr.hadd(tr);

                let det_m = det_a * det_d + det_b * det_c - tr;

                let adj_sign_mask = Vec4::new(T::one(), -T::one(), -T::one(), T::one());
                let r_det_m = adj_sign_mask / det_m;

                let x_ = x_ * r_det_m;
                let y_ = y_ * r_det_m;
                let z_ = z_ * r_det_m;
                let w_ = w_ * r_det_m;

                Self {
                    $lines: CVec4::new(
                        Vec4::shuffle_lo_hi(x_, y_, (3,1,3,1)),
                        Vec4::shuffle_lo_hi(x_, y_, (2,0,2,0)),
                        Vec4::shuffle_lo_hi(z_, w_, (3,1,3,1)),
                        Vec4::shuffle_lo_hi(z_, w_, (2,0,2,0))
                    )
                }
            }

            /// Returns this matrix's inverse, blindly assuming that it is an invertible transform
            /// matrix which scale is 1.
            ///
            /// See `inverted_affine_transform_no_scale()` for more info.
            pub fn invert_affine_transform_no_scale(&mut self) where T: Real {
                *self = self.inverted_affine_transform_no_scale()
            }
            /// Returns this matrix's inverse, blindly assuming that it is an invertible transform
            /// matrix which scale is 1.
            ///
            /// A transform matrix is invertible this way as long as it consists
            /// of translations, rotations, and shears.
            /// **It's not guaranteed to work if the scale is not 1.**
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// use vek::vec::repr_c::Vec3;
            /// use vek::mat::repr_c::row_major::Mat4 as Rows4;
            /// use vek::mat::repr_c::column_major::Mat4 as Cols4;
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let a = Rows4::rotation_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted_affine_transform_no_scale();
            /// assert_relative_eq!(a*b, Rows4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Rows4::identity(), epsilon = 0.000001);
            ///
            /// let a = Cols4::rotation_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted_affine_transform_no_scale();
            /// assert_relative_eq!(a*b, Cols4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Cols4::identity(), epsilon = 0.000001);
            ///
            /// // Look! It stops working as soon as we add a scale.
            /// // Notice that we assert _inequality_ below.
            /// let a = Rows4::scaling_3d(5_f32)
            ///     .rotated_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted_affine_transform_no_scale();
            /// assert_relative_ne!(a*b, Rows4::identity(), epsilon = 0.000001);
            /// assert_relative_ne!(b*a, Rows4::identity(), epsilon = 0.000001);
            /// # }
            /// ```
            // NOTE: Stolen from
            // https://lxjk.github.io/2017/09/03/Fast-4x4-Matrix-Inverse-with-SSE-SIMD-Explained.html
            pub fn inverted_affine_transform_no_scale(self) -> Self where T: Real
            {
                // NOTE: The VecShuffle_2323() macro in the article swaps its arguments
                let m = Cols4::from(self).cols;
                let t0 = Vec4::shuffle_lo_hi_0101(m.x, m.y);
                let t1 = Vec4::shuffle_hi_lo_2323(m.y, m.x);
                let r0 = Vec4::shuffle_lo_hi(t0, m.z, (0,2,0,3));
                let r1 = Vec4::shuffle_lo_hi(t0, m.z, (1,3,1,3));
                let r2 = Vec4::shuffle_lo_hi(t1, m.z, (0,2,2,3));
                let r3 = Vec4::unit_w()
                       - r0 * m.w.shuffled(0)
                       - r1 * m.w.shuffled(1)
                       - r2 * m.w.shuffled(2);
                Cols4 { cols: CVec4::new(r0, r1, r2, r3) }.into()
            }
            /// Inverts this matrix, blindly assuming that it is an invertible transform matrix.
            /// See `inverted_affine_transform()` for more info.
            pub fn invert_affine_transform(&mut self) where T: Real {
                *self = self.inverted_affine_transform()
            }
            /// Returns this matrix's inverse, blindly assuming that it is an invertible transform
            /// matrix.
            ///
            /// A transform matrix is invertible this way as long as it consists
            /// of translations, rotations, scales and shears.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// use vek::vec::repr_c::Vec3;
            /// use vek::mat::repr_c::row_major::Mat4 as Rows4;
            /// use vek::mat::repr_c::column_major::Mat4 as Cols4;
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let a = Rows4::scaling_3d(1.77_f32)
            ///     .rotated_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted_affine_transform();
            /// assert_relative_eq!(a*b, Rows4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Rows4::identity(), epsilon = 0.000001);
            ///
            /// let a = Cols4::scaling_3d(1.77_f32)
            ///     .rotated_3d(PI*4./5., Vec3::new(5., 8., 10.))
            ///     .translated_3d(Vec3::new(1., 2., 3.));
            /// let b = a.inverted_affine_transform();
            /// assert_relative_eq!(a*b, Cols4::identity(), epsilon = 0.000001);
            /// assert_relative_eq!(b*a, Cols4::identity(), epsilon = 0.000001);
            /// # }
            /// ```
            // NOTE: Stolen from
            // https://lxjk.github.io/2017/09/03/Fast-4x4-Matrix-Inverse-with-SSE-SIMD-Explained.html
            pub fn inverted_affine_transform(self) -> Self where T: Real
            {
                // NOTE: The VecShuffle_2323() macro in the article swaps its arguments
                let m = Cols4::from(self).cols;
                let t0 = Vec4::shuffle_lo_hi_0101(m.x, m.y);
                let t1 = Vec4::shuffle_hi_lo_2323(m.y, m.x);
                let r0 = Vec4::shuffle_lo_hi(t0, m.z, (0,2,0,3));
                let r1 = Vec4::shuffle_lo_hi(t0, m.z, (1,3,1,3));
                let r2 = Vec4::shuffle_lo_hi(t1, m.z, (0,2,2,3));
                // PERF: Could use mul_add()
                let size_sqr = r0 * r0 + r1 * r1 + r2 * r2;
                let epsilon = T::epsilon(); // XXX: Might prefer the one from RelativeEq ???
                // PERF: Could use _mm_blendv_ps(), like in this part of the article's source code.
                let size_sqr = size_sqr.map(|x| if x.abs() > epsilon { x } else { T::one() });
                let r0 = r0 / size_sqr;
                let r1 = r1 / size_sqr;
                let r2 = r2 / size_sqr;
                let r3 = Vec4::unit_w()
                       - r0 * m.w.shuffled(0)
                       - r1 * m.w.shuffled(1)
                       - r2 * m.w.shuffled(2);
                Cols4 { cols: CVec4::new(r0, r1, r2, r3) }.into()
            }




            #[allow(dead_code)]
            /// XXX I don't know exactly what this does. Make it public when I do.
            fn orthonormalize(&mut self) where T: Real + Add<T, Output=T> + SubAssign {
                *self = self.orthonormalized();
            }
            #[allow(dead_code)]
            /// XXX I don't know exactly what this does. Make it public when I do.
            // Taken verbatim from linmath.h - I don't know exactly what it does.
            fn orthonormalized(self) -> Self where T: Real + Add<T, Output=T> + SubAssign {
                let mut r = Rows4::from(self).rows;

                r[2] = r[2].normalized();

                let s = r[1].dot(r[2]);
                let h = r[2] * s;
                r[1] -= h;

                r[1] -= h;
                r[1] = r[1].normalized();

                let s = r[0].dot(r[1]);
                let h = r[1] * s;
                r[0] -= h;
                r[0] = r[0].normalized();

                Rows4 { rows: r }.into()
            }


            //
            // MULTIPLY BY
            //

            /// Shortcut for `self * Vec4::from_point(rhs)`.
            pub fn mul_point<V: Into<Vec3<T>> + From<Vec4<T>>>(self, rhs: V) -> V
                where T: Real + MulAdd<T,T,Output=T>
            {
                V::from(self * Vec4::from_point(rhs))
            }
            /// Shortcut for `self * Vec4::from_direction(rhs)`.
            pub fn mul_direction<V: Into<Vec3<T>> + From<Vec4<T>>>(self, rhs: V) -> V
                where T: Real + MulAdd<T,T,Output=T>
            {
                V::from(self * Vec4::from_direction(rhs))
            }

            //
            // TRANSFORMS
            //

            /// Translates this matrix in 2D.
            pub fn translate_2d<V: Into<Vec2<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.translated_2d(v);
            }
            /// Returns this matrix translated in 2D.
            pub fn translated_2d<V: Into<Vec2<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::translation_2d(v) * self
            }
            /// Creates a 2D translation matrix.
            pub fn translation_2d<V: Into<Vec2<T>>>(v: V) -> Self where T: Zero + One {
                let Vec2 { x, y } = v.into();
                Self::new(
                    T::one() , T::zero(), T::zero(), x,
                    T::zero(), T::one() , T::zero(), y,
                    T::zero(), T::zero(), T::one() , T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one(),
                )
            }
            /// Translates this matrix in 3D.
            pub fn translate_3d<V: Into<Vec3<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.translated_3d(v);
            }
            /// Returns this matrix translated in 3D.
            pub fn translated_3d<V: Into<Vec3<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::translation_3d(v) * self
            }
            /// Creates a 3D translation matrix.
            pub fn translation_3d<V: Into<Vec3<T>>>(v: V) -> Self where T: Zero + One {
                let Vec3 { x, y, z } = v.into();
                Self::new(
                    T::one() , T::zero(), T::zero(), x,
                    T::zero(), T::one() , T::zero(), y,
                    T::zero(), T::zero(), T::one() , z,
                    T::zero(), T::zero(), T::zero(), T::one(),
                )
            }
            #[allow(dead_code)]
            /// XXX: This was from linmath.h. I'm not confident what this does. Make it pub when I do.
            fn translate_in_place_3d<V: Into<Vec3<T>>>(&mut self, v: V) where T: Copy + Zero + One + AddAssign + Add<T, Output=T> {
                let Vec3 { x, y, z } = v.into();
                let t = Vec4 { x, y, z, w: T::zero() };
                let mut rows = Rows4::from(*self).rows;
                rows[3] = [
                    rows[0].dot(t),
                    rows[1].dot(t),
                    rows[2].dot(t),
                    rows[3].dot(t),
                ].into();
                *self = Rows4 { rows }.into();
            }

            /// Scales this matrix in 3D.
            pub fn scale_3d<V: Into<Vec3<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.scaled_3d(v);
            }
            /// Returns this matrix scaled in 3D.
            pub fn scaled_3d<V: Into<Vec3<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::scaling_3d(v) * self
            }
            /// Creates a 3D scaling matrix.
            pub fn scaling_3d<V: Into<Vec3<T>>>(v: V) -> Self where T: Zero + One {
                let Vec3 { x, y, z } = v.into();
                Self::new(
                    x, T::zero(), T::zero(), T::zero(),
                    T::zero(), y, T::zero(), T::zero(),
                    T::zero(), T::zero(), z, T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
            /// Rotates this matrix around the X axis.
            pub fn rotate_x(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_x(angle_radians);
            }
            /// Returns this matrix rotated around the X axis.
            pub fn rotated_x(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_x(angle_radians) * self
            }
            /// Creates a matrix that rotates around the X axis.
            pub fn rotation_x(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    T::one(), T::zero(), T::zero(), T::zero(),
                    T::zero(), c, -s, T::zero(),
                    T::zero(), s, c, T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
            /// Rotates this matrix around the Y axis.
            pub fn rotate_y(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_y(angle_radians);
            }
            /// Returns this matrix rotated around the Y axis.
            pub fn rotated_y(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_y(angle_radians) * self
            }
            /// Creates a matrix that rotates around the Y axis.
            pub fn rotation_y(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    c, T::zero(), s, T::zero(),
                    T::zero(), T::one(), T::zero(), T::zero(),
                    -s, T::zero(), c, T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
            /// Rotates this matrix around the Z axis.
            pub fn rotate_z(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_z(angle_radians);
            }
            /// Returns this matrix rotated around the Z axis.
            pub fn rotated_z(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_z(angle_radians) * self
            }
            /// Creates a matrix that rotates around the Z axis.
            pub fn rotation_z(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    c, -s, T::zero(), T::zero(),
                    s,  c, T::zero(), T::zero(),
                    T::zero(), T::zero(), T::one(), T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
            /// Rotates this matrix around a 3D axis.
            /// The axis is not required to be normalized.
            pub fn rotate_3d<V: Into<Vec3<T>>>(&mut self, angle_radians: T, axis: V)
                where T: Real + MulAdd<T,T,Output=T> + Add<T, Output=T>
            {
                *self = self.rotated_3d(angle_radians, axis);
            }
            /// Returns this matrix rotated around a 3D axis.
            /// The axis is not required to be normalized.
            pub fn rotated_3d<V: Into<Vec3<T>>>(self, angle_radians: T, axis: V) -> Self
                where T: Real + MulAdd<T,T,Output=T> + Add<T, Output=T>
            {
                Self::rotation_3d(angle_radians, axis) * self
            }
            /// Creates a matrix that rotates around a 3D axis.
            /// The axis is not required to be normalized.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec4};
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let v = Vec4::unit_x();
            ///
            /// let m = Mat4::rotation_z(PI);
            /// assert_relative_eq!(m * v, -v);
            ///
            /// let m = Mat4::rotation_z(PI * 0.5);
            /// assert_relative_eq!(m * v, Vec4::unit_y());
            ///
            /// let m = Mat4::rotation_z(PI * 1.5);
            /// assert_relative_eq!(m * v, -Vec4::unit_y());
            ///
            /// let angles = 32;
            /// for i in 0..angles {
            ///     let theta = PI * 2. * (i as f32) / (angles as f32);
            ///
            ///     // See what rotating unit vectors do for most angles between 0 and 2*PI.
            ///     // It's helpful to picture this as a right-handed coordinate system.
            ///
            ///     let v = Vec4::unit_y();
            ///     let m = Mat4::rotation_x(theta);
            ///     assert_relative_eq!(m * v, Vec4::new(0., theta.cos(), theta.sin(), 0.));
            ///
            ///     let v = Vec4::unit_z();
            ///     let m = Mat4::rotation_y(theta);
            ///     assert_relative_eq!(m * v, Vec4::new(theta.sin(), 0., theta.cos(), 0.));
            ///
            ///     let v = Vec4::unit_x();
            ///     let m = Mat4::rotation_z(theta);
            ///     assert_relative_eq!(m * v, Vec4::new(theta.cos(), theta.sin(), 0., 0.));
            ///
            ///     assert_relative_eq!(Mat4::rotation_x(theta), Mat4::rotation_3d(theta, Vec4::unit_x()));
            ///     assert_relative_eq!(Mat4::rotation_y(theta), Mat4::rotation_3d(theta, Vec4::unit_y()));
            ///     assert_relative_eq!(Mat4::rotation_z(theta), Mat4::rotation_3d(theta, Vec4::unit_z()));
            /// }
            /// # }
            /// ```
            pub fn rotation_3d<V: Into<Vec3<T>>>(angle_radians: T, axis: V) -> Self where T: Real + Add<T, Output=T> {
                let Vec3 { x, y, z } = axis.into().normalized();
                let s = angle_radians.sin();
                let c = angle_radians.cos();
                let oc = T::one() - c;
                Self::new(
                    oc*x*x + c  , oc*x*y - z*s, oc*z*x + y*s, T::zero(),
                    oc*x*y + z*s, oc*y*y + c  , oc*y*z - x*s, T::zero(),
                    oc*z*x - y*s, oc*y*z + x*s, oc*z*z + c  , T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }


            /// Creates a matrix that would rotate a `from` direction to `to`.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Vec4, Mat4};
            ///
            /// # fn main() {
            /// let (from, to) = (Vec4::<f32>::unit_x(), Vec4::<f32>::unit_z());
            /// let m = Mat4::<f32>::rotation_from_to_3d(from, to);
            /// assert_relative_eq!(m * from, to);
            ///
            /// let (from, to) = (Vec4::<f32>::unit_x(), -Vec4::<f32>::unit_x());
            /// let m = Mat4::<f32>::rotation_from_to_3d(from, to);
            /// assert_relative_eq!(m * from, to);
            /// # }
            /// ```
            pub fn rotation_from_to_3d<V: Into<Vec3<T>>>(from: V, to: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                Self::from(Quaternion::rotation_from_to_3d(from, to))
            }

            //
            // CHANGE OF BASIS
            //

            /// Builds a change of basis matrix that transforms points and directions from
            /// any space to the canonical one.
            ///
            /// `origin` is the origin of the child space.
            /// `i`, `j` and `k` are all required to be normalized;
            /// They are the unit basis vector along the target space x-axis, y-axis and z-axis
            /// respectively, expressed in canonical-space coordinates.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec3};
            /// # fn main() {
            ///     let origin = Vec3::new(1_f32, 2., 3.);
            ///     let i = Vec3::unit_z();
            ///     let j = Vec3::unit_y();
            ///     let k = Vec3::unit_x();
            ///     let m = Mat4::basis_to_local(origin, i, j, k);
            ///     assert_relative_eq!(m.mul_point(origin), Vec3::zero());
            ///     assert_relative_eq!(m.mul_point(origin+i), Vec3::unit_x());
            ///     assert_relative_eq!(m.mul_point(origin+j), Vec3::unit_y());
            ///     assert_relative_eq!(m.mul_point(origin+k), Vec3::unit_z());
            ///
            ///     // `local_to_basis` and `basis_to_local` undo each other
            ///     let a = Mat4::<f32>::basis_to_local(origin, i, j, k);
            ///     let b = Mat4::<f32>::local_to_basis(origin, i, j, k);
            ///     assert_relative_eq!(a*b, Mat4::identity());
            ///     assert_relative_eq!(b*a, Mat4::identity());
            /// # }
            /// ```
            ///
            /// Slightly more contrived example:
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec3};
            /// # fn main() {
            ///     let origin = Vec3::new(1_f32, 2., 3.);
            ///     let r = Mat4::rotation_3d(3., Vec3::new(2_f32, 1., 3.));
            ///     let i = r.mul_direction(Vec3::unit_x());
            ///     let j = r.mul_direction(Vec3::unit_y());
            ///     let k = r.mul_direction(Vec3::unit_z());
            ///     let m = Mat4::basis_to_local(origin, i, j, k);
            ///     assert_relative_eq!(m.mul_point(origin), Vec3::zero(), epsilon = 0.000001);
            ///     assert_relative_eq!(m.mul_point(origin+i), Vec3::unit_x(), epsilon = 0.000001);
            ///     assert_relative_eq!(m.mul_point(origin+j), Vec3::unit_y(), epsilon = 0.000001);
            ///     assert_relative_eq!(m.mul_point(origin+k), Vec3::unit_z(), epsilon = 0.000001);
            /// # }
            /// ```
            pub fn basis_to_local<V: Into<Vec3<T>>>(origin: V, i: V, j: V, k: V) -> Self
                where T: Zero + One + Neg<Output=T> + Real + Add<T, Output=T>
            {
                let (origin, i, j, k) = (origin.into(), i.into(), j.into(), k.into());
                Self::new(
                    i.x, i.y, i.z, -i.dot(origin),
                    j.x, j.y, j.z, -j.dot(origin),
                    k.x, k.y, k.z, -k.dot(origin),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
            /// Builds a change of basis matrix that transforms points and directions from
            /// canonical space to another space.
            ///
            /// `origin` is the origin of the child space.
            /// `i`, `j` and `k` are all required to be normalized;
            /// They are the unit basis vector along the target space x-axis, y-axis and z-axis
            /// respectively, expressed in canonical-space coordinates.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec3};
            /// # fn main() {
            ///     let origin = Vec3::new(1_f32, 2., 3.);
            ///     let i = Vec3::unit_z();
            ///     let j = Vec3::unit_y();
            ///     let k = Vec3::unit_x();
            ///     let m = Mat4::local_to_basis(origin, i, j, k);
            ///     assert_relative_eq!(origin,   m.mul_point(Vec3::zero()));
            ///     assert_relative_eq!(origin+i, m.mul_point(Vec3::unit_x()));
            ///     assert_relative_eq!(origin+j, m.mul_point(Vec3::unit_y()));
            ///     assert_relative_eq!(origin+k, m.mul_point(Vec3::unit_z()));
            ///
            ///     // `local_to_basis` and `basis_to_local` undo each other
            ///     let a = Mat4::<f32>::local_to_basis(origin, i, j, k);
            ///     let b = Mat4::<f32>::basis_to_local(origin, i, j, k);
            ///     assert_relative_eq!(a*b, Mat4::identity());
            ///     assert_relative_eq!(b*a, Mat4::identity());
            /// # }
            /// ```
            ///
            /// Slightly more contrived example:
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec3};
            /// # fn main() {
            ///     // Sanity test
            ///     let origin = Vec3::new(1_f32, 2., 3.);
            ///     let r = Mat4::rotation_3d(3., Vec3::new(2_f32, 1., 3.));
            ///     let i = r.mul_direction(Vec3::unit_x());
            ///     let j = r.mul_direction(Vec3::unit_y());
            ///     let k = r.mul_direction(Vec3::unit_z());
            ///     let m = Mat4::local_to_basis(origin, i, j, k);
            ///     assert_relative_eq!(origin,   m.mul_point(Vec3::zero()));
            ///     assert_relative_eq!(origin+i, m.mul_point(Vec3::unit_x()));
            ///     assert_relative_eq!(origin+j, m.mul_point(Vec3::unit_y()));
            ///     assert_relative_eq!(origin+k, m.mul_point(Vec3::unit_z()));
            /// # }
            /// ```
            pub fn local_to_basis<V: Into<Vec3<T>>>(origin: V, i: V, j: V, k: V) -> Self where T: Zero + One {
                let (origin, i, j, k) = (origin.into(), i.into(), j.into(), k.into());
                Self::new(
                    i.x, j.x, k.x, origin.x,
                    i.y, j.y, k.y, origin.y,
                    i.z, j.z, k.z, origin.z,
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }


            //
            // VIEW
            //

            /// Builds a "look at" view transform
            /// from an eye position, a target position, and up vector.
            /// Commonly used for cameras - in short, it maps points from
            /// world-space to eye-space.
            #[deprecated(since = "0.9.7", note = "Use look_at_lh() or look_at_rh() instead depending on your space's handedness")]
            pub fn look_at<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                Self::look_at_lh(eye, target, up)
            }

            /// Builds a "look at" view transform for left-handed spaces
            /// from an eye position, a target position, and up vector.
            /// Commonly used for cameras - in short, it maps points from
            /// world-space to eye-space.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec4};
            /// # fn main() {
            /// let eye = Vec4::new(1_f32, 0., 1., 1.);
            /// let target = Vec4::new(2_f32, 0., 2., 1.);
            /// let view = Mat4::<f32>::look_at_lh(eye, target, Vec4::up());
            /// assert_relative_eq!(view * eye, Vec4::unit_w());
            /// assert_relative_eq!(view * target, Vec4::new(0_f32, 0., 2_f32.sqrt(), 1.));
            /// # }
            /// ```
            pub fn look_at_lh<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                // From GLM
                let (eye, target, up) = (eye.into(), target.into(), up.into());
                let f = (target - eye).normalized();
                let s = up.cross(f).normalized();
                let u = f.cross(s);
                Self::new(
                    s.x, s.y, s.z, -s.dot(eye),
                    u.x, u.y, u.z, -u.dot(eye),
                    f.x, f.y, f.z, -f.dot(eye),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }

            /// Builds a "look at" view transform for right-handed spaces
            /// from an eye position, a target position, and up vector.
            /// Commonly used for cameras - in short, it maps points from
            /// world-space to eye-space.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec4};
            /// # fn main() {
            /// let eye = Vec4::new(1_f32, 0., 1., 1.);
            /// let target = Vec4::new(2_f32, 0., 2., 1.);
            /// let view = Mat4::<f32>::look_at_rh(eye, target, Vec4::up());
            /// assert_relative_eq!(view * eye, Vec4::unit_w());
            /// assert_relative_eq!(view * target, Vec4::new(0_f32, 0., -2_f32.sqrt(), 1.));
            /// # }
            /// ```
            pub fn look_at_rh<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                // From GLM
                let (eye, target, up) = (eye.into(), target.into(), up.into());
                let f = (target - eye).normalized();
                let s = f.cross(up).normalized();
                let u = s.cross(f);
                Self::new(
                     s.x,  s.y,  s.z, -s.dot(eye),
                     u.x,  u.y,  u.z, -u.dot(eye),
                    -f.x, -f.y, -f.z,  f.dot(eye),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }

            /// Builds a "look at" model transform
            /// from an eye position, a target position, and up vector.
            /// Preferred for transforming objects.
            #[deprecated(since = "0.9.7", note = "Use model_look_at_lh() or model_look_at_rh() instead depending on your space's handedness")]
            pub fn model_look_at<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                Self::model_look_at_lh(eye, target, up)
            }

            /// Builds a "look at" model transform for left-handed spaces
            /// from an eye position, a target position, and up vector.
            /// Preferred for transforming objects.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec4};
            /// # fn main() {
            /// let eye = Vec4::new(1_f32, 0., 1., 1.);
            /// let target = Vec4::new(2_f32, 0., 2., 1.);
            /// let model = Mat4::<f32>::model_look_at_lh(eye, target, Vec4::up());
            /// assert_relative_eq!(model * Vec4::unit_w(), eye);
            /// let d = 2_f32.sqrt();
            /// assert_relative_eq!(model * Vec4::new(0_f32, 0., d, 1.), target);
            ///
            /// // A "model" look-at essentially undoes a "view" look-at
            /// let view = Mat4::look_at_lh(eye, target, Vec4::up());
            /// assert_relative_eq!(view * model, Mat4::identity());
            /// assert_relative_eq!(model * view, Mat4::identity());
            /// # }
            /// ```
            pub fn model_look_at_lh<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                // Advanced 3D Game Programming with DirectX 10.0, p. 173
                let (eye, target, up) = (eye.into(), target.into(), up.into());
                let f = (target - eye).normalized();
                let s = up.cross(f).normalized();
                let u = f.cross(s);
                Self::new(
                    s.x, u.x, f.x, eye.x,
                    s.y, u.y, f.y, eye.y,
                    s.z, u.z, f.z, eye.z,
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }

            /// Builds a "look at" model transform for right-handed spaces
            /// from an eye position, a target position, and up vector.
            /// Preferred for transforming objects.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Vec4};
            /// # fn main() {
            /// let eye = Vec4::new(1_f32, 0., -1., 1.);
            /// let forward = Vec4::new(0_f32, 0., -1., 0.);
            /// let model = Mat4::<f32>::model_look_at_rh(eye, eye + forward, Vec4::up());
            /// assert_relative_eq!(model * Vec4::unit_w(), eye);
            /// assert_relative_eq!(model * forward, forward);
            ///
            /// // A "model" look-at essentially undoes a "view" look-at
            /// let view = Mat4::look_at_rh(eye, eye + forward, Vec4::up());
            /// assert_relative_eq!(view * model, Mat4::identity());
            /// assert_relative_eq!(model * view, Mat4::identity());
            /// # }
            /// ```
            pub fn model_look_at_rh<V: Into<Vec3<T>>>(eye: V, target: V, up: V) -> Self
                where T: Real + Add<T, Output=T> + MulAdd<T,T,Output=T>
            {
                let (eye, target, up) = (eye.into(), target.into(), up.into());
                let f = (target - eye).normalized();
                let s = f.cross(up).normalized();
                let u = s.cross(f);
                Self::new(
                    s.x, u.x, -f.x, eye.x,
                    s.y, u.y, -f.y, eye.y,
                    s.z, u.z, -f.z, eye.z,
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }


            //
            // PROJECTIONS
            //

            /// Returns an orthographic projection matrix that doesn't use near and far planes.
            pub fn orthographic_without_depth_planes (o: FrustumPlanes<T>) -> Self where T: Real {
                let two = T::one() + T::one();
                let FrustumPlanes { left, right, top, bottom, .. } = o;
                let mut m = Self::identity();
                m[(0, 0)] = two / (right - left);
                m[(1, 1)] = two / (top - bottom);
                m[(0, 3)] = - (right + left) / (right - left);
                m[(1, 3)] = - (top + bottom) / (top - bottom);
                m
            }
            /// Returns an orthographic projection matrix for left-handed spaces,
            /// for a depth clip space ranging from 0 to 1 (`GL_DEPTH_ZERO_TO_ONE`,
            /// hence the `_zo` suffix).
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, FrustumPlanes, Vec4};
            /// # fn main() {
            /// let m = Mat4::orthographic_lh_zo(FrustumPlanes {
            ///     left: -1_f32, right: 1., bottom: -1., top: 1.,
            ///     near: 0., far: 1.
            /// });
            /// let v = Vec4::new(0_f32, 0., 1., 1.); // "forward"
            /// assert_relative_eq!(m * v, Vec4::new(0., 0., 1., 1.)); // "far"
            /// # }
            /// ```
            pub fn orthographic_lh_zo (o: FrustumPlanes<T>) -> Self where T: Real {
                let FrustumPlanes { near, far, .. } = o;
                let mut m = Self::orthographic_without_depth_planes(o);
                m[(2, 2)] = T::one() / (far - near);
                m[(2, 3)] = - near / (far - near);
                m
            }
            /// Returns an orthographic projection matrix for left-handed spaces,
            /// for a depth clip space ranging from -1 to 1 (`GL_DEPTH_NEGATIVE_ONE_TO_ONE`,
            /// hence the `_no` suffix).
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, FrustumPlanes, Vec4};
            /// # fn main() {
            /// let m = Mat4::orthographic_lh_no(FrustumPlanes {
            ///     left: -1_f32, right: 1., bottom: -1., top: 1.,
            ///     near: 0., far: 1.
            /// });
            /// let v = Vec4::new(0_f32, 0., 1., 1.); // "forward"
            /// assert_relative_eq!(m * v, Vec4::new(0., 0., 1., 1.)); // "far"
            /// # }
            /// ```
            pub fn orthographic_lh_no (o: FrustumPlanes<T>) -> Self where T: Real {
                let two = T::one() + T::one();
                let FrustumPlanes { near, far, .. } = o;
                let mut m = Self::orthographic_without_depth_planes(o);
                m[(2, 2)] = two / (far - near);
                m[(2, 3)] = - (far + near) / (far - near);
                m
            }
            /// Returns an orthographic projection matrix for right-handed spaces,
            /// for a depth clip space ranging from 0 to 1 (`GL_DEPTH_ZERO_TO_ONE`,
            /// hence the `_zo` suffix).
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, FrustumPlanes, Vec4};
            /// # fn main() {
            /// let m = Mat4::orthographic_rh_zo(FrustumPlanes {
            ///     left: -1_f32, right: 1., bottom: -1., top: 1.,
            ///     near: 0., far: 1.
            /// });
            /// let v = Vec4::new(0_f32, 0., -1., 1.); // "forward"
            /// assert_relative_eq!(m * v, Vec4::new(0., 0., 1., 1.)); // "far"
            /// # }
            /// ```
            pub fn orthographic_rh_zo (o: FrustumPlanes<T>) -> Self where T: Real {
                let FrustumPlanes { near, far, .. } = o;
                let mut m = Self::orthographic_without_depth_planes(o);
                m[(2, 2)] = - T::one() / (far - near);
                m[(2, 3)] = - near / (far - near);
                m
            }
            /// Returns an orthographic projection matrix for right-handed spaces,
            /// for a depth clip space ranging from -1 to 1 (`GL_DEPTH_NEGATIVE_ONE_TO_ONE`,
            /// hence the `_no` suffix).
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, FrustumPlanes, Vec4};
            /// # fn main() {
            /// let m = Mat4::orthographic_rh_no(FrustumPlanes {
            ///     left: -1_f32, right: 1., bottom: -1., top: 1.,
            ///     near: 0., far: 1.
            /// });
            /// let v = Vec4::new(0_f32, 0., -1., 1.); // "forward"
            /// assert_relative_eq!(m * v, Vec4::new(0., 0., 1., 1.)); // "far"
            /// # }
            /// ```
            pub fn orthographic_rh_no (o: FrustumPlanes<T>) -> Self where T: Real {
                let two = T::one() + T::one();
                let FrustumPlanes { near, far, .. } = o;
                let mut m = Self::orthographic_without_depth_planes(o);
                m[(2, 2)] = - two / (far - near);
                m[(2, 3)] = - (far + near) / (far - near);
                m
            }

            /// Creates a perspective projection matrix from a frustum
            /// (left-handed, zero-to-one depth clip planes).
            pub fn frustum_lh_zo (o: FrustumPlanes<T>) -> Self where T: Real {
                let two = T::one() + T::one();
                let FrustumPlanes { left, right, top, bottom, near, far } = o;
                let mut m = Self::zero();
                m[(0, 0)] = (two * near) / (right - left);
                m[(1, 1)] = (two * near) / (top - bottom);
                m[(0, 2)] = (right + left) / (right - left);
                m[(1, 2)] = (top + bottom) / (top - bottom);
                m[(2, 2)] = far / (far - near);
                m[(3, 2)] = T::one();
                m[(2, 3)] = -(far * near) / (far - near);
                m
            }
            /// Creates a perspective projection matrix from a frustum
            /// (left-handed, negative-one-to-one depth clip planes).
            pub fn frustum_lh_no (o: FrustumPlanes<T>) -> Self where T: Real {
                let two = T::one() + T::one();
                let FrustumPlanes { near, far, .. } = o;
                let mut m = Self::frustum_lh_zo(o);
                m[(2, 2)] = (far + near) / (far - near);
                m[(2, 3)] = -(two * far * near) / (far - near);
                m
            }
            /// Creates a perspective projection matrix from a frustum
            /// (right-handed, zero-to-one depth clip planes).
            pub fn frustum_rh_zo (o: FrustumPlanes<T>) -> Self where T: Real {
                let mut m = Self::frustum_lh_zo(o);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }
            /// Creates a perspective projection matrix from a frustum
            /// (right-handed, negative-one-to-one depth clip planes).
            pub fn frustum_rh_no (o: FrustumPlanes<T>) -> Self where T: Real {
                let mut m = Self::frustum_lh_no(o);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }

            /// Creates a perspective projection matrix for right-handed spaces, with zero-to-one depth clip planes.
            pub fn perspective_rh_zo (fov_y_radians: T, aspect_ratio: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                // Assertions from cgmath
                debug_assert!(fov_y_radians > T::zero(), "The vertical field of view cannot be below zero, found: {:?}", fov_y_radians);
                debug_assert!(fov_y_radians < (T::PI()+T::PI()), "The vertical field of view cannot be greater than a half turn, found: {:?} radians", fov_y_radians);
                debug_assert!(aspect_ratio > T::zero(), "The aspect ratio cannot be below zero, found: {:?}", aspect_ratio);
                debug_assert!(near > T::zero(), "The near plane distance cannot be below zero, found: {:?}", near);
                debug_assert!(far  > T::zero(), "The far plane distance cannot be below zero, found: {:?}", far);
                debug_assert!(far  > near, "The far plane cannot be closer than the near plane, found: far: {:?}, near: {:?}", far, near);
                let two = T::one() + T::one();
                let tan_half_fovy = (fov_y_radians / two).tan();
                let m00 = T::one() / (aspect_ratio * tan_half_fovy);
                let m11 = T::one() / tan_half_fovy;
                let m22 = far / (near - far);
                let m23 = -(far*near) / (far-near);
                let m32 = -T::one();
                Self::new(
                    m00, T::zero(), T::zero(), T::zero(),
                    T::zero(), m11, T::zero(), T::zero(),
                    T::zero(), T::zero(), m22, m23,
                    T::zero(), T::zero(), m32, T::zero()
                )
            }
            /// Creates a perspective projection matrix for left-handed spaces, with zero-to-one depth clip planes.
            pub fn perspective_lh_zo (fov_y_radians: T, aspect_ratio: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                let mut m = Self::perspective_rh_zo(fov_y_radians, aspect_ratio, near, far);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }

            /// Creates a perspective projection matrix for right-handed spaces, with negative-one-to-one depth clip planes.
            pub fn perspective_rh_no (fov_y_radians: T, aspect_ratio: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                // Assertions from cgmath
                debug_assert!(fov_y_radians > T::zero(), "The vertical field of view cannot be below zero, found: {:?}", fov_y_radians);
                debug_assert!(fov_y_radians < (T::PI()+T::PI()), "The vertical field of view cannot be greater than a half turn, found: {:?} radians", fov_y_radians);
                debug_assert!(aspect_ratio > T::zero(), "The aspect ratio cannot be below zero, found: {:?}", aspect_ratio);
                debug_assert!(near > T::zero(), "The near plane distance cannot be below zero, found: {:?}", near);
                debug_assert!(far  > T::zero(), "The far plane distance cannot be below zero, found: {:?}", far);
                debug_assert!(far  > near, "The far plane cannot be closer than the near plane, found: far: {:?}, near: {:?}", far, near);
                let two = T::one() + T::one();
                let tan_half_fovy = (fov_y_radians / two).tan();
                let m00 = T::one() / (aspect_ratio * tan_half_fovy);
                let m11 = T::one() / tan_half_fovy;
                let m22 = -(far + near) / (far - near);
                let m23 = -(two*far*near) / (far-near);
                let m32 = -T::one();
                Self::new(
                    m00, T::zero(), T::zero(), T::zero(),
                    T::zero(), m11, T::zero(), T::zero(),
                    T::zero(), T::zero(), m22, m23,
                    T::zero(), T::zero(), m32, T::zero()
                )
            }
            /// Creates a perspective projection matrix for left-handed spaces, with negative-one-to-one depth clip planes.
            pub fn perspective_lh_no (fov_y_radians: T, aspect_ratio: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                let mut m = Self::perspective_rh_no(fov_y_radians, aspect_ratio, near, far);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }

            /// Creates a perspective projection matrix for right-handed spaces, with zero-to-one depth clip planes.
            ///
            /// # Panics
            /// `width`, `height` and `fov_y_radians` must all be strictly greater than zero.
            pub fn perspective_fov_rh_zo (fov_y_radians: T, width: T, height: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                debug_assert!(width > T::zero(), "viewport width cannot be below zero, found: {:?}", width);
                debug_assert!(height > T::zero(), "viewport height cannot be below zero, found: {:?}", height);
                // Assertions from cgmath
                debug_assert!(fov_y_radians > T::zero(), "The vertical field of view cannot be below zero, found: {:?}", fov_y_radians);
                debug_assert!(fov_y_radians < (T::PI()+T::PI()), "The vertical field of view cannot be greater than a half turn, found: {:?} radians", fov_y_radians);
                debug_assert!(near > T::zero(), "The near plane distance cannot be below zero, found: {:?}", near);
                debug_assert!(far  > T::zero(), "The far plane distance cannot be below zero, found: {:?}", far);
                debug_assert!(far  > near, "The far plane cannot be closer than the near plane, found: far: {:?}, near: {:?}", far, near);

                let two = T::one() + T::one();
                let rad = fov_y_radians;
                let h = (rad/two).cos() / (rad/two).sin();
                let w = h * height / width;

                let m00 = w;
                let m11 = h;
                let m22 = far / (near - far);
                let m23 = -(far * near) / (far - near);
                let m32 = -T::one();
                Self::new(
                    m00, T::zero(), T::zero(), T::zero(),
                    T::zero(), m11, T::zero(), T::zero(),
                    T::zero(), T::zero(), m22, m23,
                    T::zero(), T::zero(), m32, T::zero()
                )
            }

            /// Creates a perspective projection matrix for left-handed spaces, with zero-to-one depth clip planes.
            ///
            /// # Panics
            /// `width`, `height` and `fov_y_radians` must all be strictly greater than zero.
            pub fn perspective_fov_lh_zo (fov_y_radians: T, width: T, height: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                let mut m = Self::perspective_fov_rh_zo(fov_y_radians, width, height, near, far);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }

            /// Creates a perspective projection matrix for right-handed spaces, with negative-one-to-one depth clip planes.
            ///
            /// # Panics
            /// `width`, `height` and `fov_y_radians` must all be strictly greater than zero.
            pub fn perspective_fov_rh_no (fov_y_radians: T, width: T, height: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                debug_assert!(width > T::zero(), "viewport width cannot be below zero, found: {:?}", width);
                debug_assert!(height > T::zero(), "viewport height cannot be below zero, found: {:?}", height);
                // Assertions from cgmath
                debug_assert!(fov_y_radians > T::zero(), "The vertical field of view cannot be below zero, found: {:?}", fov_y_radians);
                debug_assert!(fov_y_radians < (T::PI()+T::PI()), "The vertical field of view cannot be greater than a half turn, found: {:?} radians", fov_y_radians);
                debug_assert!(near > T::zero(), "The near plane distance cannot be below zero, found: {:?}", near);
                debug_assert!(far  > T::zero(), "The far plane distance cannot be below zero, found: {:?}", far);
                debug_assert!(far  > near, "The far plane cannot be closer than the near plane, found: far: {:?}, near: {:?}", far, near);

                let two = T::one() + T::one();
                let rad = fov_y_radians;
                let h = (rad/two).cos() / (rad/two).sin();
                let w = h * height / width;

                let m00 = w;
                let m11 = h;
                let m22 = -(far + near) / (far - near);
                let m23 = -(two * far * near) / (far - near);
                let m32 = -T::one();
                Self::new(
                    m00, T::zero(), T::zero(), T::zero(),
                    T::zero(), m11, T::zero(), T::zero(),
                    T::zero(), T::zero(), m22, m23,
                    T::zero(), T::zero(), m32, T::zero()
                )
            }
            /// Creates a perspective projection matrix for left-handed spaces, with negative-one-to-one depth clip planes.
            ///
            /// # Panics
            /// `width`, `height` and `fov_y_radians` must all be strictly greater than zero.
            pub fn perspective_fov_lh_no (fov_y_radians: T, width: T, height: T, near: T, far: T) -> Self
                where T: Real + FloatConst + Debug
            {
                let mut m = Self::perspective_fov_rh_no(fov_y_radians, width, height, near, far);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }


            /// Creates an infinite perspective projection matrix for right-handed spaces.
            ///
            /// [Link to PDF](http://www.terathon.com/gdc07_lengyel.pdf)
            // From GLM
            pub fn tweaked_infinite_perspective_rh (fov_y_radians: T, aspect_ratio: T, near: T, epsilon: T) -> Self
                where T: Real + FloatConst + Debug
            {
                // Assertions from cgmath
                debug_assert!(fov_y_radians > T::zero(), "The vertical field of view cannot be below zero, found: {:?}", fov_y_radians);
                debug_assert!(fov_y_radians < (T::PI()+T::PI()), "The vertical field of view cannot be greater than a half turn, found: {:?} radians", fov_y_radians);
                debug_assert!(aspect_ratio > T::zero(), "The aspect ratio cannot be below zero, found: {:?}", aspect_ratio);
                debug_assert!(near > T::zero(), "The near plane distance cannot be below zero, found: {:?}", near);

                let two = T::one() + T::one();
                let range = (fov_y_radians / two).tan() * near;
                let left = -range * aspect_ratio;
                let right = range * aspect_ratio;
                let bottom = -range;
                let top = range;

                let m00 = (two * near) / (right - left);
                let m11 = (two * near) / (top - bottom);
                let m22 = epsilon - T::one();
                let m23 = (epsilon - two) * near;
                let m32 = -T::one();
                Self::new(
                    m00, T::zero(), T::zero(), T::zero(),
                    T::zero(), m11, T::zero(), T::zero(),
                    T::zero(), T::zero(), m22, m23,
                    T::zero(), T::zero(), m32, T::zero()
                )
            }

            /// Creates an infinite perspective projection matrix for left-handed spaces.
            pub fn tweaked_infinite_perspective_lh (fov_y_radians: T, aspect_ratio: T, near: T, epsilon: T) -> Self
                where T: Real + FloatConst + Debug
            {
                let mut m = Self::tweaked_infinite_perspective_rh(fov_y_radians, aspect_ratio, near, epsilon);
                m[(2, 2)] = -m[(2, 2)];
                m[(3, 2)] = -m[(3, 2)];
                m
            }

            /// Creates an infinite perspective projection matrix for right-handed spaces.
            pub fn infinite_perspective_rh (fov_y_radians: T, aspect_ratio: T, near: T) -> Self
                where T: Real + FloatConst + Debug
            {
                Self::tweaked_infinite_perspective_rh(fov_y_radians, aspect_ratio, near, T::zero())
            }

            /// Creates an infinite perspective projection matrix for left-handed spaces.
            pub fn infinite_perspective_lh (fov_y_radians: T, aspect_ratio: T, near: T) -> Self
                where T: Real + FloatConst + Debug
            {
                Self::tweaked_infinite_perspective_lh(fov_y_radians, aspect_ratio, near, T::zero())
            }

            //
            // PICKING
            //

            /// GLM's pickMatrix. Creates a projection matrix that can be
            /// used to restrict drawing to a small region of the viewport.
            ///
            /// # Panics
            /// `delta`'s `x` and `y` are required to be strictly greater than zero.
            pub fn picking_region<V2: Into<Vec2<T>>>(center: V2, delta: V2, viewport: Rect<T, T>) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                let (center, delta) = (center.into(), delta.into());
                assert!(delta.x > T::zero());
                assert!(delta.y > T::zero());
                let two = T::one() + T::one();

                let tr = Vec3::new(
                    (viewport.w - two * (center.x - viewport.x)) / delta.x,
                    (viewport.h - two * (center.y - viewport.y)) / delta.y,
                    T::zero()
                );
                let sc = Vec3::new(
                    viewport.w / delta.x,
                    viewport.h / delta.y,
                    T::one()
                );
                Self::scaling_3d(sc) * Self::translation_3d(tr)
            }

            /// Projects a world-space coordinate into screen space,
            /// for a depth clip space ranging from -1 to 1 (`GL_DEPTH_NEGATIVE_ONE_TO_ONE`,
            /// hence the `_no` suffix).
            pub fn world_to_viewport_no<V3>(obj: V3, modelview: Self, proj: Self, viewport: Rect<T, T>) -> Vec3<T>
                where T: Real + MulAdd<T,T,Output=T>,
                      V3: Into<Vec3<T>>
            {
                // GLM's projectNO()
                let mut tmp = Vec4::from_point(obj.into());
                tmp = modelview * tmp;
                tmp = proj * tmp;

                let two = T::one() + T::one();
                let half_one = T::one() / two;

                tmp = tmp / tmp.w; // Real doesn't imply DivAssign
                tmp = tmp / two + half_one;
                tmp.x = tmp.x * viewport.w + viewport.x;
                tmp.y = tmp.y * viewport.h + viewport.y;

                tmp.into()
            }

            /// Projects a world-space coordinate into screen space,
            /// for a depth clip space ranging from 0 to 1 (`GL_DEPTH_ZERO_TO_ONE`,
            /// hence the `_zo` suffix).
            pub fn world_to_viewport_zo<V3>(obj: V3, modelview: Self, proj: Self, viewport: Rect<T, T>) -> Vec3<T>
                where T: Real + MulAdd<T,T,Output=T>,
                      V3: Into<Vec3<T>>
            {
                // GLM's projectZO()
                let mut tmp = Vec4::from_point(obj.into());
                tmp = modelview * tmp;
                tmp = proj * tmp;

                let two = T::one() + T::one();
                let half_one = T::one() / two;

                tmp = tmp / tmp.w; // Real doesn't imply DivAssign
                tmp.x = tmp.x / two + half_one;
                tmp.y = tmp.y / two + half_one;
                tmp.x = tmp.x * viewport.w + viewport.x;
                tmp.y = tmp.y * viewport.h + viewport.y;

                tmp.into()
            }

            /// Projects a screen-space coordinate into world space,
            /// for a depth clip space ranging from 0 to 1 (`GL_DEPTH_ZERO_TO_ONE`,
            /// hence the `_zo` suffix).
            pub fn viewport_to_world_zo<V3>(ray: V3, modelview: Self, proj: Self, viewport: Rect<T, T>) -> Vec3<T>
                where T: Real + MulAdd<T,T,Output=T>,
                      V3: Into<Vec3<T>>
            {
                let inverse = (proj * modelview).inverted();
                let two = T::one() + T::one();

                let mut tmp = Vec4::from_point(ray.into());
                tmp.x = (tmp.x - viewport.x) / viewport.w;
                tmp.y = (tmp.y - viewport.y) / viewport.h;
                tmp.x = tmp.x * two - T::one();
                tmp.y = tmp.y * two - T::one();

                let mut obj = inverse * tmp;
                obj = obj / obj.w; // Real doesn't imply DivAssign

                obj.into()
            }
            /// Projects a screen-space coordinate into world space,
            /// for a depth clip space ranging from -1 to 1 (`GL_DEPTH_NEGATIVE_ONE_TO_ONE`,
            /// hence the `_no` suffix).
            pub fn viewport_to_world_no<V3>(ray: V3, modelview: Self, proj: Self, viewport: Rect<T, T>) -> Vec3<T>
                where T: Real + MulAdd<T,T,Output=T>,
                      V3: Into<Vec3<T>>
            {
                let inverse = (proj * modelview).inverted();
                let two = T::one() + T::one();

                let mut tmp = Vec4::from_point(ray.into());
                tmp.x = (tmp.x - viewport.x) / viewport.w;
                tmp.y = (tmp.y - viewport.y) / viewport.h;
                tmp = tmp * two - T::one();

                let mut obj = inverse * tmp;
                obj = obj / obj.w; // Real doesn't imply DivAssign

                obj.into()
            }
        }
        use super::mat3::Mat3;
        impl<T> From<Mat3<T>> for Mat4<T> where T: Zero + One {
            fn from(m: Mat3<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec4::new(
                        m.x.into(),
                        m.y.into(),
                        m.z.into(),
                        Vec4::new(T::zero(), T::zero(), T::zero(), T::one())
                    )
                }
            }
        }
        use super::mat2::Mat2;
        impl<T> From<Mat2<T>> for Mat4<T> where T: Zero + One {
            fn from(m: Mat2<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec4::new(
                        m.x.into(),
                        m.y.into(),
                        Vec4::new(T::zero(), T::zero(), T::one(), T::zero()),
                        Vec4::new(T::zero(), T::zero(), T::zero(), T::one())
                    )
                }
            }
        }

        /// A `Mat4` can be obtained from a `Transform`, by rotating, then scaling, then
        /// translating.
        impl<T> From<Transform<T,T,T>> for Mat4<T>
            where T: Real + MulAdd<T,T,Output=T>
        {
            fn from(xform: Transform<T,T,T>) -> Self {
                let Transform { position, orientation, scale } = xform;
                Mat4::from(orientation).scaled_3d(scale).translated_3d(position)
            }
        }

        /// Rotation matrices can be obtained from quaternions.
        /// **This implementation only works properly if the quaternion is normalized**.
        ///
        /// ```
        /// # extern crate vek;
        /// # #[macro_use] extern crate approx;
        /// # use vek::{Quaternion, Mat4, Vec4};
        /// use std::f32::consts::PI;
        ///
        /// # fn main() {
        /// let angles = 32;
        /// for i in 0..angles {
        ///     let theta = PI * 2. * (i as f32) / (angles as f32);
        ///
        ///     assert_relative_eq!(Mat4::rotation_x(theta), Mat4::from(Quaternion::rotation_x(theta)), epsilon = 0.000001);
        ///     assert_relative_eq!(Mat4::rotation_y(theta), Mat4::from(Quaternion::rotation_y(theta)), epsilon = 0.000001);
        ///     assert_relative_eq!(Mat4::rotation_z(theta), Mat4::from(Quaternion::rotation_z(theta)), epsilon = 0.000001);
        ///
        ///     assert_relative_eq!(Mat4::rotation_x(theta), Mat4::rotation_3d(theta, Vec4::unit_x()));
        ///     assert_relative_eq!(Mat4::rotation_y(theta), Mat4::rotation_3d(theta, Vec4::unit_y()));
        ///     assert_relative_eq!(Mat4::rotation_z(theta), Mat4::rotation_3d(theta, Vec4::unit_z()));
        ///
        ///     // See what rotating unit vectors do for most angles between 0 and 2*PI.
        ///     // It's helpful to picture this as a right-handed coordinate system.
        ///
        ///     let v = Vec4::unit_y();
        ///     let m = Mat4::rotation_x(theta);
        ///     assert_relative_eq!(m * v, Vec4::new(0., theta.cos(), theta.sin(), 0.));
        ///
        ///     let v = Vec4::unit_z();
        ///     let m = Mat4::rotation_y(theta);
        ///     assert_relative_eq!(m * v, Vec4::new(theta.sin(), 0., theta.cos(), 0.));
        ///
        ///     let v = Vec4::unit_x();
        ///     let m = Mat4::rotation_z(theta);
        ///     assert_relative_eq!(m * v, Vec4::new(theta.cos(), theta.sin(), 0., 0.));
        /// }
        /// # }
        /// ```
        // NOTE: Logically, this conversion should be implemented for Mat3,
        // and Mat4 would do it by converting itself from a Mat3.
        // Here, we have the other way round, and I'm fine with this, because
        // at best it's better, SIMD-wise, and at worst we don't care that much, seriously.
        impl<T> From<Quaternion<T>> for Mat4<T>
            where T: Copy + Zero + One + Mul<Output=T> + Add<Output=T> + Sub<Output=T>
        {
            fn from(q: Quaternion<T>) -> Self {
                // From both GEA and Matrix FAQ
                let Quaternion { x, y, z, w } = q;
                let one = T::one();
                let two = one+one;
                let (x2, y2, z2) = (x*x, y*y, z*z);
                let m00 = one - two*y2 - two*z2;
                let m11 = one - two*x2 - two*z2;
                let m22 = one - two*x2 - two*y2;
                let m01 = two*x*y + two*z*w;
                let m10 = two*x*y - two*z*w;
                let m02 = two*x*z - two*y*w;
                let m20 = two*x*z + two*y*w;
                let m12 = two*y*z + two*x*w;
                let m21 = two*y*z - two*x*w;
                // NOTE: transpose, because otherwise the rotation goes the opposite way.
                // See tests.
                Self::new(
                    m00, m10, m20, T::zero(),
                    m01, m11, m21, T::zero(),
                    m02, m12, m22, T::zero(),
                    T::zero(), T::zero(), T::zero(), T::one()
                )
            }
        }

        /* NOTE: Commented until I find an implementation that actually works
        /// A quaternion may be obtained from a rotation matrix.
        ///
        /// ```
        /// # extern crate vek;
        /// # #[macro_use] extern crate approx;
        /// # use vek::{Mat4, Quaternion, Vec3};
        /// # fn main() {
        /// let (angle, axis) = (3_f32, Vec3::new(1_f32, 3., 7.));
        /// let a = Quaternion::rotation_3d(angle, axis);
        /// let b = Quaternion::from(Mat4::rotation_3d(angle, axis));
        /// assert_relative_eq!(a, b);
        /// # }
        /// ```
        impl<T> From<Mat4<T>> for Quaternion<T>
            where T: Real + Zero + One + Mul<Output=T> + Add<Output=T> + Sub<Output=T>
        {
            fn from(m: Mat4<T>) -> Self {
                // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/
                // Using the most branchy one, because if you're willing to convert a matrix to
                // quaternion in the first place, surely you don't mind this extra cost.
                let m = Rows4::from(m);
                let Rows4 {
                    rows: CVec4 {
                        x: Vec4 { x: m00, y: m01, z: m02, w: _ },
                        y: Vec4 { x: m10, y: m11, z: m12, w: _ },
                        z: Vec4 { x: m20, y: m21, z: m22, w: _ },
                        w: Vec4 { x:   _, y:   _, z:   _, w: _ },
                    }
                } = m;
                let tr = m00 + m11 + m22;

                let one = T::one();
                let two = one + one;
                let four = two + two;
                if tr > T::zero() {
                    let s = (tr+one).sqrt() * two; // S=4*qw
                    Self {
                        w: s / four,
                        x: (m21 - m12) / s,
                        y: (m02 - m20) / s,
                        z: (m10 - m01) / s,
                    }
                } else if (m00 > m11) && (m00 > m22) {
                    let s = (one + m00 - m11 - m22).sqrt() * two; // S=4*qx
                    Self {
                        w: (m21 - m12) / s,
                        x: s / four,
                        y: (m01 + m10) / s,
                        z: (m02 + m20) / s,
                    }
                } else if m11 > m22 {
                    let s = (one + m11 - m00 - m22).sqrt() * two; // S=4*qy
                    Self {
                        w: (m02 - m20) / s,
                        x: (m01 + m10) / s,
                        y: s / four,
                        z: (m12 + m21) / s,
                    }
                } else {
                    let s = (one + m22 - m00 - m11).sqrt() * two; // S=4*qz
                    Self {
                        w: (m10 - m01) / s,
                        x: (m02 + m20) / s,
                        y: (m12 + m21) / s,
                        z: s / four,
                    }
                }
            }
        } */
    };
}

#[allow(unused_macros)]
macro_rules! mat_impl_mat3 {
    (rows) => {

        mat_impl_mat3!{common rows}

        impl<T> Mat3<T> {
            /// Creates a new 3x3 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T, m02: T,
                m10: T, m11: T, m12: T,
                m20: T, m21: T, m22: T,
            ) -> Self {
                Self {
                    rows: CVec3::new(
                        Vec3::new(m00, m01, m02),
                        Vec3::new(m10, m11, m12),
                        Vec3::new(m20, m21, m22)
                    )
                }
            }
        }
    };
    (cols) => {

        mat_impl_mat3!{common cols}

        impl<T> Mat3<T> {
            /// Creates a new 3x3 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T, m02: T,
                m10: T, m11: T, m12: T,
                m20: T, m21: T, m22: T
            ) -> Self {
                Self {
                    cols: CVec3::new(
                        Vec3::new(m00, m10, m20),
                        Vec3::new(m01, m11, m21),
                        Vec3::new(m02, m12, m22)
                    )
                }
            }
        }
    };
    (common $lines:ident) => {
        impl<T> Mat3<T> {
            /// Returns an element-wise-converted copy of this matrix, using the given conversion
            /// closure.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<f32>::new(
            ///     0.25, 1.25, 5.56, 8.66,
            ///     8.53, 2.92, 3.86, 9.36,
            ///     1.02, 0.28, 5.52, 6.06,
            ///     6.20, 7.01, 4.90, 5.26
            /// );
            /// let m = m.map(|x| x.round() as i32);
            /// assert_eq!(m, Mat4::new(
            ///     0, 1, 6, 9,
            ///     9, 3, 4, 9,
            ///     1, 0, 6, 6,
            ///     6, 7, 5, 5
            /// ));
            /// ```
            pub fn map<D,F>(self, mut f: F) -> Mat3<D> where F: FnMut(T) -> D {
                let m = self.$lines;
                Mat3 {
                    $lines: CVec3::new(
                        Vec3::new(f(m.x.x), f(m.x.y), f(m.x.z)),
                        Vec3::new(f(m.y.x), f(m.y.y), f(m.y.z)),
                        Vec3::new(f(m.z.x), f(m.z.y), f(m.z.z)),
                    )
                }
            }

            /// Returns a memberwise-converted copy of this matrix, using `AsPrimitive`.
            ///
            /// # Examples
            ///
            /// ```
            /// # use vek::vec::Vec4;
            /// let v = Vec4::new(0_f32, 1., 2., 3.);
            /// let i: Vec4<i32> = v.as_();
            /// assert_eq!(i, Vec4::new(0, 1, 2, 3));
            /// ```
            ///
            /// # Safety
            ///
            /// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe.
            /// In particular, it was undefined behavior if
            /// a truncated floating point value could not fit in the target integer
            /// type ([#10184](https://github.com/rust-lang/rust/issues/10184));
            ///
            /// ```ignore
            /// # use num_traits::AsPrimitive;
            /// let x: u8 = (1.04E+17).as_(); // UB
            /// ```
            pub fn as_<D>(self) -> Mat3<D> where T: AsPrimitive<D>, D: 'static + Copy {
                let m = self.$lines;
                Mat3 {
                    $lines: CVec3::new(
                        Vec3::new(m.x.x.as_(), m.x.y.as_(), m.x.z.as_()),
                        Vec3::new(m.y.x.as_(), m.y.y.as_(), m.y.z.as_()),
                        Vec3::new(m.z.x.as_(), m.z.y.as_(), m.z.z.as_()),
                    )
                }
            }

            /// Applies the function f to each element of two matrices, pairwise, and returns the result.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let a = Mat4::<f32>::new(
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99
            /// );
            /// let b = Mat4::<i32>::new(
            ///     0, 1, 0, 0,
            ///     1, 0, 0, 0,
            ///     0, 0, 1, 0,
            ///     0, 0, 0, 1
            /// );
            /// let m = a.map2(b, |a, b| a.round() as i32 + b);
            /// assert_eq!(m, Mat4::new(
            ///     0, 2, 3, 3,
            ///     1, 1, 3, 3,
            ///     0, 1, 4, 3,
            ///     0, 1, 3, 4
            /// ));
            /// ```
            pub fn map2<D,F,S>(self, other: Mat3<S>, mut f: F) -> Mat3<D> where F: FnMut(T, S) -> D {
                let m = self.$lines;
                let o = other.$lines;
                Mat3 {
                    $lines: CVec3::new(
                        Vec3::new(f(m.x.x, o.x.x), f(m.x.y, o.x.y), f(m.x.z, o.x.z)),
                        Vec3::new(f(m.y.x, o.y.x), f(m.y.y, o.y.y), f(m.y.z, o.y.z)),
                        Vec3::new(f(m.z.x, o.z.x), f(m.z.y, o.z.y), f(m.z.z, o.z.z))
                    )
                }
            }

            /// The matrix's transpose.
            ///
            /// For orthogonal matrices, the transpose is the same as the inverse.
            /// All pure rotation matrices are orthogonal, and therefore can be inverted
            /// faster by simply computing their transpose.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::Mat3;
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let m = Mat3::new(
            ///     0, 1, 2,
            ///     4, 5, 6,
            ///     8, 9, 0
            /// );
            /// let t = Mat3::new(
            ///     0, 4, 8,
            ///     1, 5, 9,
            ///     2, 6, 0
            /// );
            /// assert_eq!(m.transposed(), t);
            /// assert_eq!(m, m.transposed().transposed());
            ///
            /// let m = Mat3::rotation_x(PI/7.);
            /// assert_relative_eq!(m * m.transposed(), Mat3::identity());
            /// assert_relative_eq!(m.transposed() * m, Mat3::identity());
            /// # }
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transposed(self) -> Self {
                let s = self.$lines;
                Self {
                    $lines: CVec3::new(
                        Vec3::new(s.x.x, s.y.x, s.z.x),
                        Vec3::new(s.x.y, s.y.y, s.z.y),
                        Vec3::new(s.x.z, s.y.z, s.z.z)
                    )
                }
            }
            /// Transpose this matrix.
            ///
            /// ```
            /// # use vek::Mat3;
            ///
            /// let mut m = Mat3::new(
            ///     0, 1, 2,
            ///     4, 5, 6,
            ///     8, 9, 0
            /// );
            /// let t = Mat3::new(
            ///     0, 4, 8,
            ///     1, 5, 9,
            ///     2, 6, 0
            /// );
            /// m.transpose();
            /// assert_eq!(m, t);
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transpose(&mut self) {
                mem::swap(&mut self.$lines.x.y, &mut self.$lines.y.x);
                mem::swap(&mut self.$lines.x.z, &mut self.$lines.z.x);
                mem::swap(&mut self.$lines.y.z, &mut self.$lines.z.y);
            }

            /// Get this matrix's determinant.
            ///
            /// A matrix is invertible if its determinant is non-zero.
            pub fn determinant(self) -> T where T: Copy + Mul<T,Output=T> + Sub<T,Output=T> + Add<T, Output=T> {
                // https://www.mathsisfun.com/algebra/matrix-determinant.html
                use super::row_major::Mat3 as Rows3;
                let CVec3 {
                    x: Vec3 { x: a, y: b, z: c },
                    y: Vec3 { x: d, y: e, z: f },
                    z: Vec3 { x: g, y: h, z: i },
                } = Rows3::from(self).rows;
                a*(e*i - f*h) - b*(d*i - f*g) + c*(d*h - e*g)
            }


            //
            // MULTIPLY BY
            //

            /// Shortcut for `self * Vec3::from_point_2d(rhs)`.
            pub fn mul_point_2d<V: Into<Vec2<T>> + From<Vec3<T>>>(self, rhs: V) -> V
                where T: Real + MulAdd<T,T,Output=T>
            {
                V::from(self * Vec3::from_point_2d(rhs))
            }
            /// Shortcut for `self * Vec3::from_direction_2d(rhs)`.
            pub fn mul_direction_2d<V: Into<Vec2<T>> + From<Vec3<T>>>(self, rhs: V) -> V
                where T: Real + MulAdd<T,T,Output=T>
            {
                V::from(self * Vec3::from_direction_2d(rhs))
            }


            /// Translates this matrix in 2D.
            pub fn translate_2d<V: Into<Vec2<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.translated_2d(v);
            }
            /// Returns this matrix translated in 2D.
            pub fn translated_2d<V: Into<Vec2<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::translation_2d(v) * self
            }
            /// Creates a 2D translation matrix.
            pub fn translation_2d<V: Into<Vec2<T>>>(v: V) -> Self where T: Zero + One {
                let v = v.into();
                Self::new(
                    T::one() , T::zero(), v.x,
                    T::zero(), T::one() , v.y,
                    T::zero(), T::zero(), T::one()
                )
            }
            /// Scales this matrix in 3D.
            pub fn scale_3d<V: Into<Vec3<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.scaled_3d(v);
            }
            /// Returns this matrix scaled in 3D.
            pub fn scaled_3d<V: Into<Vec3<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::scaling_3d(v) * self
            }
            /// Creates a 3D scaling matrix.
            pub fn scaling_3d<V: Into<Vec3<T>>>(v: V) -> Self where T: Zero {
                let Vec3 { x, y, z } = v.into();
                Self::new(
                    x, T::zero(), T::zero(),
                    T::zero(), y, T::zero(),
                    T::zero(), T::zero(), z
                )
            }
            /// Rotates this matrix around the X axis.
            pub fn rotate_x(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_x(angle_radians);
            }
            /// Returns this matrix rotated around the X axis.
            pub fn rotated_x(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_x(angle_radians) * self
            }
            /// Creates a matrix that rotates around the X axis.
            pub fn rotation_x(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    T::one(), T::zero(), T::zero(),
                    T::zero(), c, -s,
                    T::zero(), s, c
                )
            }
            /// Rotates this matrix around the Y axis.
            pub fn rotate_y(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_y(angle_radians);
            }
            /// Returns this matrix rotated around the Y axis.
            pub fn rotated_y(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_y(angle_radians) * self
            }
            /// Creates a matrix that rotates around the Y axis.
            pub fn rotation_y(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    c, T::zero(), s,
                    T::zero(), T::one(), T::zero(),
                    -s, T::zero(), c
                )
            }
            /// Rotates this matrix around the Z axis.
            pub fn rotate_z(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_z(angle_radians);
            }
            /// Returns this matrix rotated around the Z axis.
            pub fn rotated_z(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_z(angle_radians) * self
            }
            /// Creates a matrix that rotates around the Z axis.
            pub fn rotation_z(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    c, -s, T::zero(),
                    s,  c, T::zero(),
                    T::zero(), T::zero(), T::one()
                )
            }

            /// Rotates this matrix around a 3D axis.
            /// The axis is not required to be normalized.
            pub fn rotate_3d<V: Into<Vec3<T>>>(&mut self, angle_radians: T, axis: V)
                where T: Real + MulAdd<T,T,Output=T> + Add<T, Output=T>
            {
                *self = self.rotated_3d(angle_radians, axis);
            }
            /// Returns this matrix rotated around a 3D axis.
            /// The axis is not required to be normalized.
            pub fn rotated_3d<V: Into<Vec3<T>>>(self, angle_radians: T, axis: V) -> Self
                where T: Real + MulAdd<T,T,Output=T> + Add<T, Output=T>
            {
                Self::rotation_3d(angle_radians, axis) * self
            }
            /// Creates a matrix that rotates around a 3D axis.
            /// The axis is not required to be normalized.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Mat4, Mat3, Vec3, Quaternion};
            /// use std::f32::consts::PI;
            ///
            /// # fn main() {
            /// let angles = 32;
            /// for i in 0..angles {
            ///     let theta = PI * 2. * (i as f32) / (angles as f32);
            ///
            ///     assert_relative_eq!(Mat3::rotation_x(theta), Mat3::from(Quaternion::rotation_x(theta)), epsilon = 0.000001);
            ///     assert_relative_eq!(Mat3::rotation_y(theta), Mat3::from(Quaternion::rotation_y(theta)), epsilon = 0.000001);
            ///     assert_relative_eq!(Mat3::rotation_z(theta), Mat3::from(Quaternion::rotation_z(theta)), epsilon = 0.000001);
            ///
            ///     assert_relative_eq!(Mat3::rotation_x(theta), Mat3::rotation_3d(theta, Vec3::unit_x()));
            ///     assert_relative_eq!(Mat3::rotation_y(theta), Mat3::rotation_3d(theta, Vec3::unit_y()));
            ///     assert_relative_eq!(Mat3::rotation_z(theta), Mat3::rotation_3d(theta, Vec3::unit_z()));
            ///
            ///     assert_relative_eq!(Mat3::rotation_x(theta), Mat3::from(Mat4::rotation_3d(theta, Vec3::unit_x())));
            ///     assert_relative_eq!(Mat3::rotation_y(theta), Mat3::from(Mat4::rotation_3d(theta, Vec3::unit_y())));
            ///     assert_relative_eq!(Mat3::rotation_z(theta), Mat3::from(Mat4::rotation_3d(theta, Vec3::unit_z())));
            ///
            ///     assert_relative_eq!(Mat4::rotation_x(theta), Mat4::from(Mat3::rotation_3d(theta, Vec3::unit_x())));
            ///     assert_relative_eq!(Mat4::rotation_y(theta), Mat4::from(Mat3::rotation_3d(theta, Vec3::unit_y())));
            ///     assert_relative_eq!(Mat4::rotation_z(theta), Mat4::from(Mat3::rotation_3d(theta, Vec3::unit_z())));
            ///
            ///     // See what rotating unit vectors do for most angles between 0 and 2*PI.
            ///     // It's helpful to picture this as a right-handed coordinate system.
            ///
            ///     let v = Vec3::unit_y();
            ///     let m = Mat3::rotation_x(theta);
            ///     assert_relative_eq!(m * v, Vec3::new(0., theta.cos(), theta.sin()));
            ///
            ///     let v = Vec3::unit_z();
            ///     let m = Mat3::rotation_y(theta);
            ///     assert_relative_eq!(m * v, Vec3::new(theta.sin(), 0., theta.cos()));
            ///
            ///     let v = Vec3::unit_x();
            ///     let m = Mat3::rotation_z(theta);
            ///     assert_relative_eq!(m * v, Vec3::new(theta.cos(), theta.sin(), 0.));
            /// }
            /// # }
            /// ```
            pub fn rotation_3d<V: Into<Vec3<T>>>(angle_radians: T, axis: V) -> Self where T: Real + Add<T, Output=T> {
                let Vec3 { x, y, z } = axis.into().normalized();
                let s = angle_radians.sin();
                let c = angle_radians.cos();
                let oc = T::one() - c;
                Self::new(
                    oc*x*x + c  , oc*x*y - z*s, oc*z*x + y*s,
                    oc*x*y + z*s, oc*y*y + c  , oc*y*z - x*s,
                    oc*z*x - y*s, oc*y*z + x*s, oc*z*z + c
                )
            }
            /// Creates a matrix that would rotate a `from` direction to `to`.
            ///
            /// ```
            /// # extern crate vek;
            /// # #[macro_use] extern crate approx;
            /// # use vek::{Vec3, Mat3};
            ///
            /// # fn main() {
            /// let (from, to) = (Vec3::<f32>::unit_x(), Vec3::<f32>::unit_z());
            /// let m = Mat3::<f32>::rotation_from_to_3d(from, to);
            /// assert_relative_eq!(m * from, to);
            ///
            /// let (from, to) = (Vec3::<f32>::unit_x(), -Vec3::<f32>::unit_x());
            /// let m = Mat3::<f32>::rotation_from_to_3d(from, to);
            /// assert_relative_eq!(m * from, to);
            /// # }
            /// ```
            pub fn rotation_from_to_3d<V: Into<Vec3<T>>>(from: V, to: V) -> Self
                where T: Real + Add<T, Output=T>
            {
                Self::from(Quaternion::rotation_from_to_3d(from, to))
            }
        }

        use super::mat4::Mat4;
        impl<T> From<Mat4<T>> for Mat3<T> {
            fn from(m: Mat4<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec3::new(
                        m.x.into(),
                        m.y.into(),
                        m.z.into()
                    )
                }
            }
        }
        use super::mat2::Mat2;
        impl<T> From<Mat2<T>> for Mat3<T> where T: Zero + One {
            fn from(m: Mat2<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec3::new(
                        m.x.into(),
                        m.y.into(),
                        Vec3::new(T::zero(), T::zero(), T::one())
                    )
                }
            }
        }
        impl<T> From<Quaternion<T>> for Mat3<T>
            where T: Copy + Zero + One + Mul<Output=T> + Add<Output=T> + Sub<Output=T>
        {
            fn from(q: Quaternion<T>) -> Self {
                Mat4::from(q).into()
            }
        }
        /* NOTE: Blocked by From<Mat4<T>> for Quaternion
        /// A quaternion may be obtained from a rotation matrix.
        ///
        /// ```
        /// # extern crate vek;
        /// # #[macro_use] extern crate approx;
        /// # use vek::{Mat3, Quaternion, Vec3};
        /// # fn main() {
        /// let (angle, axis) = (3_f32, Vec3::new(1_f32, 3., 7.));
        /// let a = Quaternion::rotation_3d(angle, axis);
        /// let b = Quaternion::from(Mat3::rotation_3d(angle, axis));
        /// assert_relative_eq!(a, b);
        /// # }
        /// ```
        impl<T> From<Mat3<T>> for Quaternion<T>
            where T: Zero + One + Mul<Output=T> + Add<Output=T> + Sub<Output=T> + Real
        {
            fn from(m: Mat3<T>) -> Self {
                Mat4::from(m).into()
            }
        }
        */

    };
}

#[allow(unused_macros)]
macro_rules! mat_impl_mat2 {
    (rows) => {

        mat_impl_mat2!{common rows}

        impl<T> Mat2<T> {
            /// Creates a new 2x2 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T,
                m10: T, m11: T
            ) -> Self {
                Self {
                    rows: CVec2::new(
                        Vec2::new(m00, m01),
                        Vec2::new(m10, m11)
                    )
                }
            }
        }
    };
    (cols) => {

        mat_impl_mat2!{common cols}

        impl<T> Mat2<T> {
            /// Creates a new 2x2 matrix from elements in a layout-agnostic way.
            ///
            /// The parameters are named `mij` where `i` is the row index and
            /// `j` the column index. Their order is always the same regardless
            /// of the matrix's layout.
            pub fn new(
                m00: T, m01: T,
                m10: T, m11: T
            ) -> Self {
                Self {
                    cols: CVec2::new(
                        Vec2::new(m00, m10),
                        Vec2::new(m01, m11),
                    )
                }
            }
        }
    };
    (common $lines:ident) => {
        impl<T> Mat2<T> {
            /// Returns an element-wise-converted copy of this matrix, using the given conversion
            /// closure.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let m = Mat4::<f32>::new(
            ///     0.25, 1.25, 5.56, 8.66,
            ///     8.53, 2.92, 3.86, 9.36,
            ///     1.02, 0.28, 5.52, 6.06,
            ///     6.20, 7.01, 4.90, 5.26
            /// );
            /// let m = m.map(|x| x.round() as i32);
            /// assert_eq!(m, Mat4::new(
            ///     0, 1, 6, 9,
            ///     9, 3, 4, 9,
            ///     1, 0, 6, 6,
            ///     6, 7, 5, 5
            /// ));
            /// ```
            pub fn map<D,F>(self, mut f: F) -> Mat2<D> where F: FnMut(T) -> D {
                let m = self.$lines;
                Mat2 {
                    $lines: CVec2::new(
                        Vec2::new(f(m.x.x), f(m.x.y)),
                        Vec2::new(f(m.y.x), f(m.y.y)),
                    )
                }
            }

            /// Returns a memberwise-converted copy of this matrix, using `AsPrimitive`.
            ///
            /// # Examples
            ///
            /// ```
            /// # use vek::vec::Vec4;
            /// let v = Vec4::new(0_f32, 1., 2., 3.);
            /// let i: Vec4<i32> = v.as_();
            /// assert_eq!(i, Vec4::new(0, 1, 2, 3));
            /// ```
            ///
            /// # Safety
            ///
            /// **In Rust versions before 1.45.0**, some uses of the `as` operator were not entirely safe.
            /// In particular, it was undefined behavior if
            /// a truncated floating point value could not fit in the target integer
            /// type ([#10184](https://github.com/rust-lang/rust/issues/10184));
            ///
            /// ```ignore
            /// # use num_traits::AsPrimitive;
            /// let x: u8 = (1.04E+17).as_(); // UB
            /// ```
            pub fn as_<D>(self) -> Mat2<D> where T: AsPrimitive<D>, D: 'static + Copy {
                let m = self.$lines;
                Mat2 {
                    $lines: CVec2::new(
                        Vec2::new(m.x.x.as_(), m.x.y.as_()),
                        Vec2::new(m.y.x.as_(), m.y.y.as_()),
                    )
                }
            }

            /// Applies the function f to each element of two matrices, pairwise, and returns the result.
            ///
            /// ```
            /// use vek::mat::repr_c::row_major::Mat4;
            ///
            /// let a = Mat4::<f32>::new(
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99,
            ///     0.25, 1.25, 2.52, 2.99
            /// );
            /// let b = Mat4::<i32>::new(
            ///     0, 1, 0, 0,
            ///     1, 0, 0, 0,
            ///     0, 0, 1, 0,
            ///     0, 0, 0, 1
            /// );
            /// let m = a.map2(b, |a, b| a.round() as i32 + b);
            /// assert_eq!(m, Mat4::new(
            ///     0, 2, 3, 3,
            ///     1, 1, 3, 3,
            ///     0, 1, 4, 3,
            ///     0, 1, 3, 4
            /// ));
            /// ```
            pub fn map2<D,F,S>(self, other: Mat2<S>, mut f: F) -> Mat2<D> where F: FnMut(T, S) -> D {
                let m = self.$lines;
                let o = other.$lines;
                Mat2 {
                    $lines: CVec2::new(
                        Vec2::new(f(m.x.x, o.x.x), f(m.x.y, o.x.y)),
                        Vec2::new(f(m.y.x, o.y.x), f(m.y.y, o.y.y))
                    )
                }
            }

            /// The matrix's transpose.
            ///
            /// ```
            /// # extern crate vek;
            /// # use vek::Mat2;
            ///
            /// # fn main() {
            /// let m = Mat2::new(
            ///     0, 1,
            ///     4, 5
            /// );
            /// let t = Mat2::new(
            ///     0, 4,
            ///     1, 5
            /// );
            /// assert_eq!(m.transposed(), t);
            /// assert_eq!(m, m.transposed().transposed());
            /// # }
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transposed(self) -> Self {
                let s = self.$lines;
                Self {
                    $lines: CVec2::new(
                        Vec2::new(s.x.x, s.y.x),
                        Vec2::new(s.x.y, s.y.y)
                    )
                }
            }
            /// Transpose this matrix.
            ///
            /// ```
            /// # use vek::Mat2;
            ///
            /// let mut m = Mat2::new(
            ///     0, 1,
            ///     4, 5
            /// );
            /// let t = Mat2::new(
            ///     0, 4,
            ///     1, 5
            /// );
            /// m.transpose();
            /// assert_eq!(m, t);
            /// ```
            // NOTE: Implemented on a per-matrix basis to avoid a Clone bound on T
            pub fn transpose(&mut self) {
                mem::swap(&mut self.$lines.x.y, &mut self.$lines.y.x);
            }

            /// Get this matrix's determinant.
            ///
            /// A matrix is invertible if its determinant is non-zero.
            ///
            /// ```
            /// # use vek::Mat2;
            /// let (a,b,c,d) = (0,1,2,3);
            /// let m = Mat2::new(a,b,c,d);
            /// assert_eq!(m.determinant(), a*d - c*b);
            /// ```
            pub fn determinant(self) -> T where T: Mul<T,Output=T> + Sub<T,Output=T> {
                // NOTE: This works on row-major as well as column-major.
                let CVec2 {
                    x: Vec2 { x: a, y: b },
                    y: Vec2 { x: c, y: d },
                } = self.$lines;
                a*d - c*b
            }

            /// Rotates this matrix around the Z axis (counter-clockwise rotation in 2D).
            pub fn rotate_z(&mut self, angle_radians: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.rotated_z(angle_radians);
            }
            /// Rotates this matrix around the Z axis (counter-clockwise rotation in 2D).
            pub fn rotated_z(self, angle_radians: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::rotation_z(angle_radians) * self
            }
            /// Creates a matrix that rotates around the Z axis (counter-clockwise rotation in 2D).
            pub fn rotation_z(angle_radians: T) -> Self where T: Real {
                let c = angle_radians.cos();
                let s = angle_radians.sin();
                Self::new(
                    c, -s,
                    s,  c
                )
            }
            /// Scales this matrix in 2D.
            pub fn scale_2d<V: Into<Vec2<T>>>(&mut self, v: V)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.scaled_2d(v);
            }
            /// Returns this matrix scaled in 2D.
            pub fn scaled_2d<V: Into<Vec2<T>>>(self, v: V) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::scaling_2d(v) * self
            }
            /// Creates a 2D scaling matrix.
            pub fn scaling_2d<V: Into<Vec2<T>>>(v: V) -> Self where T: Zero {
                let Vec2 { x, y } = v.into();
                Self::new(
                    x, T::zero(),
                    T::zero(), y
                )
            }
            /// Shears this matrix along the X axis.
            pub fn shear_x(&mut self, k: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.sheared_x(k);
            }
            /// Returns this matrix sheared along the X axis.
            pub fn sheared_x(self, k: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::shearing_x(k) * self
            }
            /// Creates a 2D shearing matrix along the X axis.
            pub fn shearing_x(k: T) -> Self where T: Zero + One {
                Self::new(
                    T::one(), k,
                    T::zero(), T::one()
                )
            }
            /// Shears this matrix along the Y axis.
            pub fn shear_y(&mut self, k: T)
                where T: Real + MulAdd<T,T,Output=T>
            {
                *self = self.sheared_y(k);
            }
            /// Returns this matrix sheared along the Y axis.
            pub fn sheared_y(self, k: T) -> Self
                where T: Real + MulAdd<T,T,Output=T>
            {
                Self::shearing_y(k) * self
            }
            /// Creates a 2D shearing matrix along the Y axis.
            pub fn shearing_y(k: T) -> Self where T: Zero + One {
                Self::new(
                    T::one(), T::zero(),
                    k, T::one()
                )
            }
        }
        use super::mat3::Mat3;
        impl<T> From<Mat3<T>> for Mat2<T> {
            fn from(m: Mat3<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec2::new(
                        m.x.into(),
                        m.y.into(),
                    )
                }
            }
        }
        use super::mat4::Mat4;
        impl<T> From<Mat4<T>> for Mat2<T> {
            fn from(m: Mat4<T>) -> Self {
                let m = m.$lines;
                Self {
                    $lines: CVec2::new(
                        m.x.into(),
                        m.y.into(),
                    )
                }
            }
        }

    };
}




macro_rules! mat_impl_all_mats {
    ($lines:ident) => {
        /// 4x4 matrix.
        pub mod mat4 {
            use super::*;
            /// 4x4 matrix.
            #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq/* , Ord, PartialOrd */)]
            #[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
            #[repr(C)]
            pub struct Mat4<T> {
                #[allow(missing_docs)]
                pub $lines: CVec4<Vec4<T>>,
            }
            mat_impl_mat!{$lines Mat4 RowMatrix4 ColumnMatrix4 CVec4 Vec4 (4 x 4) (x y z w)}
            mat_impl_mat4!{$lines}
        }
        pub use self::mat4::Mat4;

        /// 3x3 matrix.
        pub mod mat3 {
            use super::*;
            /// 3x3 matrix.
            #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq/* , Ord, PartialOrd */)]
            #[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
            #[repr(C)]
            pub struct Mat3<T> {
                #[allow(missing_docs)]
                pub $lines: CVec3<Vec3<T>>,
            }
            mat_impl_mat!{$lines Mat3 RowMatrix3 ColumnMatrix3 CVec3 Vec3 (3 x 3) (x y z)}
            mat_impl_mat3!{$lines}
        }
        pub use self::mat3::Mat3;

        /// 2x2 matrix.
        pub mod mat2 {
            use super::*;
            /// 2x2 matrix.
            #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq/* , Ord, PartialOrd */)]
            #[cfg_attr(feature="serde", derive(Serialize, Deserialize))]
            #[repr(C)]
            pub struct Mat2<T> {
                #[allow(missing_docs)]
                pub $lines: CVec2<Vec2<T>>,
            }
            mat_impl_mat!{$lines Mat2 RowMatrix2 ColumnMatrix2 CVec2 Vec2 (2 x 2) (x y)}
            mat_impl_mat2!{$lines}
        }
        pub use self::mat2::Mat2;

    }
}

macro_rules! mat_declare_modules {
    () => {
        pub mod column_major {
            //! Matrices stored in column-major layout.
            //!
            //! Multiplying a column-major matrix by one or more column vectors is fast
            //! due to the way it is implemented in SIMD
            //! (a `matrix * vector` mutliply is four broadcasts, one SIMD product and three fused-multiply-adds).
            //!
            //! Because `matrix * matrix` and `matrix * vector` products are fastest with this layout,
            //! it's the preferred one for most computer graphics libraries and application.

            use super::*;
            mat_impl_all_mats!{cols}
        }
        pub mod row_major {
            //! Matrices stored in row-major layout.
            //!
            //! Unlike the column-major layout, row-major matrices are good at being the
            //! right-hand-side of a product with one or more row vectors.
            //!
            //! Also, their natural indexing order matches the existing mathematical conventions.

            use super::*;
            mat_impl_all_mats!{rows}
        }
        /// Column-major layout is the default.
        ///
        /// Rationale:
        /// - (Matrix * Vector) multiplications are more efficient;
        /// - This is the layout expected by OpenGL;
        pub use self::column_major::*;
    }
}

pub mod repr_c {
    //! Matrix types which use `#[repr(C)]` vectors exclusively.
    //!
    //! See also the `repr_simd` neighbour module, which is available on Nightly
    //! with the `repr_simd` feature enabled.

    use super::*;
    #[allow(unused_imports)]
    use super::vec::repr_c::{Vec2, Vec2 as CVec2};
    #[allow(unused_imports)]
    use super::vec::repr_c::{Vec3, Vec3 as CVec3};
    use super::vec::repr_c::{Vec4, Vec4 as CVec4};

    use super::quaternion::repr_c::Quaternion;
    use super::transform::repr_c::Transform;

    mat_declare_modules!{}
}

#[cfg(all(nightly, feature="repr_simd"))]
pub mod repr_simd {
    //! Matrix types which use a `#[repr(C)]` vector of `#[repr(simd)]` vectors.

    use super::*;
    #[allow(unused_imports)]
    use super::vec::repr_simd::{Vec2};
    #[allow(unused_imports)]
    use super::vec::repr_c::{Vec2 as CVec2};
    #[allow(unused_imports)]
    use super::vec::repr_simd::{Vec3};
    #[allow(unused_imports)]
    use super::vec::repr_c::{Vec3 as CVec3};
    use super::vec::repr_simd::{Vec4};
    use super::vec::repr_c::{Vec4 as CVec4};

    use super::quaternion::repr_simd::Quaternion;
    use super::transform::repr_simd::Transform;

    mat_declare_modules!{}
}

pub use self::repr_c::*;


#[cfg(test)]
mod tests {
    macro_rules! for_each_type {
        ($mat:ident $Mat:ident $($T:ident)+) => {
            mod $mat {
                // repr_c matrices are expected to be packed.
                // repr_simd matrices are not necessarily expected to be packed in the first place.
                mod repr_c {
                    $(mod $T {
                        use $crate::mat::repr_c::column_major::$Mat;
                        use $crate::vtest::Rc;

                        #[test]
                        fn is_actually_packed() {
                            let m = $Mat::<$T>::identity();
                            let a = m.clone().into_row_array(); // same as into_col_array(), because identity.
                            let mp = unsafe {
                                ::std::slice::from_raw_parts(&m as *const _ as *const $T, a.len())
                            };
                            assert_eq!(mp, &a);
                        }
                        #[test]
                        fn is_actually_packed_refcell() {
                            let m = $Mat::<$T>::identity().map(::std::cell::RefCell::new);
                            let a = m.clone().into_row_array(); // same as into_col_array(), because identity.
                            let mp = unsafe {
                                ::std::slice::from_raw_parts(&m as *const _ as *const ::std::cell::RefCell<$T>, a.len())
                            };
                            assert_eq!(mp, &a);
                        }
                        #[test] fn claims_to_be_packed() { assert!($Mat::<$T>::default().is_packed()); }
                        #[test] fn claims_to_be_packed_refcell() { assert!($Mat::<$T>::default().map(::std::cell::RefCell::new).is_packed()); }

                        #[test]
                        fn rc_col_array_conversions() {
                            let m: $Mat<Rc<i32>> = $Mat::default().map(Rc::new);
                            let mut a = m.into_col_array();
                            assert_eq!(Rc::strong_count(&a[0]), 1);
                            *Rc::make_mut(&mut a[0]) = 2; // Try to write. If there's a double free, this is supposed to crash.
                            let mut m = $Mat::from_col_array(a);
                            assert_eq!(Rc::strong_count(&m[(0, 0)]), 1);
                            *Rc::make_mut(&mut m[(0, 0)]) = 3; // Try to write. If there's a double free, this is supposed to crash.
                        }
                        #[test]
                        fn rc_row_array_conversions() {
                            let m: $Mat<Rc<i32>> = $Mat::default().map(Rc::new);
                            let mut a = m.into_row_array();
                            assert_eq!(Rc::strong_count(&a[0]), 1);
                            *Rc::make_mut(&mut a[0]) = 2; // Try to write. If there's a double free, this is supposed to crash.
                            let mut m = $Mat::from_row_array(a);
                            assert_eq!(Rc::strong_count(&m[(0, 0)]), 1);
                            *Rc::make_mut(&mut m[(0, 0)]) = 3; // Try to write. If there's a double free, this is supposed to crash.
                        }
                    })+
                }
                #[cfg(all(nightly, feature="repr_simd"))]
                mod repr_simd {
                    mod bool {
                        use $crate::mat::repr_simd::column_major::$Mat;
                        #[test]
                        fn can_monomorphize() {
                            let _: $Mat<bool> = $Mat::<u32>::identity().map(|x| x != 0);
                        }
                    }
                }
            }
        };
    }
    // Vertical editing helps here :)
    for_each_type!{mat2 Mat2 i8 u8 i16 u16 i32 u32 i64 u64 f32 f64}
    for_each_type!{mat3 Mat3 i8 u8 i16 u16 i32 u32 i64 u64 f32 f64}
    for_each_type!{mat4 Mat4 i8 u8 i16 u16 i32 u32 i64 u64 f32 f64}

    use super::Mat4;
    use super::super::vec::Vec4;


    #[test] fn simple_mat2() {
        use crate::vec::Vec2;
        use crate::mat::row_major::Mat2 as Rows2;
        use crate::mat::column_major::Mat2 as Cols2;
        let a = Rows2::new(
            1, 2,
            3, 4
        );
        let b = Cols2::new(
            1, 2,
            3, 4
        );
        let v = Vec2::new(2, 3);

        // Not available on no_std, but don't worry, it's been long proven.
        // assert_eq!(format!("{}", a), format!("{}", b));
        
        assert_eq!(v * a, v * b);
        assert_eq!(a * v, b * v);
    }

    #[test]
    fn test_model_look_at_rh() {
        let eye = Vec4::new(1_f32, 0., 1., 1.);
        let target = Vec4::new(2_f32, 0., 2., 1.);
        let model = Mat4::<f32>::model_look_at_rh(eye, target, Vec4::up());
        assert_relative_eq!(model * Vec4::unit_w(), Vec4::new(1_f32, 0., 1., 1.));
        assert_relative_eq!(model * Vec4::new(0_f32, 0., -2_f32.sqrt(), 1.), Vec4::new(2_f32, 0., 2., 1.));

        // A "model" look-at essentially undoes a "view" look-at
        let view = Mat4::<f32>::look_at_rh(eye, target, Vec4::up());
        assert_relative_eq!(view * model, Mat4::identity());
        assert_relative_eq!(model * view, Mat4::identity());
    }

    #[test]
    fn test_model_look_at_lh() {
        let eye = Vec4::new(1_f32, 0., 1., 1.);
        let target = Vec4::new(2_f32, 0., 2., 1.);
        let model = Mat4::<f32>::model_look_at_lh(eye, target, Vec4::up());
        assert_relative_eq!(model * Vec4::unit_w(), eye);
        let d = 2_f32.sqrt();
        assert_relative_eq!(model * Vec4::new(0_f32, 0., d, 1.), target);

        // A "model" look-at essentially undoes a "view" look-at
        let view = Mat4::look_at_lh(eye, target, Vec4::up());
        assert_relative_eq!(view * model, Mat4::identity());
        assert_relative_eq!(model * view, Mat4::identity());
    }

    #[test]
    fn test_look_at_rh() {
        let eye = Vec4::new(1_f32, 0., 1., 1.);
        let target = Vec4::new(2_f32, 0., 2., 1.);
        let view = Mat4::<f32>::look_at_rh(eye, target, Vec4::up());
        assert_relative_eq!(view * eye, Vec4::unit_w());
        assert_relative_eq!(view * target, Vec4::new(0_f32, 0., -2_f32.sqrt(), 1.));
    }

    #[test]
    fn test_look_at_lh() {
        let eye = Vec4::new(1_f32, 0., 1., 1.);
        let target = Vec4::new(2_f32, 0., 2., 1.);
        let view = Mat4::<f32>::look_at_lh(eye, target, Vec4::up());
        assert_relative_eq!(view * eye, Vec4::unit_w());
        assert_relative_eq!(view * target, Vec4::new(0_f32, 0., 2_f32.sqrt(), 1.));
    }

}