Spaces:
Running
Running
File size: 52,076 Bytes
6cd9596 |
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 |
/**
* @author fernandojsg / http://fernandojsg.com
* @author Don McCurdy / https://www.donmccurdy.com
* @author Takahiro / https://github.com/takahirox
*/
import {
BufferAttribute,
BufferGeometry,
ClampToEdgeWrapping,
DoubleSide,
InterpolateDiscrete,
InterpolateLinear,
LinearFilter,
LinearMipMapLinearFilter,
LinearMipMapNearestFilter,
Math as _Math,
MirroredRepeatWrapping,
NearestFilter,
NearestMipMapLinearFilter,
NearestMipMapNearestFilter,
PropertyBinding,
RGBAFormat,
RepeatWrapping,
Scene,
TriangleFanDrawMode,
TriangleStripDrawMode,
Vector3
} from "../../../build/three.module.js";
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
var WEBGL_CONSTANTS = {
POINTS: 0x0000,
LINES: 0x0001,
LINE_LOOP: 0x0002,
LINE_STRIP: 0x0003,
TRIANGLES: 0x0004,
TRIANGLE_STRIP: 0x0005,
TRIANGLE_FAN: 0x0006,
UNSIGNED_BYTE: 0x1401,
UNSIGNED_SHORT: 0x1403,
FLOAT: 0x1406,
UNSIGNED_INT: 0x1405,
ARRAY_BUFFER: 0x8892,
ELEMENT_ARRAY_BUFFER: 0x8893,
NEAREST: 0x2600,
LINEAR: 0x2601,
NEAREST_MIPMAP_NEAREST: 0x2700,
LINEAR_MIPMAP_NEAREST: 0x2701,
NEAREST_MIPMAP_LINEAR: 0x2702,
LINEAR_MIPMAP_LINEAR: 0x2703,
CLAMP_TO_EDGE: 33071,
MIRRORED_REPEAT: 33648,
REPEAT: 10497
};
var THREE_TO_WEBGL = {};
THREE_TO_WEBGL[ NearestFilter ] = WEBGL_CONSTANTS.NEAREST;
THREE_TO_WEBGL[ NearestMipMapNearestFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_NEAREST;
THREE_TO_WEBGL[ NearestMipMapLinearFilter ] = WEBGL_CONSTANTS.NEAREST_MIPMAP_LINEAR;
THREE_TO_WEBGL[ LinearFilter ] = WEBGL_CONSTANTS.LINEAR;
THREE_TO_WEBGL[ LinearMipMapNearestFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_NEAREST;
THREE_TO_WEBGL[ LinearMipMapLinearFilter ] = WEBGL_CONSTANTS.LINEAR_MIPMAP_LINEAR;
THREE_TO_WEBGL[ ClampToEdgeWrapping ] = WEBGL_CONSTANTS.CLAMP_TO_EDGE;
THREE_TO_WEBGL[ RepeatWrapping ] = WEBGL_CONSTANTS.REPEAT;
THREE_TO_WEBGL[ MirroredRepeatWrapping ] = WEBGL_CONSTANTS.MIRRORED_REPEAT;
var PATH_PROPERTIES = {
scale: 'scale',
position: 'translation',
quaternion: 'rotation',
morphTargetInfluences: 'weights'
};
//------------------------------------------------------------------------------
// GLTF Exporter
//------------------------------------------------------------------------------
var GLTFExporter = function () {};
GLTFExporter.prototype = {
constructor: GLTFExporter,
/**
* Parse scenes and generate GLTF output
* @param {Scene or [THREE.Scenes]} input Scene or Array of THREE.Scenes
* @param {Function} onDone Callback on completed
* @param {Object} options options
*/
parse: function ( input, onDone, options ) {
var DEFAULT_OPTIONS = {
binary: false,
trs: false,
onlyVisible: true,
truncateDrawRange: true,
embedImages: true,
animations: [],
forceIndices: false,
forcePowerOfTwoTextures: false,
includeCustomExtensions: false
};
options = Object.assign( {}, DEFAULT_OPTIONS, options );
if ( options.animations.length > 0 ) {
// Only TRS properties, and not matrices, may be targeted by animation.
options.trs = true;
}
var outputJSON = {
asset: {
version: "2.0",
generator: "GLTFExporter"
}
};
var byteOffset = 0;
var buffers = [];
var pending = [];
var nodeMap = new Map();
var skins = [];
var extensionsUsed = {};
var cachedData = {
meshes: new Map(),
attributes: new Map(),
attributesNormalized: new Map(),
materials: new Map(),
textures: new Map(),
images: new Map()
};
var cachedCanvas;
/**
* Compare two arrays
*/
/**
* Compare two arrays
* @param {Array} array1 Array 1 to compare
* @param {Array} array2 Array 2 to compare
* @return {Boolean} Returns true if both arrays are equal
*/
function equalArray( array1, array2 ) {
return ( array1.length === array2.length ) && array1.every( function ( element, index ) {
return element === array2[ index ];
} );
}
/**
* Converts a string to an ArrayBuffer.
* @param {string} text
* @return {ArrayBuffer}
*/
function stringToArrayBuffer( text ) {
if ( window.TextEncoder !== undefined ) {
return new TextEncoder().encode( text ).buffer;
}
var array = new Uint8Array( new ArrayBuffer( text.length ) );
for ( var i = 0, il = text.length; i < il; i ++ ) {
var value = text.charCodeAt( i );
// Replacing multi-byte character with space(0x20).
array[ i ] = value > 0xFF ? 0x20 : value;
}
return array.buffer;
}
/**
* Get the min and max vectors from the given attribute
* @param {BufferAttribute} attribute Attribute to find the min/max in range from start to start + count
* @param {Integer} start
* @param {Integer} count
* @return {Object} Object containing the `min` and `max` values (As an array of attribute.itemSize components)
*/
function getMinMax( attribute, start, count ) {
var output = {
min: new Array( attribute.itemSize ).fill( Number.POSITIVE_INFINITY ),
max: new Array( attribute.itemSize ).fill( Number.NEGATIVE_INFINITY )
};
for ( var i = start; i < start + count; i ++ ) {
for ( var a = 0; a < attribute.itemSize; a ++ ) {
var value = attribute.array[ i * attribute.itemSize + a ];
output.min[ a ] = Math.min( output.min[ a ], value );
output.max[ a ] = Math.max( output.max[ a ], value );
}
}
return output;
}
/**
* Checks if image size is POT.
*
* @param {Image} image The image to be checked.
* @returns {Boolean} Returns true if image size is POT.
*
*/
function isPowerOfTwo( image ) {
return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
}
/**
* Checks if normal attribute values are normalized.
*
* @param {BufferAttribute} normal
* @returns {Boolean}
*
*/
function isNormalizedNormalAttribute( normal ) {
if ( cachedData.attributesNormalized.has( normal ) ) {
return false;
}
var v = new Vector3();
for ( var i = 0, il = normal.count; i < il; i ++ ) {
// 0.0005 is from glTF-validator
if ( Math.abs( v.fromArray( normal.array, i * 3 ).length() - 1.0 ) > 0.0005 ) return false;
}
return true;
}
/**
* Creates normalized normal buffer attribute.
*
* @param {BufferAttribute} normal
* @returns {BufferAttribute}
*
*/
function createNormalizedNormalAttribute( normal ) {
if ( cachedData.attributesNormalized.has( normal ) ) {
return cachedData.attributesNormalized.get( normal );
}
var attribute = normal.clone();
var v = new Vector3();
for ( var i = 0, il = attribute.count; i < il; i ++ ) {
v.fromArray( attribute.array, i * 3 );
if ( v.x === 0 && v.y === 0 && v.z === 0 ) {
// if values can't be normalized set (1, 0, 0)
v.setX( 1.0 );
} else {
v.normalize();
}
v.toArray( attribute.array, i * 3 );
}
cachedData.attributesNormalized.set( normal, attribute );
return attribute;
}
/**
* Get the required size + padding for a buffer, rounded to the next 4-byte boundary.
* https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
*
* @param {Integer} bufferSize The size the original buffer.
* @returns {Integer} new buffer size with required padding.
*
*/
function getPaddedBufferSize( bufferSize ) {
return Math.ceil( bufferSize / 4 ) * 4;
}
/**
* Returns a buffer aligned to 4-byte boundary.
*
* @param {ArrayBuffer} arrayBuffer Buffer to pad
* @param {Integer} paddingByte (Optional)
* @returns {ArrayBuffer} The same buffer if it's already aligned to 4-byte boundary or a new buffer
*/
function getPaddedArrayBuffer( arrayBuffer, paddingByte ) {
paddingByte = paddingByte || 0;
var paddedLength = getPaddedBufferSize( arrayBuffer.byteLength );
if ( paddedLength !== arrayBuffer.byteLength ) {
var array = new Uint8Array( paddedLength );
array.set( new Uint8Array( arrayBuffer ) );
if ( paddingByte !== 0 ) {
for ( var i = arrayBuffer.byteLength; i < paddedLength; i ++ ) {
array[ i ] = paddingByte;
}
}
return array.buffer;
}
return arrayBuffer;
}
/**
* Serializes a userData.
*
* @param {THREE.Object3D|THREE.Material} object
* @param {Object} gltfProperty
*/
function serializeUserData( object, gltfProperty ) {
if ( Object.keys( object.userData ).length === 0 ) {
return;
}
try {
var json = JSON.parse( JSON.stringify( object.userData ) );
if ( options.includeCustomExtensions && json.gltfExtensions ) {
if ( gltfProperty.extensions === undefined ) {
gltfProperty.extensions = {};
}
for ( var extensionName in json.gltfExtensions ) {
gltfProperty.extensions[ extensionName ] = json.gltfExtensions[ extensionName ];
extensionsUsed[ extensionName ] = true;
}
delete json.gltfExtensions;
}
if ( Object.keys( json ).length > 0 ) {
gltfProperty.extras = json;
}
} catch ( error ) {
console.warn( 'THREE.GLTFExporter: userData of \'' + object.name + '\' ' +
'won\'t be serialized because of JSON.stringify error - ' + error.message );
}
}
/**
* Applies a texture transform, if present, to the map definition. Requires
* the KHR_texture_transform extension.
*/
function applyTextureTransform( mapDef, texture ) {
var didTransform = false;
var transformDef = {};
if ( texture.offset.x !== 0 || texture.offset.y !== 0 ) {
transformDef.offset = texture.offset.toArray();
didTransform = true;
}
if ( texture.rotation !== 0 ) {
transformDef.rotation = texture.rotation;
didTransform = true;
}
if ( texture.repeat.x !== 1 || texture.repeat.y !== 1 ) {
transformDef.scale = texture.repeat.toArray();
didTransform = true;
}
if ( didTransform ) {
mapDef.extensions = mapDef.extensions || {};
mapDef.extensions[ 'KHR_texture_transform' ] = transformDef;
extensionsUsed[ 'KHR_texture_transform' ] = true;
}
}
/**
* Process a buffer to append to the default one.
* @param {ArrayBuffer} buffer
* @return {Integer}
*/
function processBuffer( buffer ) {
if ( ! outputJSON.buffers ) {
outputJSON.buffers = [ { byteLength: 0 } ];
}
// All buffers are merged before export.
buffers.push( buffer );
return 0;
}
/**
* Process and generate a BufferView
* @param {BufferAttribute} attribute
* @param {number} componentType
* @param {number} start
* @param {number} count
* @param {number} target (Optional) Target usage of the BufferView
* @return {Object}
*/
function processBufferView( attribute, componentType, start, count, target ) {
if ( ! outputJSON.bufferViews ) {
outputJSON.bufferViews = [];
}
// Create a new dataview and dump the attribute's array into it
var componentSize;
if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
componentSize = 1;
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
componentSize = 2;
} else {
componentSize = 4;
}
var byteLength = getPaddedBufferSize( count * attribute.itemSize * componentSize );
var dataView = new DataView( new ArrayBuffer( byteLength ) );
var offset = 0;
for ( var i = start; i < start + count; i ++ ) {
for ( var a = 0; a < attribute.itemSize; a ++ ) {
// @TODO Fails on InterleavedBufferAttribute, and could probably be
// optimized for normal BufferAttribute.
var value = attribute.array[ i * attribute.itemSize + a ];
if ( componentType === WEBGL_CONSTANTS.FLOAT ) {
dataView.setFloat32( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_INT ) {
dataView.setUint32( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_SHORT ) {
dataView.setUint16( offset, value, true );
} else if ( componentType === WEBGL_CONSTANTS.UNSIGNED_BYTE ) {
dataView.setUint8( offset, value );
}
offset += componentSize;
}
}
var gltfBufferView = {
buffer: processBuffer( dataView.buffer ),
byteOffset: byteOffset,
byteLength: byteLength
};
if ( target !== undefined ) gltfBufferView.target = target;
if ( target === WEBGL_CONSTANTS.ARRAY_BUFFER ) {
// Only define byteStride for vertex attributes.
gltfBufferView.byteStride = attribute.itemSize * componentSize;
}
byteOffset += byteLength;
outputJSON.bufferViews.push( gltfBufferView );
// @TODO Merge bufferViews where possible.
var output = {
id: outputJSON.bufferViews.length - 1,
byteLength: 0
};
return output;
}
/**
* Process and generate a BufferView from an image Blob.
* @param {Blob} blob
* @return {Promise<Integer>}
*/
function processBufferViewImage( blob ) {
if ( ! outputJSON.bufferViews ) {
outputJSON.bufferViews = [];
}
return new Promise( function ( resolve ) {
var reader = new window.FileReader();
reader.readAsArrayBuffer( blob );
reader.onloadend = function () {
var buffer = getPaddedArrayBuffer( reader.result );
var bufferView = {
buffer: processBuffer( buffer ),
byteOffset: byteOffset,
byteLength: buffer.byteLength
};
byteOffset += buffer.byteLength;
outputJSON.bufferViews.push( bufferView );
resolve( outputJSON.bufferViews.length - 1 );
};
} );
}
/**
* Process attribute to generate an accessor
* @param {BufferAttribute} attribute Attribute to process
* @param {BufferGeometry} geometry (Optional) Geometry used for truncated draw range
* @param {Integer} start (Optional)
* @param {Integer} count (Optional)
* @return {Integer} Index of the processed accessor on the "accessors" array
*/
function processAccessor( attribute, geometry, start, count ) {
var types = {
1: 'SCALAR',
2: 'VEC2',
3: 'VEC3',
4: 'VEC4',
16: 'MAT4'
};
var componentType;
// Detect the component type of the attribute array (float, uint or ushort)
if ( attribute.array.constructor === Float32Array ) {
componentType = WEBGL_CONSTANTS.FLOAT;
} else if ( attribute.array.constructor === Uint32Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_INT;
} else if ( attribute.array.constructor === Uint16Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_SHORT;
} else if ( attribute.array.constructor === Uint8Array ) {
componentType = WEBGL_CONSTANTS.UNSIGNED_BYTE;
} else {
throw new Error( 'THREE.GLTFExporter: Unsupported bufferAttribute component type.' );
}
if ( start === undefined ) start = 0;
if ( count === undefined ) count = attribute.count;
// @TODO Indexed buffer geometry with drawRange not supported yet
if ( options.truncateDrawRange && geometry !== undefined && geometry.index === null ) {
var end = start + count;
var end2 = geometry.drawRange.count === Infinity
? attribute.count
: geometry.drawRange.start + geometry.drawRange.count;
start = Math.max( start, geometry.drawRange.start );
count = Math.min( end, end2 ) - start;
if ( count < 0 ) count = 0;
}
// Skip creating an accessor if the attribute doesn't have data to export
if ( count === 0 ) {
return null;
}
var minMax = getMinMax( attribute, start, count );
var bufferViewTarget;
// If geometry isn't provided, don't infer the target usage of the bufferView. For
// animation samplers, target must not be set.
if ( geometry !== undefined ) {
bufferViewTarget = attribute === geometry.index ? WEBGL_CONSTANTS.ELEMENT_ARRAY_BUFFER : WEBGL_CONSTANTS.ARRAY_BUFFER;
}
var bufferView = processBufferView( attribute, componentType, start, count, bufferViewTarget );
var gltfAccessor = {
bufferView: bufferView.id,
byteOffset: bufferView.byteOffset,
componentType: componentType,
count: count,
max: minMax.max,
min: minMax.min,
type: types[ attribute.itemSize ]
};
if ( ! outputJSON.accessors ) {
outputJSON.accessors = [];
}
outputJSON.accessors.push( gltfAccessor );
return outputJSON.accessors.length - 1;
}
/**
* Process image
* @param {Image} image to process
* @param {Integer} format of the image (e.g. THREE.RGBFormat, RGBAFormat etc)
* @param {Boolean} flipY before writing out the image
* @return {Integer} Index of the processed texture in the "images" array
*/
function processImage( image, format, flipY ) {
if ( ! cachedData.images.has( image ) ) {
cachedData.images.set( image, {} );
}
var cachedImages = cachedData.images.get( image );
var mimeType = format === RGBAFormat ? 'image/png' : 'image/jpeg';
var key = mimeType + ":flipY/" + flipY.toString();
if ( cachedImages[ key ] !== undefined ) {
return cachedImages[ key ];
}
if ( ! outputJSON.images ) {
outputJSON.images = [];
}
var gltfImage = { mimeType: mimeType };
if ( options.embedImages ) {
var canvas = cachedCanvas = cachedCanvas || document.createElement( 'canvas' );
canvas.width = image.width;
canvas.height = image.height;
if ( options.forcePowerOfTwoTextures && ! isPowerOfTwo( image ) ) {
console.warn( 'GLTFExporter: Resized non-power-of-two image.', image );
canvas.width = _Math.floorPowerOfTwo( canvas.width );
canvas.height = _Math.floorPowerOfTwo( canvas.height );
}
var ctx = canvas.getContext( '2d' );
if ( flipY === true ) {
ctx.translate( 0, canvas.height );
ctx.scale( 1, - 1 );
}
ctx.drawImage( image, 0, 0, canvas.width, canvas.height );
if ( options.binary === true ) {
pending.push( new Promise( function ( resolve ) {
canvas.toBlob( function ( blob ) {
processBufferViewImage( blob ).then( function ( bufferViewIndex ) {
gltfImage.bufferView = bufferViewIndex;
resolve();
} );
}, mimeType );
} ) );
} else {
gltfImage.uri = canvas.toDataURL( mimeType );
}
} else {
gltfImage.uri = image.src;
}
outputJSON.images.push( gltfImage );
var index = outputJSON.images.length - 1;
cachedImages[ key ] = index;
return index;
}
/**
* Process sampler
* @param {Texture} map Texture to process
* @return {Integer} Index of the processed texture in the "samplers" array
*/
function processSampler( map ) {
if ( ! outputJSON.samplers ) {
outputJSON.samplers = [];
}
var gltfSampler = {
magFilter: THREE_TO_WEBGL[ map.magFilter ],
minFilter: THREE_TO_WEBGL[ map.minFilter ],
wrapS: THREE_TO_WEBGL[ map.wrapS ],
wrapT: THREE_TO_WEBGL[ map.wrapT ]
};
outputJSON.samplers.push( gltfSampler );
return outputJSON.samplers.length - 1;
}
/**
* Process texture
* @param {Texture} map Map to process
* @return {Integer} Index of the processed texture in the "textures" array
*/
function processTexture( map ) {
if ( cachedData.textures.has( map ) ) {
return cachedData.textures.get( map );
}
if ( ! outputJSON.textures ) {
outputJSON.textures = [];
}
var gltfTexture = {
sampler: processSampler( map ),
source: processImage( map.image, map.format, map.flipY )
};
outputJSON.textures.push( gltfTexture );
var index = outputJSON.textures.length - 1;
cachedData.textures.set( map, index );
return index;
}
/**
* Process material
* @param {THREE.Material} material Material to process
* @return {Integer} Index of the processed material in the "materials" array
*/
function processMaterial( material ) {
if ( cachedData.materials.has( material ) ) {
return cachedData.materials.get( material );
}
if ( ! outputJSON.materials ) {
outputJSON.materials = [];
}
if ( material.isShaderMaterial ) {
console.warn( 'GLTFExporter: THREE.ShaderMaterial not supported.' );
return null;
}
// @QUESTION Should we avoid including any attribute that has the default value?
var gltfMaterial = {
pbrMetallicRoughness: {}
};
if ( material.isMeshBasicMaterial ) {
gltfMaterial.extensions = { KHR_materials_unlit: {} };
extensionsUsed[ 'KHR_materials_unlit' ] = true;
} else if ( ! material.isMeshStandardMaterial ) {
console.warn( 'GLTFExporter: Use MeshStandardMaterial or MeshBasicMaterial for best results.' );
}
// pbrMetallicRoughness.baseColorFactor
var color = material.color.toArray().concat( [ material.opacity ] );
if ( ! equalArray( color, [ 1, 1, 1, 1 ] ) ) {
gltfMaterial.pbrMetallicRoughness.baseColorFactor = color;
}
if ( material.isMeshStandardMaterial ) {
gltfMaterial.pbrMetallicRoughness.metallicFactor = material.metalness;
gltfMaterial.pbrMetallicRoughness.roughnessFactor = material.roughness;
} else if ( material.isMeshBasicMaterial ) {
gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.0;
gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.9;
} else {
gltfMaterial.pbrMetallicRoughness.metallicFactor = 0.5;
gltfMaterial.pbrMetallicRoughness.roughnessFactor = 0.5;
}
// pbrMetallicRoughness.metallicRoughnessTexture
if ( material.metalnessMap || material.roughnessMap ) {
if ( material.metalnessMap === material.roughnessMap ) {
var metalRoughMapDef = { index: processTexture( material.metalnessMap ) };
applyTextureTransform( metalRoughMapDef, material.metalnessMap );
gltfMaterial.pbrMetallicRoughness.metallicRoughnessTexture = metalRoughMapDef;
} else {
console.warn( 'THREE.GLTFExporter: Ignoring metalnessMap and roughnessMap because they are not the same Texture.' );
}
}
// pbrMetallicRoughness.baseColorTexture
if ( material.map ) {
var baseColorMapDef = { index: processTexture( material.map ) };
applyTextureTransform( baseColorMapDef, material.map );
gltfMaterial.pbrMetallicRoughness.baseColorTexture = baseColorMapDef;
}
if ( material.isMeshBasicMaterial ||
material.isLineBasicMaterial ||
material.isPointsMaterial ) {
} else {
// emissiveFactor
var emissive = material.emissive.clone().multiplyScalar( material.emissiveIntensity ).toArray();
if ( ! equalArray( emissive, [ 0, 0, 0 ] ) ) {
gltfMaterial.emissiveFactor = emissive;
}
// emissiveTexture
if ( material.emissiveMap ) {
var emissiveMapDef = { index: processTexture( material.emissiveMap ) };
applyTextureTransform( emissiveMapDef, material.emissiveMap );
gltfMaterial.emissiveTexture = emissiveMapDef;
}
}
// normalTexture
if ( material.normalMap ) {
var normalMapDef = { index: processTexture( material.normalMap ) };
if ( material.normalScale.x !== - 1 ) {
if ( material.normalScale.x !== material.normalScale.y ) {
console.warn( 'THREE.GLTFExporter: Normal scale components are different, ignoring Y and exporting X.' );
}
normalMapDef.scale = material.normalScale.x;
}
applyTextureTransform( normalMapDef, material.normalMap );
gltfMaterial.normalTexture = normalMapDef;
}
// occlusionTexture
if ( material.aoMap ) {
var occlusionMapDef = {
index: processTexture( material.aoMap ),
texCoord: 1
};
if ( material.aoMapIntensity !== 1.0 ) {
occlusionMapDef.strength = material.aoMapIntensity;
}
applyTextureTransform( occlusionMapDef, material.aoMap );
gltfMaterial.occlusionTexture = occlusionMapDef;
}
// alphaMode
if ( material.transparent || material.alphaTest > 0.0 ) {
gltfMaterial.alphaMode = material.opacity < 1.0 ? 'BLEND' : 'MASK';
// Write alphaCutoff if it's non-zero and different from the default (0.5).
if ( material.alphaTest > 0.0 && material.alphaTest !== 0.5 ) {
gltfMaterial.alphaCutoff = material.alphaTest;
}
}
// doubleSided
if ( material.side === DoubleSide ) {
gltfMaterial.doubleSided = true;
}
if ( material.name !== '' ) {
gltfMaterial.name = material.name;
}
serializeUserData( material, gltfMaterial );
outputJSON.materials.push( gltfMaterial );
var index = outputJSON.materials.length - 1;
cachedData.materials.set( material, index );
return index;
}
/**
* Process mesh
* @param {THREE.Mesh} mesh Mesh to process
* @return {Integer} Index of the processed mesh in the "meshes" array
*/
function processMesh( mesh ) {
var cacheKey = mesh.geometry.uuid + ':' + mesh.material.uuid;
if ( cachedData.meshes.has( cacheKey ) ) {
return cachedData.meshes.get( cacheKey );
}
var geometry = mesh.geometry;
var mode;
// Use the correct mode
if ( mesh.isLineSegments ) {
mode = WEBGL_CONSTANTS.LINES;
} else if ( mesh.isLineLoop ) {
mode = WEBGL_CONSTANTS.LINE_LOOP;
} else if ( mesh.isLine ) {
mode = WEBGL_CONSTANTS.LINE_STRIP;
} else if ( mesh.isPoints ) {
mode = WEBGL_CONSTANTS.POINTS;
} else {
if ( ! geometry.isBufferGeometry ) {
console.warn( 'GLTFExporter: Exporting THREE.Geometry will increase file size. Use BufferGeometry instead.' );
var geometryTemp = new BufferGeometry();
geometryTemp.fromGeometry( geometry );
geometry = geometryTemp;
}
if ( mesh.drawMode === TriangleFanDrawMode ) {
console.warn( 'GLTFExporter: TriangleFanDrawMode and wireframe incompatible.' );
mode = WEBGL_CONSTANTS.TRIANGLE_FAN;
} else if ( mesh.drawMode === TriangleStripDrawMode ) {
mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINE_STRIP : WEBGL_CONSTANTS.TRIANGLE_STRIP;
} else {
mode = mesh.material.wireframe ? WEBGL_CONSTANTS.LINES : WEBGL_CONSTANTS.TRIANGLES;
}
}
var gltfMesh = {};
var attributes = {};
var primitives = [];
var targets = [];
// Conversion between attributes names in threejs and gltf spec
var nameConversion = {
uv: 'TEXCOORD_0',
uv2: 'TEXCOORD_1',
color: 'COLOR_0',
skinWeight: 'WEIGHTS_0',
skinIndex: 'JOINTS_0'
};
var originalNormal = geometry.getAttribute( 'normal' );
if ( originalNormal !== undefined && ! isNormalizedNormalAttribute( originalNormal ) ) {
console.warn( 'THREE.GLTFExporter: Creating normalized normal attribute from the non-normalized one.' );
geometry.addAttribute( 'normal', createNormalizedNormalAttribute( originalNormal ) );
}
// @QUESTION Detect if .vertexColors = THREE.VertexColors?
// For every attribute create an accessor
var modifiedAttribute = null;
for ( var attributeName in geometry.attributes ) {
// Ignore morph target attributes, which are exported later.
if ( attributeName.substr( 0, 5 ) === 'morph' ) continue;
var attribute = geometry.attributes[ attributeName ];
attributeName = nameConversion[ attributeName ] || attributeName.toUpperCase();
// Prefix all geometry attributes except the ones specifically
// listed in the spec; non-spec attributes are considered custom.
var validVertexAttributes =
/^(POSITION|NORMAL|TANGENT|TEXCOORD_\d+|COLOR_\d+|JOINTS_\d+|WEIGHTS_\d+)$/;
if ( ! validVertexAttributes.test( attributeName ) ) {
attributeName = '_' + attributeName;
}
if ( cachedData.attributes.has( attribute ) ) {
attributes[ attributeName ] = cachedData.attributes.get( attribute );
continue;
}
// JOINTS_0 must be UNSIGNED_BYTE or UNSIGNED_SHORT.
modifiedAttribute = null;
var array = attribute.array;
if ( attributeName === 'JOINTS_0' &&
! ( array instanceof Uint16Array ) &&
! ( array instanceof Uint8Array ) ) {
console.warn( 'GLTFExporter: Attribute "skinIndex" converted to type UNSIGNED_SHORT.' );
modifiedAttribute = new BufferAttribute( new Uint16Array( array ), attribute.itemSize, attribute.normalized );
}
var accessor = processAccessor( modifiedAttribute || attribute, geometry );
if ( accessor !== null ) {
attributes[ attributeName ] = accessor;
cachedData.attributes.set( attribute, accessor );
}
}
if ( originalNormal !== undefined ) geometry.addAttribute( 'normal', originalNormal );
// Skip if no exportable attributes found
if ( Object.keys( attributes ).length === 0 ) {
return null;
}
// Morph targets
if ( mesh.morphTargetInfluences !== undefined && mesh.morphTargetInfluences.length > 0 ) {
var weights = [];
var targetNames = [];
var reverseDictionary = {};
if ( mesh.morphTargetDictionary !== undefined ) {
for ( var key in mesh.morphTargetDictionary ) {
reverseDictionary[ mesh.morphTargetDictionary[ key ] ] = key;
}
}
for ( var i = 0; i < mesh.morphTargetInfluences.length; ++ i ) {
var target = {};
var warned = false;
for ( var attributeName in geometry.morphAttributes ) {
// glTF 2.0 morph supports only POSITION/NORMAL/TANGENT.
// Three.js doesn't support TANGENT yet.
if ( attributeName !== 'position' && attributeName !== 'normal' ) {
if ( ! warned ) {
console.warn( 'GLTFExporter: Only POSITION and NORMAL morph are supported.' );
warned = true;
}
continue;
}
var attribute = geometry.morphAttributes[ attributeName ][ i ];
var gltfAttributeName = attributeName.toUpperCase();
// Three.js morph attribute has absolute values while the one of glTF has relative values.
//
// glTF 2.0 Specification:
// https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#morph-targets
var baseAttribute = geometry.attributes[ attributeName ];
if ( cachedData.attributes.has( attribute ) ) {
target[ gltfAttributeName ] = cachedData.attributes.get( attribute );
continue;
}
// Clones attribute not to override
var relativeAttribute = attribute.clone();
for ( var j = 0, jl = attribute.count; j < jl; j ++ ) {
relativeAttribute.setXYZ(
j,
attribute.getX( j ) - baseAttribute.getX( j ),
attribute.getY( j ) - baseAttribute.getY( j ),
attribute.getZ( j ) - baseAttribute.getZ( j )
);
}
target[ gltfAttributeName ] = processAccessor( relativeAttribute, geometry );
cachedData.attributes.set( baseAttribute, target[ gltfAttributeName ] );
}
targets.push( target );
weights.push( mesh.morphTargetInfluences[ i ] );
if ( mesh.morphTargetDictionary !== undefined ) targetNames.push( reverseDictionary[ i ] );
}
gltfMesh.weights = weights;
if ( targetNames.length > 0 ) {
gltfMesh.extras = {};
gltfMesh.extras.targetNames = targetNames;
}
}
var forceIndices = options.forceIndices;
var isMultiMaterial = Array.isArray( mesh.material );
if ( isMultiMaterial && geometry.groups.length === 0 ) return null;
if ( ! forceIndices && geometry.index === null && isMultiMaterial ) {
// temporal workaround.
console.warn( 'THREE.GLTFExporter: Creating index for non-indexed multi-material mesh.' );
forceIndices = true;
}
var didForceIndices = false;
if ( geometry.index === null && forceIndices ) {
var indices = [];
for ( var i = 0, il = geometry.attributes.position.count; i < il; i ++ ) {
indices[ i ] = i;
}
geometry.setIndex( indices );
didForceIndices = true;
}
var materials = isMultiMaterial ? mesh.material : [ mesh.material ];
var groups = isMultiMaterial ? geometry.groups : [ { materialIndex: 0, start: undefined, count: undefined } ];
for ( var i = 0, il = groups.length; i < il; i ++ ) {
var primitive = {
mode: mode,
attributes: attributes,
};
serializeUserData( geometry, primitive );
if ( targets.length > 0 ) primitive.targets = targets;
if ( geometry.index !== null ) {
if ( cachedData.attributes.has( geometry.index ) ) {
primitive.indices = cachedData.attributes.get( geometry.index );
} else {
primitive.indices = processAccessor( geometry.index, geometry, groups[ i ].start, groups[ i ].count );
cachedData.attributes.set( geometry.index, primitive.indices );
}
if ( primitive.indices === null ) delete primitive.indices;
}
var material = processMaterial( materials[ groups[ i ].materialIndex ] );
if ( material !== null ) {
primitive.material = material;
}
primitives.push( primitive );
}
if ( didForceIndices ) {
geometry.setIndex( null );
}
gltfMesh.primitives = primitives;
if ( ! outputJSON.meshes ) {
outputJSON.meshes = [];
}
outputJSON.meshes.push( gltfMesh );
var index = outputJSON.meshes.length - 1;
cachedData.meshes.set( cacheKey, index );
return index;
}
/**
* Process camera
* @param {THREE.Camera} camera Camera to process
* @return {Integer} Index of the processed mesh in the "camera" array
*/
function processCamera( camera ) {
if ( ! outputJSON.cameras ) {
outputJSON.cameras = [];
}
var isOrtho = camera.isOrthographicCamera;
var gltfCamera = {
type: isOrtho ? 'orthographic' : 'perspective'
};
if ( isOrtho ) {
gltfCamera.orthographic = {
xmag: camera.right * 2,
ymag: camera.top * 2,
zfar: camera.far <= 0 ? 0.001 : camera.far,
znear: camera.near < 0 ? 0 : camera.near
};
} else {
gltfCamera.perspective = {
aspectRatio: camera.aspect,
yfov: _Math.degToRad( camera.fov ),
zfar: camera.far <= 0 ? 0.001 : camera.far,
znear: camera.near < 0 ? 0 : camera.near
};
}
if ( camera.name !== '' ) {
gltfCamera.name = camera.type;
}
outputJSON.cameras.push( gltfCamera );
return outputJSON.cameras.length - 1;
}
/**
* Creates glTF animation entry from AnimationClip object.
*
* Status:
* - Only properties listed in PATH_PROPERTIES may be animated.
*
* @param {THREE.AnimationClip} clip
* @param {THREE.Object3D} root
* @return {number}
*/
function processAnimation( clip, root ) {
if ( ! outputJSON.animations ) {
outputJSON.animations = [];
}
clip = GLTFExporter.Utils.mergeMorphTargetTracks( clip.clone(), root );
var tracks = clip.tracks;
var channels = [];
var samplers = [];
for ( var i = 0; i < tracks.length; ++ i ) {
var track = tracks[ i ];
var trackBinding = PropertyBinding.parseTrackName( track.name );
var trackNode = PropertyBinding.findNode( root, trackBinding.nodeName );
var trackProperty = PATH_PROPERTIES[ trackBinding.propertyName ];
if ( trackBinding.objectName === 'bones' ) {
if ( trackNode.isSkinnedMesh === true ) {
trackNode = trackNode.skeleton.getBoneByName( trackBinding.objectIndex );
} else {
trackNode = undefined;
}
}
if ( ! trackNode || ! trackProperty ) {
console.warn( 'THREE.GLTFExporter: Could not export animation track "%s".', track.name );
return null;
}
var inputItemSize = 1;
var outputItemSize = track.values.length / track.times.length;
if ( trackProperty === PATH_PROPERTIES.morphTargetInfluences ) {
outputItemSize /= trackNode.morphTargetInfluences.length;
}
var interpolation;
// @TODO export CubicInterpolant(InterpolateSmooth) as CUBICSPLINE
// Detecting glTF cubic spline interpolant by checking factory method's special property
// GLTFCubicSplineInterpolant is a custom interpolant and track doesn't return
// valid value from .getInterpolation().
if ( track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline === true ) {
interpolation = 'CUBICSPLINE';
// itemSize of CUBICSPLINE keyframe is 9
// (VEC3 * 3: inTangent, splineVertex, and outTangent)
// but needs to be stored as VEC3 so dividing by 3 here.
outputItemSize /= 3;
} else if ( track.getInterpolation() === InterpolateDiscrete ) {
interpolation = 'STEP';
} else {
interpolation = 'LINEAR';
}
samplers.push( {
input: processAccessor( new BufferAttribute( track.times, inputItemSize ) ),
output: processAccessor( new BufferAttribute( track.values, outputItemSize ) ),
interpolation: interpolation
} );
channels.push( {
sampler: samplers.length - 1,
target: {
node: nodeMap.get( trackNode ),
path: trackProperty
}
} );
}
outputJSON.animations.push( {
name: clip.name || 'clip_' + outputJSON.animations.length,
samplers: samplers,
channels: channels
} );
return outputJSON.animations.length - 1;
}
function processSkin( object ) {
var node = outputJSON.nodes[ nodeMap.get( object ) ];
var skeleton = object.skeleton;
var rootJoint = object.skeleton.bones[ 0 ];
if ( rootJoint === undefined ) return null;
var joints = [];
var inverseBindMatrices = new Float32Array( skeleton.bones.length * 16 );
for ( var i = 0; i < skeleton.bones.length; ++ i ) {
joints.push( nodeMap.get( skeleton.bones[ i ] ) );
skeleton.boneInverses[ i ].toArray( inverseBindMatrices, i * 16 );
}
if ( outputJSON.skins === undefined ) {
outputJSON.skins = [];
}
outputJSON.skins.push( {
inverseBindMatrices: processAccessor( new BufferAttribute( inverseBindMatrices, 16 ) ),
joints: joints,
skeleton: nodeMap.get( rootJoint )
} );
var skinIndex = node.skin = outputJSON.skins.length - 1;
return skinIndex;
}
function processLight( light ) {
var lightDef = {};
if ( light.name ) lightDef.name = light.name;
lightDef.color = light.color.toArray();
lightDef.intensity = light.intensity;
if ( light.isDirectionalLight ) {
lightDef.type = 'directional';
} else if ( light.isPointLight ) {
lightDef.type = 'point';
if ( light.distance > 0 ) lightDef.range = light.distance;
} else if ( light.isSpotLight ) {
lightDef.type = 'spot';
if ( light.distance > 0 ) lightDef.range = light.distance;
lightDef.spot = {};
lightDef.spot.innerConeAngle = ( light.penumbra - 1.0 ) * light.angle * - 1.0;
lightDef.spot.outerConeAngle = light.angle;
}
if ( light.decay !== undefined && light.decay !== 2 ) {
console.warn( 'THREE.GLTFExporter: Light decay may be lost. glTF is physically-based, '
+ 'and expects light.decay=2.' );
}
if ( light.target
&& ( light.target.parent !== light
|| light.target.position.x !== 0
|| light.target.position.y !== 0
|| light.target.position.z !== - 1 ) ) {
console.warn( 'THREE.GLTFExporter: Light direction may be lost. For best results, '
+ 'make light.target a child of the light with position 0,0,-1.' );
}
var lights = outputJSON.extensions[ 'KHR_lights_punctual' ].lights;
lights.push( lightDef );
return lights.length - 1;
}
/**
* Process Object3D node
* @param {THREE.Object3D} node Object3D to processNode
* @return {Integer} Index of the node in the nodes list
*/
function processNode( object ) {
if ( ! outputJSON.nodes ) {
outputJSON.nodes = [];
}
var gltfNode = {};
if ( options.trs ) {
var rotation = object.quaternion.toArray();
var position = object.position.toArray();
var scale = object.scale.toArray();
if ( ! equalArray( rotation, [ 0, 0, 0, 1 ] ) ) {
gltfNode.rotation = rotation;
}
if ( ! equalArray( position, [ 0, 0, 0 ] ) ) {
gltfNode.translation = position;
}
if ( ! equalArray( scale, [ 1, 1, 1 ] ) ) {
gltfNode.scale = scale;
}
} else {
object.updateMatrix();
if ( ! equalArray( object.matrix.elements, [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] ) ) {
gltfNode.matrix = object.matrix.elements;
}
}
// We don't export empty strings name because it represents no-name in Three.js.
if ( object.name !== '' ) {
gltfNode.name = String( object.name );
}
serializeUserData( object, gltfNode );
if ( object.isMesh || object.isLine || object.isPoints ) {
var mesh = processMesh( object );
if ( mesh !== null ) {
gltfNode.mesh = mesh;
}
} else if ( object.isCamera ) {
gltfNode.camera = processCamera( object );
} else if ( object.isDirectionalLight || object.isPointLight || object.isSpotLight ) {
if ( ! extensionsUsed[ 'KHR_lights_punctual' ] ) {
outputJSON.extensions = outputJSON.extensions || {};
outputJSON.extensions[ 'KHR_lights_punctual' ] = { lights: [] };
extensionsUsed[ 'KHR_lights_punctual' ] = true;
}
gltfNode.extensions = gltfNode.extensions || {};
gltfNode.extensions[ 'KHR_lights_punctual' ] = { light: processLight( object ) };
} else if ( object.isLight ) {
console.warn( 'THREE.GLTFExporter: Only directional, point, and spot lights are supported.', object );
return null;
}
if ( object.isSkinnedMesh ) {
skins.push( object );
}
if ( object.children.length > 0 ) {
var children = [];
for ( var i = 0, l = object.children.length; i < l; i ++ ) {
var child = object.children[ i ];
if ( child.visible || options.onlyVisible === false ) {
var node = processNode( child );
if ( node !== null ) {
children.push( node );
}
}
}
if ( children.length > 0 ) {
gltfNode.children = children;
}
}
outputJSON.nodes.push( gltfNode );
var nodeIndex = outputJSON.nodes.length - 1;
nodeMap.set( object, nodeIndex );
return nodeIndex;
}
/**
* Process Scene
* @param {Scene} node Scene to process
*/
function processScene( scene ) {
if ( ! outputJSON.scenes ) {
outputJSON.scenes = [];
outputJSON.scene = 0;
}
var gltfScene = {
nodes: []
};
if ( scene.name !== '' ) {
gltfScene.name = scene.name;
}
if ( scene.userData && Object.keys( scene.userData ).length > 0 ) {
gltfScene.extras = serializeUserData( scene );
}
outputJSON.scenes.push( gltfScene );
var nodes = [];
for ( var i = 0, l = scene.children.length; i < l; i ++ ) {
var child = scene.children[ i ];
if ( child.visible || options.onlyVisible === false ) {
var node = processNode( child );
if ( node !== null ) {
nodes.push( node );
}
}
}
if ( nodes.length > 0 ) {
gltfScene.nodes = nodes;
}
serializeUserData( scene, gltfScene );
}
/**
* Creates a Scene to hold a list of objects and parse it
* @param {Array} objects List of objects to process
*/
function processObjects( objects ) {
var scene = new Scene();
scene.name = 'AuxScene';
for ( var i = 0; i < objects.length; i ++ ) {
// We push directly to children instead of calling `add` to prevent
// modify the .parent and break its original scene and hierarchy
scene.children.push( objects[ i ] );
}
processScene( scene );
}
function processInput( input ) {
input = input instanceof Array ? input : [ input ];
var objectsWithoutScene = [];
for ( var i = 0; i < input.length; i ++ ) {
if ( input[ i ] instanceof Scene ) {
processScene( input[ i ] );
} else {
objectsWithoutScene.push( input[ i ] );
}
}
if ( objectsWithoutScene.length > 0 ) {
processObjects( objectsWithoutScene );
}
for ( var i = 0; i < skins.length; ++ i ) {
processSkin( skins[ i ] );
}
for ( var i = 0; i < options.animations.length; ++ i ) {
processAnimation( options.animations[ i ], input[ 0 ] );
}
}
processInput( input );
Promise.all( pending ).then( function () {
// Merge buffers.
var blob = new Blob( buffers, { type: 'application/octet-stream' } );
// Declare extensions.
var extensionsUsedList = Object.keys( extensionsUsed );
if ( extensionsUsedList.length > 0 ) outputJSON.extensionsUsed = extensionsUsedList;
if ( outputJSON.buffers && outputJSON.buffers.length > 0 ) {
// Update bytelength of the single buffer.
outputJSON.buffers[ 0 ].byteLength = blob.size;
var reader = new window.FileReader();
if ( options.binary === true ) {
// https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#glb-file-format-specification
var GLB_HEADER_BYTES = 12;
var GLB_HEADER_MAGIC = 0x46546C67;
var GLB_VERSION = 2;
var GLB_CHUNK_PREFIX_BYTES = 8;
var GLB_CHUNK_TYPE_JSON = 0x4E4F534A;
var GLB_CHUNK_TYPE_BIN = 0x004E4942;
reader.readAsArrayBuffer( blob );
reader.onloadend = function () {
// Binary chunk.
var binaryChunk = getPaddedArrayBuffer( reader.result );
var binaryChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
binaryChunkPrefix.setUint32( 0, binaryChunk.byteLength, true );
binaryChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_BIN, true );
// JSON chunk.
var jsonChunk = getPaddedArrayBuffer( stringToArrayBuffer( JSON.stringify( outputJSON ) ), 0x20 );
var jsonChunkPrefix = new DataView( new ArrayBuffer( GLB_CHUNK_PREFIX_BYTES ) );
jsonChunkPrefix.setUint32( 0, jsonChunk.byteLength, true );
jsonChunkPrefix.setUint32( 4, GLB_CHUNK_TYPE_JSON, true );
// GLB header.
var header = new ArrayBuffer( GLB_HEADER_BYTES );
var headerView = new DataView( header );
headerView.setUint32( 0, GLB_HEADER_MAGIC, true );
headerView.setUint32( 4, GLB_VERSION, true );
var totalByteLength = GLB_HEADER_BYTES
+ jsonChunkPrefix.byteLength + jsonChunk.byteLength
+ binaryChunkPrefix.byteLength + binaryChunk.byteLength;
headerView.setUint32( 8, totalByteLength, true );
var glbBlob = new Blob( [
header,
jsonChunkPrefix,
jsonChunk,
binaryChunkPrefix,
binaryChunk
], { type: 'application/octet-stream' } );
var glbReader = new window.FileReader();
glbReader.readAsArrayBuffer( glbBlob );
glbReader.onloadend = function () {
onDone( glbReader.result );
};
};
} else {
reader.readAsDataURL( blob );
reader.onloadend = function () {
var base64data = reader.result;
outputJSON.buffers[ 0 ].uri = base64data;
onDone( outputJSON );
};
}
} else {
onDone( outputJSON );
}
} );
}
};
GLTFExporter.Utils = {
insertKeyframe: function ( track, time ) {
var tolerance = 0.001; // 1ms
var valueSize = track.getValueSize();
var times = new track.TimeBufferType( track.times.length + 1 );
var values = new track.ValueBufferType( track.values.length + valueSize );
var interpolant = track.createInterpolant( new track.ValueBufferType( valueSize ) );
var index;
if ( track.times.length === 0 ) {
times[ 0 ] = time;
for ( var i = 0; i < valueSize; i ++ ) {
values[ i ] = 0;
}
index = 0;
} else if ( time < track.times[ 0 ] ) {
if ( Math.abs( track.times[ 0 ] - time ) < tolerance ) return 0;
times[ 0 ] = time;
times.set( track.times, 1 );
values.set( interpolant.evaluate( time ), 0 );
values.set( track.values, valueSize );
index = 0;
} else if ( time > track.times[ track.times.length - 1 ] ) {
if ( Math.abs( track.times[ track.times.length - 1 ] - time ) < tolerance ) {
return track.times.length - 1;
}
times[ times.length - 1 ] = time;
times.set( track.times, 0 );
values.set( track.values, 0 );
values.set( interpolant.evaluate( time ), track.values.length );
index = times.length - 1;
} else {
for ( var i = 0; i < track.times.length; i ++ ) {
if ( Math.abs( track.times[ i ] - time ) < tolerance ) return i;
if ( track.times[ i ] < time && track.times[ i + 1 ] > time ) {
times.set( track.times.slice( 0, i + 1 ), 0 );
times[ i + 1 ] = time;
times.set( track.times.slice( i + 1 ), i + 2 );
values.set( track.values.slice( 0, ( i + 1 ) * valueSize ), 0 );
values.set( interpolant.evaluate( time ), ( i + 1 ) * valueSize );
values.set( track.values.slice( ( i + 1 ) * valueSize ), ( i + 2 ) * valueSize );
index = i + 1;
break;
}
}
}
track.times = times;
track.values = values;
return index;
},
mergeMorphTargetTracks: function ( clip, root ) {
var tracks = [];
var mergedTracks = {};
var sourceTracks = clip.tracks;
for ( var i = 0; i < sourceTracks.length; ++ i ) {
var sourceTrack = sourceTracks[ i ];
var sourceTrackBinding = PropertyBinding.parseTrackName( sourceTrack.name );
var sourceTrackNode = PropertyBinding.findNode( root, sourceTrackBinding.nodeName );
if ( sourceTrackBinding.propertyName !== 'morphTargetInfluences' || sourceTrackBinding.propertyIndex === undefined ) {
// Tracks that don't affect morph targets, or that affect all morph targets together, can be left as-is.
tracks.push( sourceTrack );
continue;
}
if ( sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodDiscrete
&& sourceTrack.createInterpolant !== sourceTrack.InterpolantFactoryMethodLinear ) {
if ( sourceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
// This should never happen, because glTF morph target animations
// affect all targets already.
throw new Error( 'THREE.GLTFExporter: Cannot merge tracks with glTF CUBICSPLINE interpolation.' );
}
console.warn( 'THREE.GLTFExporter: Morph target interpolation mode not yet supported. Using LINEAR instead.' );
sourceTrack = sourceTrack.clone();
sourceTrack.setInterpolation( InterpolateLinear );
}
var targetCount = sourceTrackNode.morphTargetInfluences.length;
var targetIndex = sourceTrackNode.morphTargetDictionary[ sourceTrackBinding.propertyIndex ];
if ( targetIndex === undefined ) {
throw new Error( 'THREE.GLTFExporter: Morph target name not found: ' + sourceTrackBinding.propertyIndex );
}
var mergedTrack;
// If this is the first time we've seen this object, create a new
// track to store merged keyframe data for each morph target.
if ( mergedTracks[ sourceTrackNode.uuid ] === undefined ) {
mergedTrack = sourceTrack.clone();
var values = new mergedTrack.ValueBufferType( targetCount * mergedTrack.times.length );
for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
values[ j * targetCount + targetIndex ] = mergedTrack.values[ j ];
}
mergedTrack.name = '.morphTargetInfluences';
mergedTrack.values = values;
mergedTracks[ sourceTrackNode.uuid ] = mergedTrack;
tracks.push( mergedTrack );
continue;
}
var mergedKeyframeIndex = 0;
var sourceKeyframeIndex = 0;
var sourceInterpolant = sourceTrack.createInterpolant( new sourceTrack.ValueBufferType( 1 ) );
mergedTrack = mergedTracks[ sourceTrackNode.uuid ];
// For every existing keyframe of the merged track, write a (possibly
// interpolated) value from the source track.
for ( var j = 0; j < mergedTrack.times.length; j ++ ) {
mergedTrack.values[ j * targetCount + targetIndex ] = sourceInterpolant.evaluate( mergedTrack.times[ j ] );
}
// For every existing keyframe of the source track, write a (possibly
// new) keyframe to the merged track. Values from the previous loop may
// be written again, but keyframes are de-duplicated.
for ( var j = 0; j < sourceTrack.times.length; j ++ ) {
var keyframeIndex = this.insertKeyframe( mergedTrack, sourceTrack.times[ j ] );
mergedTrack.values[ keyframeIndex * targetCount + targetIndex ] = sourceTrack.values[ j ];
}
}
clip.tracks = tracks;
return clip;
}
};
export { GLTFExporter };
|