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
|
// Copyright (C) 2002-2012 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_X_LOADER_
#include "CXMeshFileLoader.h"
#include "os.h"
#include "fast_atof.h"
#include "coreutil.h"
#include "ISceneManager.h"
#include "IVideoDriver.h"
#include "IFileSystem.h"
#include "IReadFile.h"
#ifdef _DEBUG
#define _XREADER_DEBUG
#endif
//#define BETTER_MESHBUFFER_SPLITTING_FOR_X
namespace irr
{
namespace scene
{
//! Constructor
CXMeshFileLoader::CXMeshFileLoader(scene::ISceneManager* smgr, io::IFileSystem* fs)
: SceneManager(smgr), FileSystem(fs), AllJoints(0), AnimatedMesh(0),
Buffer(0), P(0), End(0), BinaryNumCount(0), Line(0),
CurFrame(0), MajorVersion(0), MinorVersion(0), BinaryFormat(false), FloatSize(0)
{
#ifdef _DEBUG
setDebugName("CXMeshFileLoader");
#endif
}
//! returns true if the file maybe is able to be loaded by this class
//! based on the file extension (e.g. ".bsp")
bool CXMeshFileLoader::isALoadableFileExtension(const io::path& filename) const
{
return core::hasFileExtension ( filename, "x" );
}
//! creates/loads an animated mesh from the file.
//! \return Pointer to the created mesh. Returns 0 if loading failed.
//! If you no longer need the mesh, you should call IAnimatedMesh::drop().
//! See IReferenceCounted::drop() for more information.
IAnimatedMesh* CXMeshFileLoader::createMesh(io::IReadFile* f)
{
if (!f)
return 0;
#ifdef _XREADER_DEBUG
u32 time = os::Timer::getRealTime();
#endif
AnimatedMesh = new CSkinnedMesh();
if (load(f))
{
AnimatedMesh->finalize();
}
else
{
AnimatedMesh->drop();
AnimatedMesh = 0;
}
#ifdef _XREADER_DEBUG
time = os::Timer::getRealTime() - time;
core::stringc tmpString = "Time to load ";
tmpString += BinaryFormat ? "binary" : "ascii";
tmpString += " X file: ";
tmpString += time;
tmpString += "ms";
os::Printer::log(tmpString.c_str());
#endif
//Clear up
MajorVersion=0;
MinorVersion=0;
BinaryFormat=0;
BinaryNumCount=0;
FloatSize=0;
P=0;
End=0;
CurFrame=0;
TemplateMaterials.clear();
delete [] Buffer;
Buffer = 0;
for (u32 i=0; i<Meshes.size(); ++i)
delete Meshes[i];
Meshes.clear();
return AnimatedMesh;
}
bool CXMeshFileLoader::load(io::IReadFile* file)
{
if (!readFileIntoMemory(file))
return false;
if (!parseFile())
return false;
for (u32 n=0; n<Meshes.size(); ++n)
{
SXMesh *mesh=Meshes[n];
// default material if nothing loaded
if (!mesh->Materials.size())
{
mesh->Materials.push_back(video::SMaterial());
mesh->Materials[0].DiffuseColor.set(0xff777777);
mesh->Materials[0].Shininess=0.f;
mesh->Materials[0].SpecularColor.set(0xff777777);
mesh->Materials[0].EmissiveColor.set(0xff000000);
}
u32 i;
mesh->Buffers.reallocate(mesh->Materials.size());
#ifndef BETTER_MESHBUFFER_SPLITTING_FOR_X
const u32 bufferOffset = AnimatedMesh->getMeshBufferCount();
#endif
for (i=0; i<mesh->Materials.size(); ++i)
{
mesh->Buffers.push_back( AnimatedMesh->addMeshBuffer() );
mesh->Buffers.getLast()->Material = mesh->Materials[i];
if (!mesh->HasSkinning)
{
//Set up rigid animation
if (mesh->AttachedJointID!=-1)
{
AnimatedMesh->getAllJoints()[mesh->AttachedJointID]->AttachedMeshes.push_back( AnimatedMesh->getMeshBuffers().size()-1 );
}
}
}
if (!mesh->FaceMaterialIndices.size())
{
mesh->FaceMaterialIndices.set_used(mesh->Indices.size() / 3);
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
mesh->FaceMaterialIndices[i]=0;
}
if (!mesh->HasVertexColors)
{
for (u32 j=0;j<mesh->FaceMaterialIndices.size();++j)
{
for (u32 id=j*3+0;id<=j*3+2;++id)
{
mesh->Vertices[ mesh->Indices[id] ].Color = mesh->Buffers[mesh->FaceMaterialIndices[j]]->Material.DiffuseColor;
}
}
}
#ifdef BETTER_MESHBUFFER_SPLITTING_FOR_X
{
//the same vertex can be used in many different meshbuffers, but it's slow to work out
core::array< core::array< u32 > > verticesLinkIndex;
verticesLinkIndex.reallocate(mesh->Vertices.size());
core::array< core::array< u16 > > verticesLinkBuffer;
verticesLinkBuffer.reallocate(mesh->Vertices.size());
for (i=0;i<mesh->Vertices.size();++i)
{
verticesLinkIndex.push_back( core::array< u32 >() );
verticesLinkBuffer.push_back( core::array< u16 >() );
}
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
for (u32 id=i*3+0;id<=i*3+2;++id)
{
core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ];
bool found=false;
for (u32 j=0; j < Array.size(); ++j)
{
if (Array[j]==mesh->FaceMaterialIndices[i])
{
found=true;
break;
}
}
if (!found)
Array.push_back( mesh->FaceMaterialIndices[i] );
}
}
for (i=0;i<verticesLinkBuffer.size();++i)
{
if (!verticesLinkBuffer[i].size())
verticesLinkBuffer[i].push_back(0);
}
for (i=0;i<mesh->Vertices.size();++i)
{
core::array< u16 > &Array = verticesLinkBuffer[i];
verticesLinkIndex[i].reallocate(Array.size());
for (u32 j=0; j < Array.size(); ++j)
{
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ Array[j] ];
verticesLinkIndex[i].push_back( buffer->Vertices_Standard.size() );
buffer->Vertices_Standard.push_back( mesh->Vertices[i] );
}
}
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
scene::SSkinMeshBuffer *buffer=mesh->Buffers[ mesh->FaceMaterialIndices[i] ];
for (u32 id=i*3+0;id<=i*3+2;++id)
{
core::array< u16 > &Array=verticesLinkBuffer[ mesh->Indices[id] ];
for (u32 j=0;j< Array.size() ;++j)
{
if ( Array[j]== mesh->FaceMaterialIndices[i] )
buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ][j] );
}
}
}
for (u32 j=0;j<mesh->WeightJoint.size();++j)
{
ISkinnedMesh::SJoint* joint = AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]];
ISkinnedMesh::SWeight& weight = joint->Weights[mesh->WeightNum[j]];
u32 id = weight.vertex_id;
if (id>=verticesLinkIndex.size())
{
os::Printer::log("X loader: Weight id out of range", ELL_WARNING);
id=0;
weight.strength=0.f;
}
if (verticesLinkBuffer[id].size()==1)
{
weight.vertex_id=verticesLinkIndex[id][0];
weight.buffer_id=verticesLinkBuffer[id][0];
}
else if (verticesLinkBuffer[id].size() != 0)
{
for (u32 k=1; k < verticesLinkBuffer[id].size(); ++k)
{
ISkinnedMesh::SWeight* WeightClone = AnimatedMesh->addWeight(joint);
WeightClone->strength = weight.strength;
WeightClone->vertex_id = verticesLinkIndex[id][k];
WeightClone->buffer_id = verticesLinkBuffer[id][k];
}
}
}
}
#else
{
core::array< u32 > verticesLinkIndex;
core::array< s16 > verticesLinkBuffer;
verticesLinkBuffer.set_used(mesh->Vertices.size());
// init with 0
for (i=0;i<mesh->Vertices.size();++i)
{
// watch out for vertices which are not part of the mesh
// they will keep the -1 and can lead to out-of-bounds access
verticesLinkBuffer[i]=-1;
}
bool warned = false;
// store meshbuffer number per vertex
for (i=0;i<mesh->FaceMaterialIndices.size();++i)
{
for (u32 id=i*3+0;id<=i*3+2;++id)
{
if ((verticesLinkBuffer[mesh->Indices[id]] != -1) && (verticesLinkBuffer[mesh->Indices[id]] != (s16)mesh->FaceMaterialIndices[i]))
{
if (!warned)
{
os::Printer::log("X loader", "Duplicated vertex, animation might be corrupted.", ELL_WARNING);
warned=true;
}
const u32 tmp = mesh->Vertices.size();
mesh->Vertices.push_back(mesh->Vertices[ mesh->Indices[id] ]);
mesh->Indices[id] = tmp;
verticesLinkBuffer.set_used(mesh->Vertices.size());
}
verticesLinkBuffer[ mesh->Indices[id] ] = mesh->FaceMaterialIndices[i];
}
}
if (mesh->FaceMaterialIndices.size() != 0)
{
// store vertices in buffers and remember relation in verticesLinkIndex
u32* vCountArray = new u32[mesh->Buffers.size()];
memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32));
// count vertices in each buffer and reallocate
for (i=0; i<mesh->Vertices.size(); ++i)
{
if (verticesLinkBuffer[i] != -1)
++vCountArray[verticesLinkBuffer[i]];
}
if (mesh->TCoords2.size())
{
for (i=0; i!=mesh->Buffers.size(); ++i)
{
mesh->Buffers[i]->Vertices_2TCoords.reallocate(vCountArray[i]);
mesh->Buffers[i]->VertexType=video::EVT_2TCOORDS;
}
}
else
{
for (i=0; i!=mesh->Buffers.size(); ++i)
mesh->Buffers[i]->Vertices_Standard.reallocate(vCountArray[i]);
}
verticesLinkIndex.set_used(mesh->Vertices.size());
// actually store vertices
for (i=0; i<mesh->Vertices.size(); ++i)
{
// if a vertex is missing for some reason, just skip it
if (verticesLinkBuffer[i]==-1)
continue;
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ verticesLinkBuffer[i] ];
if (mesh->TCoords2.size())
{
verticesLinkIndex[i] = buffer->Vertices_2TCoords.size();
buffer->Vertices_2TCoords.push_back( mesh->Vertices[i] );
// We have a problem with correct tcoord2 handling here
// crash fixed for now by checking the values
buffer->Vertices_2TCoords.getLast().TCoords2=(i<mesh->TCoords2.size())?mesh->TCoords2[i]:mesh->Vertices[i].TCoords;
}
else
{
verticesLinkIndex[i] = buffer->Vertices_Standard.size();
buffer->Vertices_Standard.push_back( mesh->Vertices[i] );
}
}
// count indices per buffer and reallocate
memset(vCountArray, 0, mesh->Buffers.size()*sizeof(u32));
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
++vCountArray[ mesh->FaceMaterialIndices[i] ];
for (i=0; i!=mesh->Buffers.size(); ++i)
mesh->Buffers[i]->Indices.reallocate(vCountArray[i]);
delete [] vCountArray;
// create indices per buffer
for (i=0; i<mesh->FaceMaterialIndices.size(); ++i)
{
scene::SSkinMeshBuffer *buffer = mesh->Buffers[ mesh->FaceMaterialIndices[i] ];
for (u32 id=i*3+0; id!=i*3+3; ++id)
{
buffer->Indices.push_back( verticesLinkIndex[ mesh->Indices[id] ] );
}
}
}
for (u32 j=0; j<mesh->WeightJoint.size(); ++j)
{
ISkinnedMesh::SWeight& weight = (AnimatedMesh->getAllJoints()[mesh->WeightJoint[j]]->Weights[mesh->WeightNum[j]]);
u32 id = weight.vertex_id;
if (id>=verticesLinkIndex.size())
{
os::Printer::log("X loader: Weight id out of range", ELL_WARNING);
id=0;
weight.strength=0.f;
}
weight.vertex_id=verticesLinkIndex[id];
weight.buffer_id=verticesLinkBuffer[id] + bufferOffset;
}
}
#endif
}
return true;
}
//! Reads file into memory
bool CXMeshFileLoader::readFileIntoMemory(io::IReadFile* file)
{
const long size = file->getSize();
if (size < 12)
{
os::Printer::log("X File is too small.", ELL_WARNING);
return false;
}
Buffer = new c8[size];
//! read all into memory
if (file->read(Buffer, size) != size)
{
os::Printer::log("Could not read from x file.", ELL_WARNING);
return false;
}
Line = 1;
End = Buffer + size;
//! check header "xof "
if (strncmp(Buffer, "xof ", 4)!=0)
{
os::Printer::log("Not an x file, wrong header.", ELL_WARNING);
return false;
}
//! read minor and major version, e.g. 0302 or 0303
c8 tmp[3];
tmp[0] = Buffer[4];
tmp[1] = Buffer[5];
tmp[2] = 0x0;
MajorVersion = core::strtoul10(tmp);
tmp[0] = Buffer[6];
tmp[1] = Buffer[7];
MinorVersion = core::strtoul10(tmp);
//! read format
if (strncmp(&Buffer[8], "txt ", 4) ==0)
BinaryFormat = false;
else if (strncmp(&Buffer[8], "bin ", 4) ==0)
BinaryFormat = true;
else
{
os::Printer::log("Only uncompressed x files currently supported.", ELL_WARNING);
return false;
}
BinaryNumCount=0;
//! read float size
if (strncmp(&Buffer[12], "0032", 4) ==0)
FloatSize = 4;
else if (strncmp(&Buffer[12], "0064", 4) ==0)
FloatSize = 8;
else
{
os::Printer::log("Float size not supported.", ELL_WARNING);
return false;
}
P = &Buffer[16];
readUntilEndOfLine();
FilePath = FileSystem->getFileDir(file->getFileName()) + "/";
return true;
}
//! Parses the file
bool CXMeshFileLoader::parseFile()
{
while(parseDataObject())
{
// loop
}
return true;
}
//! Parses the next Data object in the file
bool CXMeshFileLoader::parseDataObject()
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
return false;
// parse specific object
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject:", objectName.c_str(), ELL_DEBUG);
#endif
if (objectName == "template")
return parseDataObjectTemplate();
else
if (objectName == "Frame")
{
return parseDataObjectFrame( 0 );
}
else
if (objectName == "Mesh")
{
// some meshes have no frames at all
//CurFrame = AnimatedMesh->addJoint(0);
SXMesh *mesh=new SXMesh;
//mesh->Buffer=AnimatedMesh->addMeshBuffer();
Meshes.push_back(mesh);
return parseDataObjectMesh(*mesh);
}
else
if (objectName == "AnimationSet")
{
return parseDataObjectAnimationSet();
}
else
if (objectName == "Material")
{
// template materials now available thanks to joeWright
TemplateMaterials.push_back(SXTemplateMaterial());
TemplateMaterials.getLast().Name = getNextToken();
return parseDataObjectMaterial(TemplateMaterials.getLast().Material);
}
else
if (objectName == "}")
{
os::Printer::log("} found in dataObject", ELL_WARNING);
return true;
}
os::Printer::log("Unknown data object in animation of .x file", objectName.c_str(), ELL_WARNING);
return parseUnknownDataObject();
}
bool CXMeshFileLoader::parseDataObjectTemplate()
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading template", ELL_DEBUG);
#endif
// parse a template data object. Currently not stored.
core::stringc name;
if (!readHeadOfDataObject(&name))
{
os::Printer::log("Left delimiter in template data object missing.",
name.c_str(), ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read GUID
getNextToken();
// read and ignore data members
while(true)
{
core::stringc s = getNextToken();
if (s == "}")
break;
if (s.size() == 0)
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectFrame(CSkinnedMesh::SJoint *Parent)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading frame", ELL_DEBUG);
#endif
// A coordinate frame, or "frame of reference." The Frame template
// is open and can contain any object. The Direct3D extensions (D3DX)
// mesh-loading functions recognize Mesh, FrameTransformMatrix, and
// Frame template instances as child objects when loading a Frame
// instance.
u32 JointID=0;
core::stringc name;
if (!readHeadOfDataObject(&name))
{
os::Printer::log("No opening brace in Frame found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
CSkinnedMesh::SJoint *joint=0;
if (name.size())
{
for (u32 n=0; n < AnimatedMesh->getAllJoints().size(); ++n)
{
if (AnimatedMesh->getAllJoints()[n]->Name==name)
{
joint=AnimatedMesh->getAllJoints()[n];
JointID=n;
break;
}
}
}
if (!joint)
{
#ifdef _XREADER_DEBUG
os::Printer::log("creating joint ", name.c_str(), ELL_DEBUG);
#endif
joint=AnimatedMesh->addJoint(Parent);
joint->Name=name;
JointID=AnimatedMesh->getAllJoints().size()-1;
}
else
{
#ifdef _XREADER_DEBUG
os::Printer::log("using joint ", name.c_str(), ELL_DEBUG);
#endif
if (Parent)
Parent->Children.push_back(joint);
}
// Now inside a frame.
// read tokens until closing brace is reached.
while(true)
{
core::stringc objectName = getNextToken();
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject in frame:", objectName.c_str(), ELL_DEBUG);
#endif
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Frame in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // frame finished
}
else
if (objectName == "Frame")
{
if (!parseDataObjectFrame(joint))
return false;
}
else
if (objectName == "FrameTransformMatrix")
{
if (!parseDataObjectTransformationMatrix(joint->LocalMatrix))
return false;
//joint->LocalAnimatedMatrix
//joint->LocalAnimatedMatrix.makeInverse();
//joint->LocalMatrix=tmp*joint->LocalAnimatedMatrix;
}
else
if (objectName == "Mesh")
{
/*
frame.Meshes.push_back(SXMesh());
if (!parseDataObjectMesh(frame.Meshes.getLast()))
return false;
*/
SXMesh *mesh=new SXMesh;
mesh->AttachedJointID=JointID;
Meshes.push_back(mesh);
if (!parseDataObjectMesh(*mesh))
return false;
}
else
{
os::Printer::log("Unknown data object in frame in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectTransformationMatrix(core::matrix4 &mat)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading Transformation Matrix", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
readMatrix(mat);
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Transformation Matrix found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMesh(SXMesh &mesh)
{
core::stringc name;
if (!readHeadOfDataObject(&name))
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh", ELL_DEBUG);
#endif
os::Printer::log("No opening brace in Mesh found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh", name.c_str(), ELL_DEBUG);
#endif
// read vertex count
const u32 nVertices = readInt();
// read vertices
mesh.Vertices.set_used(nVertices);
for (u32 n=0; n<nVertices; ++n)
{
readVector3(mesh.Vertices[n].Pos);
mesh.Vertices[n].Color=0xFFFFFFFF;
}
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Vertex Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
// read faces
const u32 nFaces = readInt();
mesh.Indices.set_used(nFaces * 3);
mesh.IndexCountPerFace.set_used(nFaces);
core::array<u32> polygonfaces;
u32 currentIndex = 0;
for (u32 k=0; k<nFaces; ++k)
{
const u32 fcnt = readInt();
if (fcnt != 3)
{
if (fcnt < 3)
{
os::Printer::log("Invalid face count (<3) found in Mesh x file reader.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read face indices
polygonfaces.set_used(fcnt);
u32 triangles = (fcnt-2);
mesh.Indices.set_used(mesh.Indices.size() + ((triangles-1)*3));
mesh.IndexCountPerFace[k] = (u16)(triangles * 3);
for (u32 f=0; f<fcnt; ++f)
polygonfaces[f] = readInt();
for (u32 jk=0; jk<triangles; ++jk)
{
mesh.Indices[currentIndex++] = polygonfaces[0];
mesh.Indices[currentIndex++] = polygonfaces[jk+1];
mesh.Indices[currentIndex++] = polygonfaces[jk+2];
}
// TODO: change face indices in material list
}
else
{
mesh.Indices[currentIndex++] = readInt();
mesh.Indices[currentIndex++] = readInt();
mesh.Indices[currentIndex++] = readInt();
mesh.IndexCountPerFace[k] = 3;
}
}
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Face Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
// here, other data objects may follow
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Mesh in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // mesh finished
}
#ifdef _XREADER_DEBUG
os::Printer::log("debug DataObject in mesh:", objectName.c_str(), ELL_DEBUG);
#endif
if (objectName == "MeshNormals")
{
if (!parseDataObjectMeshNormals(mesh))
return false;
}
else
if (objectName == "MeshTextureCoords")
{
if (!parseDataObjectMeshTextureCoords(mesh))
return false;
}
else
if (objectName == "MeshVertexColors")
{
if (!parseDataObjectMeshVertexColors(mesh))
return false;
}
else
if (objectName == "MeshMaterialList")
{
if (!parseDataObjectMeshMaterialList(mesh))
return false;
}
else
if (objectName == "VertexDuplicationIndices")
{
// we'll ignore vertex duplication indices
// TODO: read them
if (!parseUnknownDataObject())
return false;
}
else
if (objectName == "DeclData")
{
// arbitrary vertex attributes
// first comes the number of element definitions
// then the vertex element type definitions
// with format type;tesselator;semantics;usageindex
// we want to support 2;0;6;0 == tangent
// 2;0;7;0 == binormal
// 2;0;3;0 == normal
// 1/2;0;5;0 == 1st uv coord
// and 1/2;0;5;1 == 2nd uv coord
// type==2 is 3xf32, type==1 is 2xf32
u32 j;
const u32 dcnt = readInt();
u16 size = 0;
s16 normalpos = -1;
s16 uvpos = -1;
s16 uv2pos = -1;
s16 tangentpos = -1;
s16 binormalpos = -1;
s16 normaltype = -1;
s16 uvtype = -1;
s16 uv2type = -1;
s16 tangenttype = -1;
s16 binormaltype = -1;
for (j=0; j<dcnt; ++j)
{
const u32 type = readInt();
//const u32 tesselator = readInt();
readInt();
const u32 semantics = readInt();
const u32 index = readInt();
switch (semantics)
{
case 3:
normalpos = size;
normaltype = type;
break;
case 5:
if (index==0)
{
uvpos = size;
uvtype = type;
}
else if (index==1)
{
uv2pos = size;
uv2type = type;
}
break;
case 6:
tangentpos = size;
tangenttype = type;
break;
case 7:
binormalpos = size;
binormaltype = type;
break;
default:
break;
}
switch (type)
{
case 0:
size += 4;
break;
case 1:
size += 8;
break;
case 2:
size += 12;
break;
case 3:
size += 16;
break;
case 4:
case 5:
case 6:
size += 4;
break;
case 7:
size += 8;
break;
case 8:
case 9:
size += 4;
break;
case 10:
size += 8;
break;
case 11:
size += 4;
break;
case 12:
size += 8;
break;
case 13:
size += 4;
break;
case 14:
size += 4;
break;
case 15:
size += 4;
break;
case 16:
size += 8;
break;
}
}
const u32 datasize = readInt();
u32* data = new u32[datasize];
for (j=0; j<datasize; ++j)
data[j]=readInt();
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in DeclData found.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in DeclData.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
delete [] data;
return false;
}
u8* dataptr = (u8*) data;
if ((uv2pos != -1) && (uv2type == 1))
mesh.TCoords2.reallocate(mesh.Vertices.size());
for (j=0; j<mesh.Vertices.size(); ++j)
{
if ((normalpos != -1) && (normaltype == 2))
mesh.Vertices[j].Normal.set(*((core::vector3df*)(dataptr+normalpos)));
if ((uvpos != -1) && (uvtype == 1))
mesh.Vertices[j].TCoords.set(*((core::vector2df*)(dataptr+uvpos)));
if ((uv2pos != -1) && (uv2type == 1))
mesh.TCoords2.push_back(*((core::vector2df*)(dataptr+uv2pos)));
dataptr += size;
}
delete [] data;
}
else
if (objectName == "FVFData")
{
if (!readHeadOfDataObject())
{
os::Printer::log("No starting brace in FVFData found.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
const u32 dataformat = readInt();
const u32 datasize = readInt();
u32* data = new u32[datasize];
for (u32 j=0; j<datasize; ++j)
data[j]=readInt();
if (dataformat&0x102) // 2nd uv set
{
mesh.TCoords2.reallocate(mesh.Vertices.size());
u8* dataptr = (u8*) data;
const u32 size=((dataformat>>8)&0xf)*sizeof(core::vector2df);
for (u32 j=0; j<mesh.Vertices.size(); ++j)
{
mesh.TCoords2.push_back(*((core::vector2df*)(dataptr)));
dataptr += size;
}
}
delete [] data;
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in FVFData found.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in FVFData found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
}
else
if (objectName == "XSkinMeshHeader")
{
if (!parseDataObjectSkinMeshHeader(mesh))
return false;
}
else
if (objectName == "SkinWeights")
{
//mesh.SkinWeights.push_back(SXSkinWeight());
//if (!parseDataObjectSkinWeights(mesh.SkinWeights.getLast()))
if (!parseDataObjectSkinWeights(mesh))
return false;
}
else
{
os::Printer::log("Unknown data object in mesh in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectSkinWeights(SXMesh &mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh skin weights", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Skin Weights found in .x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
core::stringc TransformNodeName;
if (!getNextTokenAsString(TransformNodeName))
{
os::Printer::log("Unknown syntax while reading transfrom node name string in .x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
mesh.HasSkinning=true;
CSkinnedMesh::SJoint *joint=0;
u32 n;
for (n=0; n < AnimatedMesh->getAllJoints().size(); ++n)
{
if (AnimatedMesh->getAllJoints()[n]->Name==TransformNodeName)
{
joint=AnimatedMesh->getAllJoints()[n];
break;
}
}
if (!joint)
{
#ifdef _XREADER_DEBUG
os::Printer::log("creating joint for skinning ", TransformNodeName.c_str(), ELL_DEBUG);
#endif
n = AnimatedMesh->getAllJoints().size();
joint=AnimatedMesh->addJoint(0);
joint->Name=TransformNodeName;
}
// read vertex weights
const u32 nWeights = readInt();
// read vertex indices
u32 i;
const u32 jointStart = joint->Weights.size();
joint->Weights.reallocate(jointStart+nWeights);
mesh.WeightJoint.reallocate( mesh.WeightJoint.size() + nWeights );
mesh.WeightNum.reallocate( mesh.WeightNum.size() + nWeights );
for (i=0; i<nWeights; ++i)
{
mesh.WeightJoint.push_back(n);
mesh.WeightNum.push_back(joint->Weights.size());
CSkinnedMesh::SWeight *weight=AnimatedMesh->addWeight(joint);
weight->buffer_id=0;
weight->vertex_id=readInt();
}
// read vertex weights
for (i=jointStart; i<jointStart+nWeights; ++i)
joint->Weights[i].strength = readFloat();
// read matrix offset
// transforms the mesh vertices to the space of the bone
// When concatenated to the bone's transform, this provides the
// world space coordinates of the mesh as affected by the bone
core::matrix4& MatrixOffset = joint->GlobalInversedMatrix;
readMatrix(MatrixOffset);
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Skin Weights found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Skin Weights found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectSkinMeshHeader(SXMesh& mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading skin mesh header", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Skin Mesh header found in .x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
mesh.MaxSkinWeightsPerVertex = readInt();
mesh.MaxSkinWeightsPerFace = readInt();
mesh.BoneCount = readInt();
if (!BinaryFormat)
getNextToken(); // skip semicolon
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in skin mesh header in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMeshNormals(SXMesh &mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading mesh normals", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Mesh Normals found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read count
const u32 nNormals = readInt();
core::array<core::vector3df> normals;
normals.set_used(nNormals);
// read normals
for (u32 i=0; i<nNormals; ++i)
readVector3(normals[i]);
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Normals Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
core::array<u32> normalIndices;
normalIndices.set_used(mesh.Indices.size());
// read face normal indices
const u32 nFNormals = readInt();
u32 normalidx = 0;
core::array<u32> polygonfaces;
for (u32 k=0; k<nFNormals; ++k)
{
const u32 fcnt = readInt();
u32 triangles = fcnt - 2;
u32 indexcount = triangles * 3;
if (indexcount != mesh.IndexCountPerFace[k])
{
os::Printer::log("Not matching normal and face index count found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
if (indexcount == 3)
{
// default, only one triangle in this face
for (u32 h=0; h<3; ++h)
{
const u32 normalnum = readInt();
mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[normalnum]);
}
}
else
{
polygonfaces.set_used(fcnt);
// multiple triangles in this face
for (u32 h=0; h<fcnt; ++h)
polygonfaces[h] = readInt();
for (u32 jk=0; jk<triangles; ++jk)
{
mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[0]]);
mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[jk+1]]);
mesh.Vertices[mesh.Indices[normalidx++]].Normal.set(normals[polygonfaces[jk+2]]);
}
}
}
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Face Normals Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Mesh Normals found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMeshTextureCoords(SXMesh &mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading mesh texture coordinates", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Mesh Texture Coordinates found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
const u32 nCoords = readInt();
for (u32 i=0; i<nCoords; ++i)
readVector2(mesh.Vertices[i].TCoords);
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Texture Coordinates Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Mesh Texture Coordinates Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMeshVertexColors(SXMesh &mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading mesh vertex colors", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace for Mesh Vertex Colors found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
mesh.HasVertexColors=true;
const u32 nColors = readInt();
for (u32 i=0; i<nColors; ++i)
{
const u32 Index=readInt();
if (Index>=mesh.Vertices.size())
{
os::Printer::log("index value in parseDataObjectMeshVertexColors out of bounds", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
readRGBA(mesh.Vertices[Index].Color);
checkForOneFollowingSemicolons();
}
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon in Mesh Vertex Colors Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Mesh Texture Coordinates Array found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMeshMaterialList(SXMesh &mesh)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh material list", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Mesh Material List found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read material count
mesh.Materials.reallocate(readInt());
// read non triangulated face material index count
const u32 nFaceIndices = readInt();
// There seems to be a compact representation of "all faces the same material"
// being represented as 1;1;0;; which means 1 material, 1 face with first material
// all the other faces have to obey then, so check is disabled
//if (nFaceIndices != mesh.IndexCountPerFace.size())
// os::Printer::log("Index count per face not equal to face material index count in x file.", ELL_WARNING);
// read non triangulated face indices and create triangulated ones
mesh.FaceMaterialIndices.set_used( mesh.Indices.size() / 3);
u32 triangulatedindex = 0;
u32 ind = 0;
for (u32 tfi=0; tfi<mesh.IndexCountPerFace.size(); ++tfi)
{
if (tfi<nFaceIndices)
ind = readInt();
const u32 fc = mesh.IndexCountPerFace[tfi]/3;
for (u32 k=0; k<fc; ++k)
mesh.FaceMaterialIndices[triangulatedindex++] = ind;
}
// in version 03.02, the face indices end with two semicolons.
// commented out version check, as version 03.03 exported from blender also has 2 semicolons
if (!BinaryFormat) // && MajorVersion == 3 && MinorVersion <= 2)
{
if (P[0] == ';')
++P;
}
// read following data objects
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Mesh Material list in .x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // material list finished
}
else
if (objectName == "{")
{
// template materials now available thanks to joeWright
objectName = getNextToken();
for (u32 i=0; i<TemplateMaterials.size(); ++i)
if (TemplateMaterials[i].Name == objectName)
mesh.Materials.push_back(TemplateMaterials[i].Material);
getNextToken(); // skip }
}
else
if (objectName == "Material")
{
mesh.Materials.push_back(video::SMaterial());
if (!parseDataObjectMaterial(mesh.Materials.getLast()))
return false;
}
else
if (objectName == ";")
{
// ignore
}
else
{
os::Printer::log("Unknown data object in material list in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectMaterial(video::SMaterial& material)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading mesh material", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Mesh Material found in .x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read RGBA
readRGBA(material.DiffuseColor); checkForOneFollowingSemicolons();
// read power
material.Shininess = readFloat();
// read specular
readRGB(material.SpecularColor); checkForOneFollowingSemicolons();
// read emissive
readRGB(material.EmissiveColor); checkForOneFollowingSemicolons();
// read other data objects
int textureLayer=0;
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Mesh Material in .x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // material finished
}
else
if (objectName.equals_ignore_case("TextureFilename"))
{
// some exporters write "TextureFileName" instead.
core::stringc TextureFileName;
if (!parseDataObjectTextureFilename(TextureFileName))
return false;
// original name
if (FileSystem->existFile(TextureFileName))
material.setTexture(textureLayer, SceneManager->getVideoDriver()->getTexture(TextureFileName));
// mesh path
else
{
TextureFileName=FilePath + FileSystem->getFileBasename(TextureFileName);
if (FileSystem->existFile(TextureFileName))
material.setTexture(textureLayer, SceneManager->getVideoDriver()->getTexture(TextureFileName));
// working directory
else
material.setTexture(textureLayer, SceneManager->getVideoDriver()->getTexture(FileSystem->getFileBasename(TextureFileName)));
}
++textureLayer;
if (textureLayer==2)
material.MaterialType=video::EMT_LIGHTMAP;
}
else
if (objectName.equals_ignore_case("NormalmapFilename"))
{
// some exporters write "NormalmapFileName" instead.
core::stringc TextureFileName;
if (!parseDataObjectTextureFilename(TextureFileName))
return false;
// original name
if (FileSystem->existFile(TextureFileName))
material.setTexture(1, SceneManager->getVideoDriver()->getTexture(TextureFileName));
// mesh path
else
{
TextureFileName=FilePath + FileSystem->getFileBasename(TextureFileName);
if (FileSystem->existFile(TextureFileName))
material.setTexture(1, SceneManager->getVideoDriver()->getTexture(TextureFileName));
// working directory
else
material.setTexture(1, SceneManager->getVideoDriver()->getTexture(FileSystem->getFileBasename(TextureFileName)));
}
if (textureLayer==1)
++textureLayer;
}
else
{
os::Printer::log("Unknown data object in material in .x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectAnimationSet()
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: Reading animation set", ELL_DEBUG);
#endif
core::stringc AnimationName;
if (!readHeadOfDataObject(&AnimationName))
{
os::Printer::log("No opening brace in Animation Set found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
os::Printer::log("Reading animationset ", AnimationName, ELL_DEBUG);
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Animation set in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // animation set finished
}
else
if (objectName == "Animation")
{
if (!parseDataObjectAnimation())
return false;
}
else
{
os::Printer::log("Unknown data object in animation set in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
return true;
}
bool CXMeshFileLoader::parseDataObjectAnimation()
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading animation", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Animation found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
//anim.closed = true;
//anim.linearPositionQuality = true;
CSkinnedMesh::SJoint animationDump;
core::stringc FrameName;
while(true)
{
core::stringc objectName = getNextToken();
if (objectName.size() == 0)
{
os::Printer::log("Unexpected ending found in Animation in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
else
if (objectName == "}")
{
break; // animation finished
}
else
if (objectName == "AnimationKey")
{
if (!parseDataObjectAnimationKey(&animationDump))
return false;
}
else
if (objectName == "AnimationOptions")
{
//TODO: parse options.
if (!parseUnknownDataObject())
return false;
}
else
if (objectName == "{")
{
// read frame name
FrameName = getNextToken();
if (!checkForClosingBrace())
{
os::Printer::log("Unexpected ending found in Animation in x file.", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
}
else
{
os::Printer::log("Unknown data object in animation in x file", objectName.c_str(), ELL_WARNING);
if (!parseUnknownDataObject())
return false;
}
}
if (FrameName.size() != 0)
{
#ifdef _XREADER_DEBUG
os::Printer::log("frame name", FrameName.c_str(), ELL_DEBUG);
#endif
CSkinnedMesh::SJoint *joint=0;
u32 n;
for (n=0; n < AnimatedMesh->getAllJoints().size(); ++n)
{
if (AnimatedMesh->getAllJoints()[n]->Name==FrameName)
{
joint=AnimatedMesh->getAllJoints()[n];
break;
}
}
if (!joint)
{
#ifdef _XREADER_DEBUG
os::Printer::log("creating joint for animation ", FrameName.c_str(), ELL_DEBUG);
#endif
joint=AnimatedMesh->addJoint(0);
joint->Name=FrameName;
}
joint->PositionKeys.reallocate(joint->PositionKeys.size()+animationDump.PositionKeys.size());
for (n=0; n<animationDump.PositionKeys.size(); ++n)
{
joint->PositionKeys.push_back(animationDump.PositionKeys[n]);
}
joint->ScaleKeys.reallocate(joint->ScaleKeys.size()+animationDump.ScaleKeys.size());
for (n=0; n<animationDump.ScaleKeys.size(); ++n)
{
joint->ScaleKeys.push_back(animationDump.ScaleKeys[n]);
}
joint->RotationKeys.reallocate(joint->RotationKeys.size()+animationDump.RotationKeys.size());
for (n=0; n<animationDump.RotationKeys.size(); ++n)
{
joint->RotationKeys.push_back(animationDump.RotationKeys[n]);
}
}
else
os::Printer::log("joint name was never given", ELL_WARNING);
return true;
}
bool CXMeshFileLoader::parseDataObjectAnimationKey(ISkinnedMesh::SJoint *joint)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading animation key", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Animation Key found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read key type
const u32 keyType = readInt();
if (keyType > 4)
{
os::Printer::log("Unknown key type found in Animation Key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read number of keys
const u32 numberOfKeys = readInt();
// eat the semicolon after the "0". if there are keys present, readInt()
// does this for us. If there aren't, we need to do it explicitly
if (numberOfKeys == 0)
checkForOneFollowingSemicolons();
for (u32 i=0; i<numberOfKeys; ++i)
{
// read time
const f32 time = (f32)readInt();
// read keys
switch(keyType)
{
case 0: //rotation
{
//read quaternions
// read count
if (readInt() != 4)
{
os::Printer::log("Expected 4 numbers in animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
f32 W = -readFloat();
f32 X = -readFloat();
f32 Y = -readFloat();
f32 Z = -readFloat();
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon after quaternion animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
ISkinnedMesh::SRotationKey *key=AnimatedMesh->addRotationKey(joint);
key->frame=time;
key->rotation.set(X,Y,Z,W);
key->rotation.normalize();
}
break;
case 1: //scale
case 2: //position
{
// read vectors
// read count
if (readInt() != 3)
{
os::Printer::log("Expected 3 numbers in animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
core::vector3df vector;
readVector3(vector);
if (!checkForTwoFollowingSemicolons())
{
os::Printer::log("No finishing semicolon after vector animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
if (keyType==2)
{
ISkinnedMesh::SPositionKey *key=AnimatedMesh->addPositionKey(joint);
key->frame=time;
key->position=vector;
}
else
{
ISkinnedMesh::SScaleKey *key=AnimatedMesh->addScaleKey(joint);
key->frame=time;
key->scale=vector;
}
}
break;
case 3:
case 4:
{
// read matrix
// read count
if (readInt() != 16)
{
os::Printer::log("Expected 16 numbers in animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
// read matrix
core::matrix4 mat(core::matrix4::EM4CONST_NOTHING);
readMatrix(mat);
//mat=joint->LocalMatrix*mat;
if (!checkForOneFollowingSemicolons())
{
os::Printer::log("No finishing semicolon after matrix animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
}
//core::vector3df rotation = mat.getRotationDegrees();
ISkinnedMesh::SRotationKey *keyR=AnimatedMesh->addRotationKey(joint);
keyR->frame=time;
// IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched from mat to mat.getTransposed() for downward compatibility.
// Not tested so far if this was correct or wrong before quaternion fix!
keyR->rotation= core::quaternion(mat.getTransposed());
ISkinnedMesh::SPositionKey *keyP=AnimatedMesh->addPositionKey(joint);
keyP->frame=time;
keyP->position=mat.getTranslation();
/*
core::vector3df scale=mat.getScale();
if (scale.X==0)
scale.X=1;
if (scale.Y==0)
scale.Y=1;
if (scale.Z==0)
scale.Z=1;
ISkinnedMesh::SScaleKey *keyS=AnimatedMesh->addScaleKey(joint);
keyS->frame=time;
keyS->scale=scale;
*/
}
break;
} // end switch
}
if (!checkForOneFollowingSemicolons())
--P;
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in animation key in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseDataObjectTextureFilename(core::stringc& texturename)
{
#ifdef _XREADER_DEBUG
os::Printer::log("CXFileReader: reading texture filename", ELL_DEBUG);
#endif
if (!readHeadOfDataObject())
{
os::Printer::log("No opening brace in Texture filename found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
if (!getNextTokenAsString(texturename))
{
os::Printer::log("Unknown syntax while reading texture filename string in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
if (!checkForClosingBrace())
{
os::Printer::log("No closing brace in Texture filename found in x file", ELL_WARNING);
os::Printer::log("Line", core::stringc(Line).c_str(), ELL_WARNING);
return false;
}
return true;
}
bool CXMeshFileLoader::parseUnknownDataObject()
{
// find opening delimiter
while(true)
{
core::stringc t = getNextToken();
if (t.size() == 0)
return false;
if (t == "{")
break;
}
u32 counter = 1;
// parse until closing delimiter
while(counter)
{
core::stringc t = getNextToken();
if (t.size() == 0)
return false;
if (t == "{")
++counter;
else
if (t == "}")
--counter;
}
return true;
}
//! checks for closing curly brace, returns false if not there
bool CXMeshFileLoader::checkForClosingBrace()
{
return (getNextToken() == "}");
}
//! checks for one following semicolon, returns false if not there
bool CXMeshFileLoader::checkForOneFollowingSemicolons()
{
if (BinaryFormat)
return true;
if (getNextToken() == ";")
return true;
else
{
--P;
return false;
}
}
//! checks for two following semicolons, returns false if they are not there
bool CXMeshFileLoader::checkForTwoFollowingSemicolons()
{
if (BinaryFormat)
return true;
for (u32 k=0; k<2; ++k)
{
if (getNextToken() != ";")
{
--P;
return false;
}
}
return true;
}
//! reads header of dataobject including the opening brace.
//! returns false if error happened, and writes name of object
//! if there is one
bool CXMeshFileLoader::readHeadOfDataObject(core::stringc* outname)
{
core::stringc nameOrBrace = getNextToken();
if (nameOrBrace != "{")
{
if (outname)
(*outname) = nameOrBrace;
if (getNextToken() != "{")
return false;
}
return true;
}
//! returns next parseable token. Returns empty string if no token there
core::stringc CXMeshFileLoader::getNextToken()
{
core::stringc s;
// process binary-formatted file
if (BinaryFormat)
{
// in binary mode it will only return NAME and STRING token
// and (correctly) skip over other tokens.
s16 tok = readBinWord();
u32 len;
// standalone tokens
switch (tok) {
case 1:
// name token
len = readBinDWord();
s = core::stringc(P, len);
P += len;
return s;
case 2:
// string token
len = readBinDWord();
s = core::stringc(P, len);
P += (len + 2);
return s;
case 3:
// integer token
P += 4;
return "<integer>";
case 5:
// GUID token
P += 16;
return "<guid>";
case 6:
len = readBinDWord();
P += (len * 4);
return "<int_list>";
case 7:
len = readBinDWord();
P += (len * FloatSize);
return "<flt_list>";
case 0x0a:
return "{";
case 0x0b:
return "}";
case 0x0c:
return "(";
case 0x0d:
return ")";
case 0x0e:
return "[";
case 0x0f:
return "]";
case 0x10:
return "<";
case 0x11:
return ">";
case 0x12:
return ".";
case 0x13:
return ",";
case 0x14:
return ";";
case 0x1f:
return "template";
case 0x28:
return "WORD";
case 0x29:
return "DWORD";
case 0x2a:
return "FLOAT";
case 0x2b:
return "DOUBLE";
case 0x2c:
return "CHAR";
case 0x2d:
return "UCHAR";
case 0x2e:
return "SWORD";
case 0x2f:
return "SDWORD";
case 0x30:
return "void";
case 0x31:
return "string";
case 0x32:
return "unicode";
case 0x33:
return "cstring";
case 0x34:
return "array";
}
}
// process text-formatted file
else
{
findNextNoneWhiteSpace();
if (P >= End)
return s;
while((P < End) && !core::isspace(P[0]))
{
// either keep token delimiters when already holding a token, or return if first valid char
if (P[0]==';' || P[0]=='}' || P[0]=='{' || P[0]==',')
{
if (!s.size())
{
s.append(P[0]);
++P;
}
break; // stop for delimiter
}
s.append(P[0]);
++P;
}
}
return s;
}
//! places pointer to next begin of a token, which must be a number,
// and ignores comments
void CXMeshFileLoader::findNextNoneWhiteSpaceNumber()
{
if (BinaryFormat)
return;
while((P < End) && (P[0] != '-') && (P[0] != '.') &&
!( core::isdigit(P[0])))
{
// check if this is a comment
if ((P[0] == '/' && P[1] == '/') || P[0] == '#')
readUntilEndOfLine();
else
++P;
}
}
// places pointer to next begin of a token, and ignores comments
void CXMeshFileLoader::findNextNoneWhiteSpace()
{
if (BinaryFormat)
return;
while(true)
{
while((P < End) && core::isspace(P[0]))
{
if (*P=='\n')
++Line;
++P;
}
if (P >= End)
return;
// check if this is a comment
if ((P[0] == '/' && P[1] == '/') ||
P[0] == '#')
readUntilEndOfLine();
else
break;
}
}
//! reads a x file style string
bool CXMeshFileLoader::getNextTokenAsString(core::stringc& out)
{
if (BinaryFormat)
{
out=getNextToken();
return true;
}
findNextNoneWhiteSpace();
if (P >= End)
return false;
if (P[0] != '"')
return false;
++P;
while(P < End && P[0]!='"')
{
out.append(P[0]);
++P;
}
if ( P[1] != ';' || P[0] != '"')
return false;
P+=2;
return true;
}
void CXMeshFileLoader::readUntilEndOfLine()
{
if (BinaryFormat)
return;
while(P < End)
{
if (P[0] == '\n' || P[0] == '\r')
{
++P;
++Line;
return;
}
++P;
}
}
u16 CXMeshFileLoader::readBinWord()
{
if (P>=End)
return 0;
#ifdef __BIG_ENDIAN__
const u16 tmp = os::Byteswap::byteswap(*(u16 *)P);
#else
const u16 tmp = *(u16 *)P;
#endif
P += 2;
return tmp;
}
u32 CXMeshFileLoader::readBinDWord()
{
if (P>=End)
return 0;
#ifdef __BIG_ENDIAN__
const u32 tmp = os::Byteswap::byteswap(*(u32 *)P);
#else
const u32 tmp = *(u32 *)P;
#endif
P += 4;
return tmp;
}
u32 CXMeshFileLoader::readInt()
{
if (BinaryFormat)
{
if (!BinaryNumCount)
{
const u16 tmp = readBinWord(); // 0x06 or 0x03
if (tmp == 0x06)
BinaryNumCount = readBinDWord();
else
BinaryNumCount = 1; // single int
}
--BinaryNumCount;
return readBinDWord();
}
else
{
findNextNoneWhiteSpaceNumber();
return core::strtoul10(P, &P);
}
}
f32 CXMeshFileLoader::readFloat()
{
if (BinaryFormat)
{
if (!BinaryNumCount)
{
const u16 tmp = readBinWord(); // 0x07 or 0x42
if (tmp == 0x07)
BinaryNumCount = readBinDWord();
else
BinaryNumCount = 1; // single int
}
--BinaryNumCount;
if (FloatSize == 8)
{
#ifdef __BIG_ENDIAN__
//TODO: Check if data is properly converted here
f32 ctmp[2];
ctmp[1] = os::Byteswap::byteswap(*(f32*)P);
ctmp[0] = os::Byteswap::byteswap(*(f32*)P+4);
const f32 tmp = (f32)(*(f64*)(void*)ctmp);
#else
const f32 tmp = (f32)(*(f64 *)P);
#endif
P += 8;
return tmp;
}
else
{
#ifdef __BIG_ENDIAN__
const f32 tmp = os::Byteswap::byteswap(*(f32 *)P);
#else
const f32 tmp = *(f32 *)P;
#endif
P += 4;
return tmp;
}
}
findNextNoneWhiteSpaceNumber();
f32 ftmp;
P = core::fast_atof_move(P, ftmp);
return ftmp;
}
// read 2-dimensional vector. Stops at semicolon after second value for text file format
bool CXMeshFileLoader::readVector2(core::vector2df& vec)
{
vec.X = readFloat();
vec.Y = readFloat();
return true;
}
// read 3-dimensional vector. Stops at semicolon after third value for text file format
bool CXMeshFileLoader::readVector3(core::vector3df& vec)
{
vec.X = readFloat();
vec.Y = readFloat();
vec.Z = readFloat();
return true;
}
// read color without alpha value. Stops after second semicolon after blue value
bool CXMeshFileLoader::readRGB(video::SColor& color)
{
video::SColorf tmpColor;
tmpColor.r = readFloat();
tmpColor.g = readFloat();
tmpColor.b = readFloat();
color = tmpColor.toSColor();
return checkForOneFollowingSemicolons();
}
// read color with alpha value. Stops after second semicolon after blue value
bool CXMeshFileLoader::readRGBA(video::SColor& color)
{
video::SColorf tmpColor;
tmpColor.r = readFloat();
tmpColor.g = readFloat();
tmpColor.b = readFloat();
tmpColor.a = readFloat();
color = tmpColor.toSColor();
return checkForOneFollowingSemicolons();
}
// read matrix from list of floats
bool CXMeshFileLoader::readMatrix(core::matrix4& mat)
{
for (u32 i=0; i<16; ++i)
mat[i] = readFloat();
return checkForOneFollowingSemicolons();
}
} // end namespace scene
} // end namespace irr
#endif // _IRR_COMPILE_WITH_X_LOADER_
|