LegacyGLTFLoader.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286
  1. /**
  2. * @author Rich Tibbett / https://github.com/richtr
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author Tony Parisi / http://www.tonyparisi.com/
  5. * @author Takahiro / https://github.com/takahirox
  6. */
  7. THREE.LegacyGLTFLoader = ( function () {
  8. function LegacyGLTFLoader( manager ) {
  9. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10. }
  11. LegacyGLTFLoader.prototype = {
  12. constructor: LegacyGLTFLoader,
  13. crossOrigin: 'Anonymous',
  14. load: function ( url, onLoad, onProgress, onError ) {
  15. var scope = this;
  16. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setResponseType( 'arraybuffer' );
  19. loader.load( url, function ( data ) {
  20. scope.parse( data, path, onLoad );
  21. }, onProgress, onError );
  22. },
  23. setCrossOrigin: function ( value ) {
  24. this.crossOrigin = value;
  25. },
  26. setPath: function ( value ) {
  27. this.path = value;
  28. },
  29. parse: function ( data, path, callback ) {
  30. var content;
  31. var extensions = {};
  32. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  33. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  34. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  35. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36. } else {
  37. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  38. }
  39. var json = JSON.parse( content );
  40. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  41. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  42. }
  43. console.time( 'LegacyGLTFLoader' );
  44. var parser = new GLTFParser( json, extensions, {
  45. path: path || this.path,
  46. crossOrigin: this.crossOrigin
  47. } );
  48. parser.parse( function ( scene, scenes, cameras, animations ) {
  49. console.timeEnd( 'LegacyGLTFLoader' );
  50. var glTF = {
  51. "scene": scene,
  52. "scenes": scenes,
  53. "cameras": cameras,
  54. "animations": animations
  55. };
  56. callback( glTF );
  57. } );
  58. }
  59. };
  60. /* GLTFREGISTRY */
  61. function GLTFRegistry() {
  62. var objects = {};
  63. return {
  64. get: function ( key ) {
  65. return objects[ key ];
  66. },
  67. add: function ( key, object ) {
  68. objects[ key ] = object;
  69. },
  70. remove: function ( key ) {
  71. delete objects[ key ];
  72. },
  73. removeAll: function () {
  74. objects = {};
  75. },
  76. update: function ( scene, camera ) {
  77. for ( var name in objects ) {
  78. var object = objects[ name ];
  79. if ( object.update ) {
  80. object.update( scene, camera );
  81. }
  82. }
  83. }
  84. };
  85. }
  86. /* GLTFSHADERS */
  87. LegacyGLTFLoader.Shaders = {
  88. update: function () {
  89. console.warn( 'THREE.LegacyGLTFLoader.Shaders has been deprecated, and now updates automatically.' );
  90. }
  91. };
  92. /* GLTFSHADER */
  93. function GLTFShader( targetNode, allNodes ) {
  94. var boundUniforms = {};
  95. // bind each uniform to its source node
  96. var uniforms = targetNode.material.uniforms;
  97. for ( var uniformId in uniforms ) {
  98. var uniform = uniforms[ uniformId ];
  99. if ( uniform.semantic ) {
  100. var sourceNodeRef = uniform.node;
  101. var sourceNode = targetNode;
  102. if ( sourceNodeRef ) {
  103. sourceNode = allNodes[ sourceNodeRef ];
  104. }
  105. boundUniforms[ uniformId ] = {
  106. semantic: uniform.semantic,
  107. sourceNode: sourceNode,
  108. targetNode: targetNode,
  109. uniform: uniform
  110. };
  111. }
  112. }
  113. this.boundUniforms = boundUniforms;
  114. this._m4 = new THREE.Matrix4();
  115. }
  116. // Update - update all the uniform values
  117. GLTFShader.prototype.update = function ( scene, camera ) {
  118. var boundUniforms = this.boundUniforms;
  119. for ( var name in boundUniforms ) {
  120. var boundUniform = boundUniforms[ name ];
  121. switch ( boundUniform.semantic ) {
  122. case "MODELVIEW":
  123. var m4 = boundUniform.uniform.value;
  124. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  125. break;
  126. case "MODELVIEWINVERSETRANSPOSE":
  127. var m3 = boundUniform.uniform.value;
  128. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  129. m3.getNormalMatrix( this._m4 );
  130. break;
  131. case "PROJECTION":
  132. var m4 = boundUniform.uniform.value;
  133. m4.copy( camera.projectionMatrix );
  134. break;
  135. case "JOINTMATRIX":
  136. var m4v = boundUniform.uniform.value;
  137. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  138. // So it goes like this:
  139. // SkinnedMesh world matrix is already baked into MODELVIEW;
  140. // transform joints to local space,
  141. // then transform using joint's inverse
  142. m4v[ mi ]
  143. .getInverse( boundUniform.sourceNode.matrixWorld )
  144. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  145. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  146. .multiply( boundUniform.targetNode.bindMatrix );
  147. }
  148. break;
  149. default :
  150. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  151. break;
  152. }
  153. }
  154. };
  155. /* ANIMATION */
  156. LegacyGLTFLoader.Animations = {
  157. update: function () {
  158. console.warn( 'THREE.LegacyGLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  159. }
  160. };
  161. /*********************************/
  162. /********** EXTENSIONS ***********/
  163. /*********************************/
  164. var EXTENSIONS = {
  165. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  166. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  167. };
  168. /* MATERIALS COMMON EXTENSION */
  169. function GLTFMaterialsCommonExtension( json ) {
  170. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  171. this.lights = {};
  172. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) || {};
  173. var lights = extension.lights || {};
  174. for ( var lightId in lights ) {
  175. var light = lights[ lightId ];
  176. var lightNode;
  177. var lightParams = light[ light.type ];
  178. var color = new THREE.Color().fromArray( lightParams.color );
  179. switch ( light.type ) {
  180. case "directional":
  181. lightNode = new THREE.DirectionalLight( color );
  182. lightNode.position.set( 0, 0, 1 );
  183. break;
  184. case "point":
  185. lightNode = new THREE.PointLight( color );
  186. break;
  187. case "spot":
  188. lightNode = new THREE.SpotLight( color );
  189. lightNode.position.set( 0, 0, 1 );
  190. break;
  191. case "ambient":
  192. lightNode = new THREE.AmbientLight( color );
  193. break;
  194. }
  195. if ( lightNode ) {
  196. this.lights[ lightId ] = lightNode;
  197. }
  198. }
  199. }
  200. /* BINARY EXTENSION */
  201. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  202. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  203. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  204. function GLTFBinaryExtension( data ) {
  205. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  206. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  207. var header = {
  208. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  209. version: headerView.getUint32( 4, true ),
  210. length: headerView.getUint32( 8, true ),
  211. contentLength: headerView.getUint32( 12, true ),
  212. contentFormat: headerView.getUint32( 16, true )
  213. };
  214. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  215. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  216. if ( header[ key ] !== value ) {
  217. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  218. }
  219. }
  220. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  221. this.header = header;
  222. this.content = THREE.LoaderUtils.decodeText( contentArray );
  223. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  224. }
  225. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  226. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  227. var array = new Uint8Array( bufferView );
  228. return THREE.LoaderUtils.decodeText( array );
  229. };
  230. GLTFBinaryExtension.prototype.loadTextureSourceUri = function ( source, bufferViews ) {
  231. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  232. var bufferView = bufferViews[ metadata.bufferView ];
  233. var stringData = THREE.LoaderUtils.decodeText( new Uint8Array( bufferView ) );
  234. return 'data:' + metadata.mimeType + ';base64,' + btoa( stringData );
  235. };
  236. /*********************************/
  237. /********** INTERNALS ************/
  238. /*********************************/
  239. /* CONSTANTS */
  240. var WEBGL_CONSTANTS = {
  241. FLOAT: 5126,
  242. //FLOAT_MAT2: 35674,
  243. FLOAT_MAT3: 35675,
  244. FLOAT_MAT4: 35676,
  245. FLOAT_VEC2: 35664,
  246. FLOAT_VEC3: 35665,
  247. FLOAT_VEC4: 35666,
  248. LINEAR: 9729,
  249. REPEAT: 10497,
  250. SAMPLER_2D: 35678,
  251. TRIANGLES: 4,
  252. LINES: 1,
  253. UNSIGNED_BYTE: 5121,
  254. UNSIGNED_SHORT: 5123,
  255. VERTEX_SHADER: 35633,
  256. FRAGMENT_SHADER: 35632
  257. };
  258. var WEBGL_TYPE = {
  259. 5126: Number,
  260. //35674: THREE.Matrix2,
  261. 35675: THREE.Matrix3,
  262. 35676: THREE.Matrix4,
  263. 35664: THREE.Vector2,
  264. 35665: THREE.Vector3,
  265. 35666: THREE.Vector4,
  266. 35678: THREE.Texture
  267. };
  268. var WEBGL_COMPONENT_TYPES = {
  269. 5120: Int8Array,
  270. 5121: Uint8Array,
  271. 5122: Int16Array,
  272. 5123: Uint16Array,
  273. 5125: Uint32Array,
  274. 5126: Float32Array
  275. };
  276. var WEBGL_FILTERS = {
  277. 9728: THREE.NearestFilter,
  278. 9729: THREE.LinearFilter,
  279. 9984: THREE.NearestMipMapNearestFilter,
  280. 9985: THREE.LinearMipMapNearestFilter,
  281. 9986: THREE.NearestMipMapLinearFilter,
  282. 9987: THREE.LinearMipMapLinearFilter
  283. };
  284. var WEBGL_WRAPPINGS = {
  285. 33071: THREE.ClampToEdgeWrapping,
  286. 33648: THREE.MirroredRepeatWrapping,
  287. 10497: THREE.RepeatWrapping
  288. };
  289. var WEBGL_TEXTURE_FORMATS = {
  290. 6406: THREE.AlphaFormat,
  291. 6407: THREE.RGBFormat,
  292. 6408: THREE.RGBAFormat,
  293. 6409: THREE.LuminanceFormat,
  294. 6410: THREE.LuminanceAlphaFormat
  295. };
  296. var WEBGL_TEXTURE_DATATYPES = {
  297. 5121: THREE.UnsignedByteType,
  298. 32819: THREE.UnsignedShort4444Type,
  299. 32820: THREE.UnsignedShort5551Type,
  300. 33635: THREE.UnsignedShort565Type
  301. };
  302. var WEBGL_SIDES = {
  303. 1028: THREE.BackSide, // Culling front
  304. 1029: THREE.FrontSide // Culling back
  305. //1032: THREE.NoSide // Culling front and back, what to do?
  306. };
  307. var WEBGL_DEPTH_FUNCS = {
  308. 512: THREE.NeverDepth,
  309. 513: THREE.LessDepth,
  310. 514: THREE.EqualDepth,
  311. 515: THREE.LessEqualDepth,
  312. 516: THREE.GreaterEqualDepth,
  313. 517: THREE.NotEqualDepth,
  314. 518: THREE.GreaterEqualDepth,
  315. 519: THREE.AlwaysDepth
  316. };
  317. var WEBGL_BLEND_EQUATIONS = {
  318. 32774: THREE.AddEquation,
  319. 32778: THREE.SubtractEquation,
  320. 32779: THREE.ReverseSubtractEquation
  321. };
  322. var WEBGL_BLEND_FUNCS = {
  323. 0: THREE.ZeroFactor,
  324. 1: THREE.OneFactor,
  325. 768: THREE.SrcColorFactor,
  326. 769: THREE.OneMinusSrcColorFactor,
  327. 770: THREE.SrcAlphaFactor,
  328. 771: THREE.OneMinusSrcAlphaFactor,
  329. 772: THREE.DstAlphaFactor,
  330. 773: THREE.OneMinusDstAlphaFactor,
  331. 774: THREE.DstColorFactor,
  332. 775: THREE.OneMinusDstColorFactor,
  333. 776: THREE.SrcAlphaSaturateFactor
  334. // The followings are not supported by Three.js yet
  335. //32769: CONSTANT_COLOR,
  336. //32770: ONE_MINUS_CONSTANT_COLOR,
  337. //32771: CONSTANT_ALPHA,
  338. //32772: ONE_MINUS_CONSTANT_COLOR
  339. };
  340. var WEBGL_TYPE_SIZES = {
  341. 'SCALAR': 1,
  342. 'VEC2': 2,
  343. 'VEC3': 3,
  344. 'VEC4': 4,
  345. 'MAT2': 4,
  346. 'MAT3': 9,
  347. 'MAT4': 16
  348. };
  349. var PATH_PROPERTIES = {
  350. scale: 'scale',
  351. translation: 'position',
  352. rotation: 'quaternion'
  353. };
  354. var INTERPOLATION = {
  355. LINEAR: THREE.InterpolateLinear,
  356. STEP: THREE.InterpolateDiscrete
  357. };
  358. var STATES_ENABLES = {
  359. 2884: 'CULL_FACE',
  360. 2929: 'DEPTH_TEST',
  361. 3042: 'BLEND',
  362. 3089: 'SCISSOR_TEST',
  363. 32823: 'POLYGON_OFFSET_FILL',
  364. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  365. };
  366. /* UTILITY FUNCTIONS */
  367. function _each( object, callback, thisObj ) {
  368. if ( !object ) {
  369. return Promise.resolve();
  370. }
  371. var results;
  372. var fns = [];
  373. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  374. results = [];
  375. var length = object.length;
  376. for ( var idx = 0; idx < length; idx ++ ) {
  377. var value = callback.call( thisObj || this, object[ idx ], idx );
  378. if ( value ) {
  379. fns.push( value );
  380. if ( value instanceof Promise ) {
  381. value.then( function( key, value ) {
  382. results[ key ] = value;
  383. }.bind( this, idx ));
  384. } else {
  385. results[ idx ] = value;
  386. }
  387. }
  388. }
  389. } else {
  390. results = {};
  391. for ( var key in object ) {
  392. if ( object.hasOwnProperty( key ) ) {
  393. var value = callback.call( thisObj || this, object[ key ], key );
  394. if ( value ) {
  395. fns.push( value );
  396. if ( value instanceof Promise ) {
  397. value.then( function( key, value ) {
  398. results[ key ] = value;
  399. }.bind( this, key ));
  400. } else {
  401. results[ key ] = value;
  402. }
  403. }
  404. }
  405. }
  406. }
  407. return Promise.all( fns ).then( function() {
  408. return results;
  409. });
  410. }
  411. function resolveURL( url, path ) {
  412. // Invalid URL
  413. if ( typeof url !== 'string' || url === '' )
  414. return '';
  415. // Absolute URL http://,https://,//
  416. if ( /^(https?:)?\/\//i.test( url ) ) {
  417. return url;
  418. }
  419. // Data URI
  420. if ( /^data:.*,.*$/i.test( url ) ) {
  421. return url;
  422. }
  423. // Relative URL
  424. return ( path || '' ) + url;
  425. }
  426. // Three.js seems too dependent on attribute names so globally
  427. // replace those in the shader code
  428. function replaceTHREEShaderAttributes( shaderText, technique ) {
  429. // Expected technique attributes
  430. var attributes = {};
  431. for ( var attributeId in technique.attributes ) {
  432. var pname = technique.attributes[ attributeId ];
  433. var param = technique.parameters[ pname ];
  434. var atype = param.type;
  435. var semantic = param.semantic;
  436. attributes[ attributeId ] = {
  437. type: atype,
  438. semantic: semantic
  439. };
  440. }
  441. // Figure out which attributes to change in technique
  442. var shaderParams = technique.parameters;
  443. var shaderAttributes = technique.attributes;
  444. var params = {};
  445. for ( var attributeId in attributes ) {
  446. var pname = shaderAttributes[ attributeId ];
  447. var shaderParam = shaderParams[ pname ];
  448. var semantic = shaderParam.semantic;
  449. if ( semantic ) {
  450. params[ attributeId ] = shaderParam;
  451. }
  452. }
  453. for ( var pname in params ) {
  454. var param = params[ pname ];
  455. var semantic = param.semantic;
  456. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  457. switch ( semantic ) {
  458. case "POSITION_0":
  459. case "POSITION0":
  460. case "POSITION":
  461. shaderText = shaderText.replace( regEx, 'position' );
  462. break;
  463. case "NORMAL_0":
  464. case "NORMAL0":
  465. case "NORMAL":
  466. shaderText = shaderText.replace( regEx, 'normal' );
  467. break;
  468. case 'TEXCOORD_0':
  469. case 'TEXCOORD0':
  470. case 'TEXCOORD':
  471. shaderText = shaderText.replace( regEx, 'uv' );
  472. break;
  473. case 'COLOR_0':
  474. case 'COLOR0':
  475. case 'COLOR':
  476. shaderText = shaderText.replace( regEx, 'color' );
  477. break;
  478. case "WEIGHT_0":
  479. case "WEIGHT0":
  480. case "WEIGHT":
  481. shaderText = shaderText.replace( regEx, 'skinWeight' );
  482. break;
  483. case "JOINT_0":
  484. case "JOINT0":
  485. case "JOINT":
  486. shaderText = shaderText.replace( regEx, 'skinIndex' );
  487. break;
  488. default:
  489. var underscoreIndex = semantic.indexOf( '_' );
  490. if ( underscoreIndex !== - 1 ) {
  491. var attrName = semantic.slice( 0, underscoreIndex ).toLowerCase();
  492. var attrNum = parseInt( semantic.slice( underscoreIndex + 1 ) ) + 1;
  493. switch ( attrName ) {
  494. case 'position':
  495. case 'normal':
  496. case 'color':
  497. shaderText = shaderText.replace( regEx, attrName + attrNum );
  498. break;
  499. case 'texcoord':
  500. shaderText = shaderText.replace( regEx, 'uv' + attrNum );
  501. break;
  502. case 'weight':
  503. shaderText = shaderText.replace( regEx, 'skinWeight' + attrNum );
  504. break;
  505. case 'joint':
  506. shaderText = shaderText.replace( regEx, 'skinIndex' + attrNum );
  507. break;
  508. }
  509. }
  510. }
  511. }
  512. return shaderText;
  513. }
  514. function createDefaultMaterial() {
  515. return new THREE.MeshPhongMaterial( {
  516. color: 0x00000,
  517. emissive: 0x888888,
  518. specular: 0x000000,
  519. shininess: 0,
  520. transparent: false,
  521. depthTest: true,
  522. side: THREE.FrontSide
  523. } );
  524. }
  525. // Deferred constructor for RawShaderMaterial types
  526. function DeferredShaderMaterial( params ) {
  527. this.isDeferredShaderMaterial = true;
  528. this.params = params;
  529. }
  530. DeferredShaderMaterial.prototype.create = function () {
  531. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  532. for ( var uniformId in this.params.uniforms ) {
  533. var originalUniform = this.params.uniforms[ uniformId ];
  534. if ( originalUniform.value instanceof THREE.Texture ) {
  535. uniforms[ uniformId ].value = originalUniform.value;
  536. uniforms[ uniformId ].value.needsUpdate = true;
  537. }
  538. uniforms[ uniformId ].semantic = originalUniform.semantic;
  539. uniforms[ uniformId ].node = originalUniform.node;
  540. }
  541. this.params.uniforms = uniforms;
  542. return new THREE.RawShaderMaterial( this.params );
  543. };
  544. /* GLTF PARSER */
  545. function GLTFParser( json, extensions, options ) {
  546. this.json = json || {};
  547. this.extensions = extensions || {};
  548. this.options = options || {};
  549. // loader object cache
  550. this.cache = new GLTFRegistry();
  551. }
  552. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  553. var _dependencies = {};
  554. for ( var i = 0; i < dependencies.length; i ++ ) {
  555. var dependency = dependencies[ i ];
  556. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  557. var cached = this.cache.get( dependency );
  558. if ( cached !== undefined ) {
  559. _dependencies[ dependency ] = cached;
  560. } else if ( this[ fnName ] ) {
  561. var fn = this[ fnName ]();
  562. this.cache.add( dependency, fn );
  563. _dependencies[ dependency ] = fn;
  564. }
  565. }
  566. return _each( _dependencies, function ( dependency ) {
  567. return dependency;
  568. } );
  569. };
  570. GLTFParser.prototype.parse = function ( callback ) {
  571. var json = this.json;
  572. // Clear the loader cache
  573. this.cache.removeAll();
  574. // Fire the callback on complete
  575. this._withDependencies( [
  576. "scenes",
  577. "cameras",
  578. "animations"
  579. ] ).then( function ( dependencies ) {
  580. var scenes = [];
  581. for ( var name in dependencies.scenes ) {
  582. scenes.push( dependencies.scenes[ name ] );
  583. }
  584. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  585. var cameras = [];
  586. for ( var name in dependencies.cameras ) {
  587. var camera = dependencies.cameras[ name ];
  588. cameras.push( camera );
  589. }
  590. var animations = [];
  591. for ( var name in dependencies.animations ) {
  592. animations.push( dependencies.animations[ name ] );
  593. }
  594. callback( scene, scenes, cameras, animations );
  595. } );
  596. };
  597. GLTFParser.prototype.loadShaders = function () {
  598. var json = this.json;
  599. var extensions = this.extensions;
  600. var options = this.options;
  601. return this._withDependencies( [
  602. "bufferViews"
  603. ] ).then( function ( dependencies ) {
  604. return _each( json.shaders, function ( shader ) {
  605. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  606. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  607. }
  608. return new Promise( function ( resolve ) {
  609. var loader = new THREE.FileLoader();
  610. loader.setResponseType( 'text' );
  611. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  612. resolve( shaderText );
  613. } );
  614. } );
  615. } );
  616. } );
  617. };
  618. GLTFParser.prototype.loadBuffers = function () {
  619. var json = this.json;
  620. var extensions = this.extensions;
  621. var options = this.options;
  622. return _each( json.buffers, function ( buffer, name ) {
  623. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  624. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  625. }
  626. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  627. return new Promise( function ( resolve ) {
  628. var loader = new THREE.FileLoader();
  629. loader.setResponseType( 'arraybuffer' );
  630. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  631. resolve( buffer );
  632. } );
  633. } );
  634. } else {
  635. console.warn( 'THREE.LegacyGLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  636. }
  637. } );
  638. };
  639. GLTFParser.prototype.loadBufferViews = function () {
  640. var json = this.json;
  641. return this._withDependencies( [
  642. "buffers"
  643. ] ).then( function ( dependencies ) {
  644. return _each( json.bufferViews, function ( bufferView ) {
  645. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  646. var byteLength = bufferView.byteLength !== undefined ? bufferView.byteLength : 0;
  647. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + byteLength );
  648. } );
  649. } );
  650. };
  651. GLTFParser.prototype.loadAccessors = function () {
  652. var json = this.json;
  653. return this._withDependencies( [
  654. "bufferViews"
  655. ] ).then( function ( dependencies ) {
  656. return _each( json.accessors, function ( accessor ) {
  657. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  658. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  659. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  660. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  661. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  662. var itemBytes = elementBytes * itemSize;
  663. // The buffer is not interleaved if the stride is the item size in bytes.
  664. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  665. // Use the full buffer if it's interleaved.
  666. var array = new TypedArray( arraybuffer );
  667. // Integer parameters to IB/IBA are in array elements, not bytes.
  668. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  669. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  670. } else {
  671. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  672. return new THREE.BufferAttribute( array, itemSize );
  673. }
  674. } );
  675. } );
  676. };
  677. GLTFParser.prototype.loadTextures = function () {
  678. var json = this.json;
  679. var extensions = this.extensions;
  680. var options = this.options;
  681. return this._withDependencies( [
  682. "bufferViews"
  683. ] ).then( function ( dependencies ) {
  684. return _each( json.textures, function ( texture ) {
  685. if ( texture.source ) {
  686. return new Promise( function ( resolve ) {
  687. var source = json.images[ texture.source ];
  688. var sourceUri = source.uri;
  689. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  690. sourceUri = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadTextureSourceUri( source, dependencies.bufferViews );
  691. }
  692. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  693. if ( textureLoader === null ) {
  694. textureLoader = new THREE.TextureLoader();
  695. }
  696. textureLoader.setCrossOrigin( options.crossOrigin );
  697. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  698. _texture.flipY = false;
  699. if ( texture.name !== undefined ) _texture.name = texture.name;
  700. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  701. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  702. console.warn( 'THREE.LegacyGLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  703. 'internalFormat will be forced to be the same value as format.' );
  704. }
  705. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  706. if ( texture.sampler ) {
  707. var sampler = json.samplers[ texture.sampler ];
  708. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  709. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.NearestMipMapLinearFilter;
  710. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  711. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  712. }
  713. resolve( _texture );
  714. }, undefined, function () {
  715. resolve();
  716. } );
  717. } );
  718. }
  719. } );
  720. } );
  721. };
  722. GLTFParser.prototype.loadMaterials = function () {
  723. var json = this.json;
  724. return this._withDependencies( [
  725. "shaders",
  726. "textures"
  727. ] ).then( function ( dependencies ) {
  728. return _each( json.materials, function ( material ) {
  729. var materialType;
  730. var materialValues = {};
  731. var materialParams = {};
  732. var khr_material;
  733. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  734. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  735. }
  736. if ( khr_material ) {
  737. // don't copy over unused values to avoid material warning spam
  738. var keys = [ 'ambient', 'emission', 'transparent', 'transparency', 'doubleSided' ];
  739. switch ( khr_material.technique ) {
  740. case 'BLINN' :
  741. case 'PHONG' :
  742. materialType = THREE.MeshPhongMaterial;
  743. keys.push( 'diffuse', 'specular', 'shininess' );
  744. break;
  745. case 'LAMBERT' :
  746. materialType = THREE.MeshLambertMaterial;
  747. keys.push( 'diffuse' );
  748. break;
  749. case 'CONSTANT' :
  750. default :
  751. materialType = THREE.MeshBasicMaterial;
  752. break;
  753. }
  754. keys.forEach( function( v ) {
  755. if ( khr_material.values[ v ] !== undefined ) materialValues[ v ] = khr_material.values[ v ];
  756. } );
  757. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  758. materialParams.side = THREE.DoubleSide;
  759. }
  760. if ( khr_material.transparent || materialValues.transparent ) {
  761. materialParams.transparent = true;
  762. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  763. }
  764. } else if ( material.technique === undefined ) {
  765. materialType = THREE.MeshPhongMaterial;
  766. Object.assign( materialValues, material.values );
  767. } else {
  768. materialType = DeferredShaderMaterial;
  769. var technique = json.techniques[ material.technique ];
  770. materialParams.uniforms = {};
  771. var program = json.programs[ technique.program ];
  772. if ( program ) {
  773. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  774. if ( ! materialParams.fragmentShader ) {
  775. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  776. materialType = THREE.MeshPhongMaterial;
  777. }
  778. var vertexShader = dependencies.shaders[ program.vertexShader ];
  779. if ( ! vertexShader ) {
  780. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  781. materialType = THREE.MeshPhongMaterial;
  782. }
  783. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  784. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  785. var uniforms = technique.uniforms;
  786. for ( var uniformId in uniforms ) {
  787. var pname = uniforms[ uniformId ];
  788. var shaderParam = technique.parameters[ pname ];
  789. var ptype = shaderParam.type;
  790. if ( WEBGL_TYPE[ ptype ] ) {
  791. var pcount = shaderParam.count;
  792. var value;
  793. if ( material.values !== undefined ) value = material.values[ pname ];
  794. var uvalue = new WEBGL_TYPE[ ptype ]();
  795. var usemantic = shaderParam.semantic;
  796. var unode = shaderParam.node;
  797. switch ( ptype ) {
  798. case WEBGL_CONSTANTS.FLOAT:
  799. uvalue = shaderParam.value;
  800. if ( pname == "transparency" ) {
  801. materialParams.transparent = true;
  802. }
  803. if ( value !== undefined ) {
  804. uvalue = value;
  805. }
  806. break;
  807. case WEBGL_CONSTANTS.FLOAT_VEC2:
  808. case WEBGL_CONSTANTS.FLOAT_VEC3:
  809. case WEBGL_CONSTANTS.FLOAT_VEC4:
  810. case WEBGL_CONSTANTS.FLOAT_MAT3:
  811. if ( shaderParam && shaderParam.value ) {
  812. uvalue.fromArray( shaderParam.value );
  813. }
  814. if ( value ) {
  815. uvalue.fromArray( value );
  816. }
  817. break;
  818. case WEBGL_CONSTANTS.FLOAT_MAT2:
  819. // what to do?
  820. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  821. break;
  822. case WEBGL_CONSTANTS.FLOAT_MAT4:
  823. if ( pcount ) {
  824. uvalue = new Array( pcount );
  825. for ( var mi = 0; mi < pcount; mi ++ ) {
  826. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  827. }
  828. if ( shaderParam && shaderParam.value ) {
  829. var m4v = shaderParam.value;
  830. uvalue.fromArray( m4v );
  831. }
  832. if ( value ) {
  833. uvalue.fromArray( value );
  834. }
  835. } else {
  836. if ( shaderParam && shaderParam.value ) {
  837. var m4 = shaderParam.value;
  838. uvalue.fromArray( m4 );
  839. }
  840. if ( value ) {
  841. uvalue.fromArray( value );
  842. }
  843. }
  844. break;
  845. case WEBGL_CONSTANTS.SAMPLER_2D:
  846. if ( value !== undefined ) {
  847. uvalue = dependencies.textures[ value ];
  848. } else if ( shaderParam.value !== undefined ) {
  849. uvalue = dependencies.textures[ shaderParam.value ];
  850. } else {
  851. uvalue = null;
  852. }
  853. break;
  854. }
  855. materialParams.uniforms[ uniformId ] = {
  856. value: uvalue,
  857. semantic: usemantic,
  858. node: unode
  859. };
  860. } else {
  861. throw new Error( "Unknown shader uniform param type: " + ptype );
  862. }
  863. }
  864. var states = technique.states || {};
  865. var enables = states.enable || [];
  866. var functions = states.functions || {};
  867. var enableCullFace = false;
  868. var enableDepthTest = false;
  869. var enableBlend = false;
  870. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  871. var enable = enables[ i ];
  872. switch ( STATES_ENABLES[ enable ] ) {
  873. case 'CULL_FACE':
  874. enableCullFace = true;
  875. break;
  876. case 'DEPTH_TEST':
  877. enableDepthTest = true;
  878. break;
  879. case 'BLEND':
  880. enableBlend = true;
  881. break;
  882. // TODO: implement
  883. case 'SCISSOR_TEST':
  884. case 'POLYGON_OFFSET_FILL':
  885. case 'SAMPLE_ALPHA_TO_COVERAGE':
  886. break;
  887. default:
  888. throw new Error( "Unknown technique.states.enable: " + enable );
  889. }
  890. }
  891. if ( enableCullFace ) {
  892. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  893. } else {
  894. materialParams.side = THREE.DoubleSide;
  895. }
  896. materialParams.depthTest = enableDepthTest;
  897. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  898. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  899. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  900. materialParams.transparent = enableBlend;
  901. var blendEquationSeparate = functions.blendEquationSeparate;
  902. if ( blendEquationSeparate !== undefined ) {
  903. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  904. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  905. } else {
  906. materialParams.blendEquation = THREE.AddEquation;
  907. materialParams.blendEquationAlpha = THREE.AddEquation;
  908. }
  909. var blendFuncSeparate = functions.blendFuncSeparate;
  910. if ( blendFuncSeparate !== undefined ) {
  911. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  912. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  913. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  914. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  915. } else {
  916. materialParams.blendSrc = THREE.OneFactor;
  917. materialParams.blendDst = THREE.ZeroFactor;
  918. materialParams.blendSrcAlpha = THREE.OneFactor;
  919. materialParams.blendDstAlpha = THREE.ZeroFactor;
  920. }
  921. }
  922. }
  923. if ( Array.isArray( materialValues.diffuse ) ) {
  924. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  925. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  926. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  927. }
  928. delete materialParams.diffuse;
  929. if ( typeof( materialValues.reflective ) === 'string' ) {
  930. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  931. }
  932. if ( typeof( materialValues.bump ) === 'string' ) {
  933. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  934. }
  935. if ( Array.isArray( materialValues.emission ) ) {
  936. if ( materialType === THREE.MeshBasicMaterial ) {
  937. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  938. } else {
  939. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  940. }
  941. } else if ( typeof( materialValues.emission ) === 'string' ) {
  942. if ( materialType === THREE.MeshBasicMaterial ) {
  943. materialParams.map = dependencies.textures[ materialValues.emission ];
  944. } else {
  945. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  946. }
  947. }
  948. if ( Array.isArray( materialValues.specular ) ) {
  949. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  950. } else if ( typeof( materialValues.specular ) === 'string' ) {
  951. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  952. }
  953. if ( materialValues.shininess !== undefined ) {
  954. materialParams.shininess = materialValues.shininess;
  955. }
  956. var _material = new materialType( materialParams );
  957. if ( material.name !== undefined ) _material.name = material.name;
  958. return _material;
  959. } );
  960. } );
  961. };
  962. GLTFParser.prototype.loadMeshes = function () {
  963. var json = this.json;
  964. return this._withDependencies( [
  965. "accessors",
  966. "materials"
  967. ] ).then( function ( dependencies ) {
  968. return _each( json.meshes, function ( mesh ) {
  969. var group = new THREE.Group();
  970. if ( mesh.name !== undefined ) group.name = mesh.name;
  971. if ( mesh.extras ) group.userData = mesh.extras;
  972. var primitives = mesh.primitives || [];
  973. for ( var name in primitives ) {
  974. var primitive = primitives[ name ];
  975. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  976. var geometry = new THREE.BufferGeometry();
  977. var attributes = primitive.attributes;
  978. var attributeIndex = 0;
  979. for ( var attributeId in attributes ) {
  980. var attributeEntry = attributes[ attributeId ];
  981. if ( ! attributeEntry ) return;
  982. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  983. switch ( attributeId ) {
  984. case 'POSITION_0':
  985. case 'POSITION0':
  986. case 'POSITION':
  987. geometry.addAttribute( 'position', bufferAttribute );
  988. break;
  989. case 'NORMAL_0':
  990. case 'NORMAL0':
  991. case 'NORMAL':
  992. geometry.addAttribute( 'normal', bufferAttribute );
  993. break;
  994. case 'TEXCOORD_0':
  995. case 'TEXCOORD0':
  996. case 'TEXCOORD':
  997. geometry.addAttribute( 'uv', bufferAttribute );
  998. break;
  999. case 'COLOR_0':
  1000. case 'COLOR0':
  1001. case 'COLOR':
  1002. geometry.addAttribute( 'color', bufferAttribute );
  1003. break;
  1004. case 'WEIGHT_0':
  1005. case 'WEIGHT0':
  1006. case 'WEIGHT':
  1007. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1008. break;
  1009. case 'JOINT_0':
  1010. case 'JOINT0':
  1011. case 'JOINT':
  1012. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1013. break;
  1014. default:
  1015. var addAttributeWithItsNameUnchanged = false;
  1016. var underscoreIndex = attributeId.indexOf( '_' );
  1017. if ( underscoreIndex !== - 1 ) {
  1018. var attrName = attributeId.slice( 0, underscoreIndex ).toLowerCase();
  1019. var attrNum = parseInt( attributeId.slice( underscoreIndex + 1 ) ) + 1;
  1020. switch ( attrName ) {
  1021. case 'position':
  1022. case 'normal':
  1023. case 'color':
  1024. geometry.addAttribute( attrName + attrNum, bufferAttribute );
  1025. break;
  1026. case 'texcoord':
  1027. geometry.addAttribute( 'uv' + attrNum, bufferAttribute );
  1028. break;
  1029. case 'weight':
  1030. geometry.addAttribute( 'skinWeight' + attrNum, bufferAttribute );
  1031. break;
  1032. case 'joint':
  1033. geometry.addAttribute( 'skinIndex' + attrNum, bufferAttribute );
  1034. break;
  1035. default:
  1036. addAttributeWithItsNameUnchanged = true;
  1037. }
  1038. }
  1039. if ( addAttributeWithItsNameUnchanged || underscoreIndex === - 1 ) {
  1040. var material = json.materials[ primitive.material ];
  1041. var attributeNames = json.techniques[ material.technique ].attributes;
  1042. var attributeName = Object.keys( attributeNames )[ attributeIndex ];
  1043. geometry.addAttribute( attributeName, bufferAttribute );
  1044. }
  1045. }
  1046. ++attributeIndex;
  1047. }
  1048. if ( primitive.indices ) {
  1049. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1050. }
  1051. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  1052. var meshNode = new THREE.Mesh( geometry, material );
  1053. meshNode.castShadow = true;
  1054. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1055. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1056. group.add( meshNode );
  1057. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1058. var geometry = new THREE.BufferGeometry();
  1059. var attributes = primitive.attributes;
  1060. for ( var attributeId in attributes ) {
  1061. var attributeEntry = attributes[ attributeId ];
  1062. if ( ! attributeEntry ) return;
  1063. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1064. switch ( attributeId ) {
  1065. case 'POSITION':
  1066. geometry.addAttribute( 'position', bufferAttribute );
  1067. break;
  1068. case 'COLOR_0':
  1069. case 'COLOR0':
  1070. case 'COLOR':
  1071. geometry.addAttribute( 'color', bufferAttribute );
  1072. break;
  1073. }
  1074. }
  1075. var material = dependencies.materials[ primitive.material ];
  1076. var meshNode;
  1077. if ( primitive.indices ) {
  1078. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1079. meshNode = new THREE.LineSegments( geometry, material );
  1080. } else {
  1081. meshNode = new THREE.Line( geometry, material );
  1082. }
  1083. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1084. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1085. group.add( meshNode );
  1086. } else {
  1087. console.warn( "Only triangular and line primitives are supported" );
  1088. }
  1089. }
  1090. return group;
  1091. } );
  1092. } );
  1093. };
  1094. GLTFParser.prototype.loadCameras = function () {
  1095. var json = this.json;
  1096. return _each( json.cameras, function ( camera ) {
  1097. if ( camera.type == "perspective" && camera.perspective ) {
  1098. var yfov = camera.perspective.yfov;
  1099. var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1;
  1100. // According to COLLADA spec...
  1101. // aspectRatio = xfov / yfov
  1102. var xfov = yfov * aspectRatio;
  1103. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  1104. if ( camera.name !== undefined ) _camera.name = camera.name;
  1105. if ( camera.extras ) _camera.userData = camera.extras;
  1106. return _camera;
  1107. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  1108. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  1109. if ( camera.name !== undefined ) _camera.name = camera.name;
  1110. if ( camera.extras ) _camera.userData = camera.extras;
  1111. return _camera;
  1112. }
  1113. } );
  1114. };
  1115. GLTFParser.prototype.loadSkins = function () {
  1116. var json = this.json;
  1117. return this._withDependencies( [
  1118. "accessors"
  1119. ] ).then( function ( dependencies ) {
  1120. return _each( json.skins, function ( skin ) {
  1121. var bindShapeMatrix = new THREE.Matrix4();
  1122. if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix );
  1123. var _skin = {
  1124. bindShapeMatrix: bindShapeMatrix,
  1125. jointNames: skin.jointNames,
  1126. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1127. };
  1128. return _skin;
  1129. } );
  1130. } );
  1131. };
  1132. GLTFParser.prototype.loadAnimations = function () {
  1133. var json = this.json;
  1134. return this._withDependencies( [
  1135. "accessors",
  1136. "nodes"
  1137. ] ).then( function ( dependencies ) {
  1138. return _each( json.animations, function ( animation, animationId ) {
  1139. var tracks = [];
  1140. for ( var channelId in animation.channels ) {
  1141. var channel = animation.channels[ channelId ];
  1142. var sampler = animation.samplers[ channel.sampler ];
  1143. if ( sampler ) {
  1144. var target = channel.target;
  1145. var name = target.id;
  1146. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1147. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1148. var inputAccessor = dependencies.accessors[ input ];
  1149. var outputAccessor = dependencies.accessors[ output ];
  1150. var node = dependencies.nodes[ name ];
  1151. if ( node ) {
  1152. node.updateMatrix();
  1153. node.matrixAutoUpdate = true;
  1154. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  1155. ? THREE.QuaternionKeyframeTrack
  1156. : THREE.VectorKeyframeTrack;
  1157. var targetName = node.name ? node.name : node.uuid;
  1158. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1159. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1160. // buffers before creating a truncated copy to keep. Because buffers may
  1161. // be reused by other tracks, make copies here.
  1162. tracks.push( new TypedKeyframeTrack(
  1163. targetName + '.' + PATH_PROPERTIES[ target.path ],
  1164. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1165. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1166. interpolation
  1167. ) );
  1168. }
  1169. }
  1170. }
  1171. var name = animation.name !== undefined ? animation.name : "animation_" + animationId;
  1172. return new THREE.AnimationClip( name, undefined, tracks );
  1173. } );
  1174. } );
  1175. };
  1176. GLTFParser.prototype.loadNodes = function () {
  1177. var json = this.json;
  1178. var extensions = this.extensions;
  1179. var scope = this;
  1180. return _each( json.nodes, function ( node ) {
  1181. var matrix = new THREE.Matrix4();
  1182. var _node;
  1183. if ( node.jointName ) {
  1184. _node = new THREE.Bone();
  1185. _node.name = node.name !== undefined ? node.name : node.jointName;
  1186. _node.jointName = node.jointName;
  1187. } else {
  1188. _node = new THREE.Object3D();
  1189. if ( node.name !== undefined ) _node.name = node.name;
  1190. }
  1191. if ( node.extras ) _node.userData = node.extras;
  1192. if ( node.matrix !== undefined ) {
  1193. matrix.fromArray( node.matrix );
  1194. _node.applyMatrix( matrix );
  1195. } else {
  1196. if ( node.translation !== undefined ) {
  1197. _node.position.fromArray( node.translation );
  1198. }
  1199. if ( node.rotation !== undefined ) {
  1200. _node.quaternion.fromArray( node.rotation );
  1201. }
  1202. if ( node.scale !== undefined ) {
  1203. _node.scale.fromArray( node.scale );
  1204. }
  1205. }
  1206. return _node;
  1207. } ).then( function ( __nodes ) {
  1208. return scope._withDependencies( [
  1209. "meshes",
  1210. "skins",
  1211. "cameras"
  1212. ] ).then( function ( dependencies ) {
  1213. return _each( __nodes, function ( _node, nodeId ) {
  1214. var node = json.nodes[ nodeId ];
  1215. if ( node.meshes !== undefined ) {
  1216. for ( var meshId in node.meshes ) {
  1217. var mesh = node.meshes[ meshId ];
  1218. var group = dependencies.meshes[ mesh ];
  1219. if ( group === undefined ) {
  1220. console.warn( 'LegacyGLTFLoader: Couldn\'t find node "' + mesh + '".' );
  1221. continue;
  1222. }
  1223. for ( var childrenId in group.children ) {
  1224. var child = group.children[ childrenId ];
  1225. // clone Mesh to add to _node
  1226. var originalMaterial = child.material;
  1227. var originalGeometry = child.geometry;
  1228. var originalUserData = child.userData;
  1229. var originalName = child.name;
  1230. var material;
  1231. if ( originalMaterial.isDeferredShaderMaterial ) {
  1232. originalMaterial = material = originalMaterial.create();
  1233. } else {
  1234. material = originalMaterial;
  1235. }
  1236. switch ( child.type ) {
  1237. case 'LineSegments':
  1238. child = new THREE.LineSegments( originalGeometry, material );
  1239. break;
  1240. case 'LineLoop':
  1241. child = new THREE.LineLoop( originalGeometry, material );
  1242. break;
  1243. case 'Line':
  1244. child = new THREE.Line( originalGeometry, material );
  1245. break;
  1246. default:
  1247. child = new THREE.Mesh( originalGeometry, material );
  1248. }
  1249. child.castShadow = true;
  1250. child.userData = originalUserData;
  1251. child.name = originalName;
  1252. var skinEntry;
  1253. if ( node.skin ) {
  1254. skinEntry = dependencies.skins[ node.skin ];
  1255. }
  1256. // Replace Mesh with SkinnedMesh in library
  1257. if ( skinEntry ) {
  1258. var getJointNode = function ( jointId ) {
  1259. var keys = Object.keys( __nodes );
  1260. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1261. var n = __nodes[ keys[ i ] ];
  1262. if ( n.jointName === jointId ) return n;
  1263. }
  1264. return null;
  1265. };
  1266. var geometry = originalGeometry;
  1267. var material = originalMaterial;
  1268. material.skinning = true;
  1269. child = new THREE.SkinnedMesh( geometry, material );
  1270. child.castShadow = true;
  1271. child.userData = originalUserData;
  1272. child.name = originalName;
  1273. var bones = [];
  1274. var boneInverses = [];
  1275. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  1276. var jointId = skinEntry.jointNames[ i ];
  1277. var jointNode = getJointNode( jointId );
  1278. if ( jointNode ) {
  1279. bones.push( jointNode );
  1280. var m = skinEntry.inverseBindMatrices.array;
  1281. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1282. boneInverses.push( mat );
  1283. } else {
  1284. console.warn( "WARNING: joint: '" + jointId + "' could not be found" );
  1285. }
  1286. }
  1287. child.bind( new THREE.Skeleton( bones, boneInverses ), skinEntry.bindShapeMatrix );
  1288. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  1289. var children = parentJson[ property ];
  1290. if ( children === undefined ) return;
  1291. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1292. var nodeId = children[ i ];
  1293. var bone = __nodes[ nodeId ];
  1294. var boneJson = json.nodes[ nodeId ];
  1295. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  1296. parentObject.add( bone );
  1297. buildBoneGraph( boneJson, bone, 'children' );
  1298. }
  1299. }
  1300. };
  1301. buildBoneGraph( node, child, 'skeletons' );
  1302. }
  1303. _node.add( child );
  1304. }
  1305. }
  1306. }
  1307. if ( node.camera !== undefined ) {
  1308. var camera = dependencies.cameras[ node.camera ];
  1309. _node.add( camera );
  1310. }
  1311. if ( node.extensions
  1312. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  1313. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  1314. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  1315. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  1316. _node.add( light );
  1317. }
  1318. return _node;
  1319. } );
  1320. } );
  1321. } );
  1322. };
  1323. GLTFParser.prototype.loadScenes = function () {
  1324. var json = this.json;
  1325. // scene node hierachy builder
  1326. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1327. var _node = allNodes[ nodeId ];
  1328. parentObject.add( _node );
  1329. var node = json.nodes[ nodeId ];
  1330. if ( node.children ) {
  1331. var children = node.children;
  1332. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1333. var child = children[ i ];
  1334. buildNodeHierachy( child, _node, allNodes );
  1335. }
  1336. }
  1337. }
  1338. return this._withDependencies( [
  1339. "nodes"
  1340. ] ).then( function ( dependencies ) {
  1341. return _each( json.scenes, function ( scene ) {
  1342. var _scene = new THREE.Scene();
  1343. if ( scene.name !== undefined ) _scene.name = scene.name;
  1344. if ( scene.extras ) _scene.userData = scene.extras;
  1345. var nodes = scene.nodes || [];
  1346. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1347. var nodeId = nodes[ i ];
  1348. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1349. }
  1350. _scene.traverse( function ( child ) {
  1351. // Register raw material meshes with LegacyGLTFLoader.Shaders
  1352. if ( child.material && child.material.isRawShaderMaterial ) {
  1353. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1354. child.onBeforeRender = function(renderer, scene, camera){
  1355. this.gltfShader.update(scene, camera);
  1356. };
  1357. }
  1358. } );
  1359. return _scene;
  1360. } );
  1361. } );
  1362. };
  1363. return LegacyGLTFLoader;
  1364. } )();