GLTFLoader.js 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168
  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. * @author Don McCurdy / https://www.donmccurdy.com
  7. */
  8. THREE.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. this.dracoLoader = null;
  12. }
  13. GLTFLoader.prototype = {
  14. constructor: GLTFLoader,
  15. crossOrigin: 'anonymous',
  16. load: function ( url, onLoad, onProgress, onError ) {
  17. var scope = this;
  18. var resourcePath;
  19. if ( this.resourcePath !== undefined ) {
  20. resourcePath = this.resourcePath;
  21. } else if ( this.path !== undefined ) {
  22. resourcePath = this.path;
  23. } else {
  24. resourcePath = THREE.LoaderUtils.extractUrlBase( url );
  25. }
  26. // Tells the LoadingManager to track an extra item, which resolves after
  27. // the model is fully loaded. This means the count of items loaded will
  28. // be incorrect, but ensures manager.onLoad() does not fire early.
  29. scope.manager.itemStart( url );
  30. var _onError = function ( e ) {
  31. if ( onError ) {
  32. onError( e );
  33. } else {
  34. console.error( e );
  35. }
  36. scope.manager.itemError( url );
  37. scope.manager.itemEnd( url );
  38. };
  39. var loader = new THREE.FileLoader( scope.manager );
  40. loader.setPath( this.path );
  41. loader.setResponseType( 'arraybuffer' );
  42. if ( scope.crossOrigin === 'use-credentials' ) {
  43. loader.setWithCredentials( true );
  44. }
  45. loader.load( url, function ( data ) {
  46. try {
  47. scope.parse( data, resourcePath, function ( gltf ) {
  48. onLoad( gltf );
  49. scope.manager.itemEnd( url );
  50. }, _onError );
  51. } catch ( e ) {
  52. _onError( e );
  53. }
  54. }, onProgress, _onError );
  55. },
  56. setCrossOrigin: function ( value ) {
  57. this.crossOrigin = value;
  58. return this;
  59. },
  60. setPath: function ( value ) {
  61. this.path = value;
  62. return this;
  63. },
  64. setResourcePath: function ( value ) {
  65. this.resourcePath = value;
  66. return this;
  67. },
  68. setDRACOLoader: function ( dracoLoader ) {
  69. this.dracoLoader = dracoLoader;
  70. return this;
  71. },
  72. parse: function ( data, path, onLoad, onError ) {
  73. var content;
  74. var extensions = {};
  75. if ( typeof data === 'string' ) {
  76. content = data;
  77. } else {
  78. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  79. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  80. try {
  81. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  82. } catch ( error ) {
  83. if ( onError ) onError( error );
  84. return;
  85. }
  86. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  87. } else {
  88. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  89. }
  90. }
  91. var json = JSON.parse( content );
  92. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  93. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  94. return;
  95. }
  96. if ( json.extensionsUsed ) {
  97. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  98. var extensionName = json.extensionsUsed[ i ];
  99. var extensionsRequired = json.extensionsRequired || [];
  100. switch ( extensionName ) {
  101. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  102. extensions[ extensionName ] = new GLTFLightsExtension( json );
  103. break;
  104. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  105. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension();
  106. break;
  107. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  108. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  109. break;
  110. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  111. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  112. break;
  113. case EXTENSIONS.MSFT_TEXTURE_DDS:
  114. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  115. break;
  116. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  117. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension();
  118. break;
  119. default:
  120. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  121. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  122. }
  123. }
  124. }
  125. }
  126. var parser = new GLTFParser( json, extensions, {
  127. path: path || this.resourcePath || '',
  128. crossOrigin: this.crossOrigin,
  129. manager: this.manager
  130. } );
  131. parser.parse( onLoad, onError );
  132. }
  133. };
  134. /* GLTFREGISTRY */
  135. function GLTFRegistry() {
  136. var objects = {};
  137. return {
  138. get: function ( key ) {
  139. return objects[ key ];
  140. },
  141. add: function ( key, object ) {
  142. objects[ key ] = object;
  143. },
  144. remove: function ( key ) {
  145. delete objects[ key ];
  146. },
  147. removeAll: function () {
  148. objects = {};
  149. }
  150. };
  151. }
  152. /*********************************/
  153. /********** EXTENSIONS ***********/
  154. /*********************************/
  155. var EXTENSIONS = {
  156. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  157. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  158. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  159. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  160. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  161. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  162. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  163. };
  164. /**
  165. * DDS Texture Extension
  166. *
  167. * Specification:
  168. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  169. *
  170. */
  171. function GLTFTextureDDSExtension() {
  172. if ( ! THREE.DDSLoader ) {
  173. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  174. }
  175. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  176. this.ddsLoader = new THREE.DDSLoader();
  177. }
  178. /**
  179. * Lights Extension
  180. *
  181. * Specification: PENDING
  182. */
  183. function GLTFLightsExtension( json ) {
  184. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  185. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  186. this.lightDefs = extension.lights || [];
  187. }
  188. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  189. var lightDef = this.lightDefs[ lightIndex ];
  190. var lightNode;
  191. var color = new THREE.Color( 0xffffff );
  192. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  193. var range = lightDef.range !== undefined ? lightDef.range : 0;
  194. switch ( lightDef.type ) {
  195. case 'directional':
  196. lightNode = new THREE.DirectionalLight( color );
  197. lightNode.target.position.set( 0, 0, - 1 );
  198. lightNode.add( lightNode.target );
  199. break;
  200. case 'point':
  201. lightNode = new THREE.PointLight( color );
  202. lightNode.distance = range;
  203. break;
  204. case 'spot':
  205. lightNode = new THREE.SpotLight( color );
  206. lightNode.distance = range;
  207. // Handle spotlight properties.
  208. lightDef.spot = lightDef.spot || {};
  209. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  210. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  211. lightNode.angle = lightDef.spot.outerConeAngle;
  212. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  213. lightNode.target.position.set( 0, 0, - 1 );
  214. lightNode.add( lightNode.target );
  215. break;
  216. default:
  217. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  218. }
  219. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  220. // here, because node-level parsing will only override position if explicitly specified.
  221. lightNode.position.set( 0, 0, 0 );
  222. lightNode.decay = 2;
  223. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  224. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  225. return Promise.resolve( lightNode );
  226. };
  227. /**
  228. * Unlit Materials Extension (pending)
  229. *
  230. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  231. */
  232. function GLTFMaterialsUnlitExtension() {
  233. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  234. }
  235. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  236. return THREE.MeshBasicMaterial;
  237. };
  238. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  239. var pending = [];
  240. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  241. materialParams.opacity = 1.0;
  242. var metallicRoughness = materialDef.pbrMetallicRoughness;
  243. if ( metallicRoughness ) {
  244. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  245. var array = metallicRoughness.baseColorFactor;
  246. materialParams.color.fromArray( array );
  247. materialParams.opacity = array[ 3 ];
  248. }
  249. if ( metallicRoughness.baseColorTexture !== undefined ) {
  250. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  251. }
  252. }
  253. return Promise.all( pending );
  254. };
  255. /* BINARY EXTENSION */
  256. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  257. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  258. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  259. function GLTFBinaryExtension( data ) {
  260. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  261. this.content = null;
  262. this.body = null;
  263. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  264. this.header = {
  265. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  266. version: headerView.getUint32( 4, true ),
  267. length: headerView.getUint32( 8, true )
  268. };
  269. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  270. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  271. } else if ( this.header.version < 2.0 ) {
  272. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  273. }
  274. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  275. var chunkIndex = 0;
  276. while ( chunkIndex < chunkView.byteLength ) {
  277. var chunkLength = chunkView.getUint32( chunkIndex, true );
  278. chunkIndex += 4;
  279. var chunkType = chunkView.getUint32( chunkIndex, true );
  280. chunkIndex += 4;
  281. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  282. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  283. this.content = THREE.LoaderUtils.decodeText( contentArray );
  284. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  285. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  286. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  287. }
  288. // Clients must ignore chunks with unknown types.
  289. chunkIndex += chunkLength;
  290. }
  291. if ( this.content === null ) {
  292. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  293. }
  294. }
  295. /**
  296. * DRACO Mesh Compression Extension
  297. *
  298. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  299. */
  300. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  301. if ( ! dracoLoader ) {
  302. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  303. }
  304. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  305. this.json = json;
  306. this.dracoLoader = dracoLoader;
  307. }
  308. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  309. var json = this.json;
  310. var dracoLoader = this.dracoLoader;
  311. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  312. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  313. var threeAttributeMap = {};
  314. var attributeNormalizedMap = {};
  315. var attributeTypeMap = {};
  316. for ( var attributeName in gltfAttributeMap ) {
  317. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  318. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  319. }
  320. for ( attributeName in primitive.attributes ) {
  321. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  322. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  323. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  324. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  325. attributeTypeMap[ threeAttributeName ] = componentType;
  326. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  327. }
  328. }
  329. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  330. return new Promise( function ( resolve ) {
  331. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  332. for ( var attributeName in geometry.attributes ) {
  333. var attribute = geometry.attributes[ attributeName ];
  334. var normalized = attributeNormalizedMap[ attributeName ];
  335. if ( normalized !== undefined ) attribute.normalized = normalized;
  336. }
  337. resolve( geometry );
  338. }, threeAttributeMap, attributeTypeMap );
  339. } );
  340. } );
  341. };
  342. /**
  343. * Texture Transform Extension
  344. *
  345. * Specification:
  346. */
  347. function GLTFTextureTransformExtension() {
  348. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  349. }
  350. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  351. texture = texture.clone();
  352. if ( transform.offset !== undefined ) {
  353. texture.offset.fromArray( transform.offset );
  354. }
  355. if ( transform.rotation !== undefined ) {
  356. texture.rotation = transform.rotation;
  357. }
  358. if ( transform.scale !== undefined ) {
  359. texture.repeat.fromArray( transform.scale );
  360. }
  361. if ( transform.texCoord !== undefined ) {
  362. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  363. }
  364. texture.needsUpdate = true;
  365. return texture;
  366. };
  367. /**
  368. * Specular-Glossiness Extension
  369. *
  370. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  371. */
  372. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  373. return {
  374. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  375. specularGlossinessParams: [
  376. 'color',
  377. 'map',
  378. 'lightMap',
  379. 'lightMapIntensity',
  380. 'aoMap',
  381. 'aoMapIntensity',
  382. 'emissive',
  383. 'emissiveIntensity',
  384. 'emissiveMap',
  385. 'bumpMap',
  386. 'bumpScale',
  387. 'normalMap',
  388. 'displacementMap',
  389. 'displacementScale',
  390. 'displacementBias',
  391. 'specularMap',
  392. 'specular',
  393. 'glossinessMap',
  394. 'glossiness',
  395. 'alphaMap',
  396. 'envMap',
  397. 'envMapIntensity',
  398. 'refractionRatio',
  399. ],
  400. getMaterialType: function () {
  401. return THREE.ShaderMaterial;
  402. },
  403. extendParams: function ( materialParams, materialDef, parser ) {
  404. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  405. var shader = THREE.ShaderLib[ 'standard' ];
  406. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  407. var specularMapParsFragmentChunk = [
  408. '#ifdef USE_SPECULARMAP',
  409. ' uniform sampler2D specularMap;',
  410. '#endif'
  411. ].join( '\n' );
  412. var glossinessMapParsFragmentChunk = [
  413. '#ifdef USE_GLOSSINESSMAP',
  414. ' uniform sampler2D glossinessMap;',
  415. '#endif'
  416. ].join( '\n' );
  417. var specularMapFragmentChunk = [
  418. 'vec3 specularFactor = specular;',
  419. '#ifdef USE_SPECULARMAP',
  420. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  421. ' texelSpecular = sRGBToLinear( texelSpecular );',
  422. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  423. ' specularFactor *= texelSpecular.rgb;',
  424. '#endif'
  425. ].join( '\n' );
  426. var glossinessMapFragmentChunk = [
  427. 'float glossinessFactor = glossiness;',
  428. '#ifdef USE_GLOSSINESSMAP',
  429. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  430. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  431. ' glossinessFactor *= texelGlossiness.a;',
  432. '#endif'
  433. ].join( '\n' );
  434. var lightPhysicalFragmentChunk = [
  435. 'PhysicalMaterial material;',
  436. 'material.diffuseColor = diffuseColor.rgb;',
  437. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  438. 'material.specularColor = specularFactor.rgb;',
  439. ].join( '\n' );
  440. var fragmentShader = shader.fragmentShader
  441. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  442. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  443. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  444. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  445. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  446. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  447. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  448. delete uniforms.roughness;
  449. delete uniforms.metalness;
  450. delete uniforms.roughnessMap;
  451. delete uniforms.metalnessMap;
  452. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  453. uniforms.glossiness = { value: 0.5 };
  454. uniforms.specularMap = { value: null };
  455. uniforms.glossinessMap = { value: null };
  456. materialParams.vertexShader = shader.vertexShader;
  457. materialParams.fragmentShader = fragmentShader;
  458. materialParams.uniforms = uniforms;
  459. materialParams.defines = { 'STANDARD': '' };
  460. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  461. materialParams.opacity = 1.0;
  462. var pending = [];
  463. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  464. var array = pbrSpecularGlossiness.diffuseFactor;
  465. materialParams.color.fromArray( array );
  466. materialParams.opacity = array[ 3 ];
  467. }
  468. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  469. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  470. }
  471. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  472. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  473. materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  474. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  475. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  476. }
  477. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  478. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  479. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  480. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  481. }
  482. return Promise.all( pending );
  483. },
  484. createMaterial: function ( params ) {
  485. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  486. var material = new THREE.ShaderMaterial( {
  487. defines: params.defines,
  488. vertexShader: params.vertexShader,
  489. fragmentShader: params.fragmentShader,
  490. uniforms: params.uniforms,
  491. fog: true,
  492. lights: true,
  493. opacity: params.opacity,
  494. transparent: params.transparent
  495. } );
  496. material.isGLTFSpecularGlossinessMaterial = true;
  497. material.color = params.color;
  498. material.map = params.map === undefined ? null : params.map;
  499. material.lightMap = null;
  500. material.lightMapIntensity = 1.0;
  501. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  502. material.aoMapIntensity = 1.0;
  503. material.emissive = params.emissive;
  504. material.emissiveIntensity = 1.0;
  505. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  506. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  507. material.bumpScale = 1;
  508. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  509. if ( params.normalScale ) material.normalScale = params.normalScale;
  510. material.displacementMap = null;
  511. material.displacementScale = 1;
  512. material.displacementBias = 0;
  513. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  514. material.specular = params.specular;
  515. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  516. material.glossiness = params.glossiness;
  517. material.alphaMap = null;
  518. material.envMap = params.envMap === undefined ? null : params.envMap;
  519. material.envMapIntensity = 1.0;
  520. material.refractionRatio = 0.98;
  521. material.extensions.derivatives = true;
  522. return material;
  523. },
  524. /**
  525. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  526. * copy only properties it knows about or inherits, and misses many properties that would
  527. * normally be defined by MeshStandardMaterial.
  528. *
  529. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  530. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  531. * AND also updating `.onBeforeRender` on the parent mesh.
  532. *
  533. * @param {THREE.ShaderMaterial} source
  534. * @return {THREE.ShaderMaterial}
  535. */
  536. cloneMaterial: function ( source ) {
  537. var target = source.clone();
  538. target.isGLTFSpecularGlossinessMaterial = true;
  539. var params = this.specularGlossinessParams;
  540. for ( var i = 0, il = params.length; i < il; i ++ ) {
  541. var value = source[ params[ i ] ];
  542. target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value;
  543. }
  544. return target;
  545. },
  546. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  547. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  548. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  549. return;
  550. }
  551. var uniforms = material.uniforms;
  552. var defines = material.defines;
  553. uniforms.opacity.value = material.opacity;
  554. uniforms.diffuse.value.copy( material.color );
  555. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  556. uniforms.map.value = material.map;
  557. uniforms.specularMap.value = material.specularMap;
  558. uniforms.alphaMap.value = material.alphaMap;
  559. uniforms.lightMap.value = material.lightMap;
  560. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  561. uniforms.aoMap.value = material.aoMap;
  562. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  563. // uv repeat and offset setting priorities
  564. // 1. color map
  565. // 2. specular map
  566. // 3. normal map
  567. // 4. bump map
  568. // 5. alpha map
  569. // 6. emissive map
  570. var uvScaleMap;
  571. if ( material.map ) {
  572. uvScaleMap = material.map;
  573. } else if ( material.specularMap ) {
  574. uvScaleMap = material.specularMap;
  575. } else if ( material.displacementMap ) {
  576. uvScaleMap = material.displacementMap;
  577. } else if ( material.normalMap ) {
  578. uvScaleMap = material.normalMap;
  579. } else if ( material.bumpMap ) {
  580. uvScaleMap = material.bumpMap;
  581. } else if ( material.glossinessMap ) {
  582. uvScaleMap = material.glossinessMap;
  583. } else if ( material.alphaMap ) {
  584. uvScaleMap = material.alphaMap;
  585. } else if ( material.emissiveMap ) {
  586. uvScaleMap = material.emissiveMap;
  587. }
  588. if ( uvScaleMap !== undefined ) {
  589. // backwards compatibility
  590. if ( uvScaleMap.isWebGLRenderTarget ) {
  591. uvScaleMap = uvScaleMap.texture;
  592. }
  593. if ( uvScaleMap.matrixAutoUpdate === true ) {
  594. uvScaleMap.updateMatrix();
  595. }
  596. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  597. }
  598. if ( material.envMap ) {
  599. uniforms.envMap.value = material.envMap;
  600. uniforms.envMapIntensity.value = material.envMapIntensity;
  601. // don't flip CubeTexture envMaps, flip everything else:
  602. // WebGLRenderTargetCube will be flipped for backwards compatibility
  603. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  604. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  605. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  606. uniforms.reflectivity.value = material.reflectivity;
  607. uniforms.refractionRatio.value = material.refractionRatio;
  608. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  609. }
  610. uniforms.specular.value.copy( material.specular );
  611. uniforms.glossiness.value = material.glossiness;
  612. uniforms.glossinessMap.value = material.glossinessMap;
  613. uniforms.emissiveMap.value = material.emissiveMap;
  614. uniforms.bumpMap.value = material.bumpMap;
  615. uniforms.normalMap.value = material.normalMap;
  616. uniforms.displacementMap.value = material.displacementMap;
  617. uniforms.displacementScale.value = material.displacementScale;
  618. uniforms.displacementBias.value = material.displacementBias;
  619. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  620. defines.USE_GLOSSINESSMAP = '';
  621. // set USE_ROUGHNESSMAP to enable vUv
  622. defines.USE_ROUGHNESSMAP = '';
  623. }
  624. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  625. delete defines.USE_GLOSSINESSMAP;
  626. delete defines.USE_ROUGHNESSMAP;
  627. }
  628. }
  629. };
  630. }
  631. /*********************************/
  632. /********** INTERPOLATION ********/
  633. /*********************************/
  634. // Spline Interpolation
  635. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  636. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  637. THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  638. }
  639. GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype );
  640. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  641. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  642. // Copies a sample value to the result buffer. See description of glTF
  643. // CUBICSPLINE values layout in interpolate_() function below.
  644. var result = this.resultBuffer,
  645. values = this.sampleValues,
  646. valueSize = this.valueSize,
  647. offset = index * valueSize * 3 + valueSize;
  648. for ( var i = 0; i !== valueSize; i ++ ) {
  649. result[ i ] = values[ offset + i ];
  650. }
  651. return result;
  652. };
  653. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  654. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  655. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  656. var result = this.resultBuffer;
  657. var values = this.sampleValues;
  658. var stride = this.valueSize;
  659. var stride2 = stride * 2;
  660. var stride3 = stride * 3;
  661. var td = t1 - t0;
  662. var p = ( t - t0 ) / td;
  663. var pp = p * p;
  664. var ppp = pp * p;
  665. var offset1 = i1 * stride3;
  666. var offset0 = offset1 - stride3;
  667. var s2 = - 2 * ppp + 3 * pp;
  668. var s3 = ppp - pp;
  669. var s0 = 1 - s2;
  670. var s1 = s3 - pp + p;
  671. // Layout of keyframe output values for CUBICSPLINE animations:
  672. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  673. for ( var i = 0; i !== stride; i ++ ) {
  674. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  675. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  676. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  677. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  678. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  679. }
  680. return result;
  681. };
  682. /*********************************/
  683. /********** INTERNALS ************/
  684. /*********************************/
  685. /* CONSTANTS */
  686. var WEBGL_CONSTANTS = {
  687. FLOAT: 5126,
  688. //FLOAT_MAT2: 35674,
  689. FLOAT_MAT3: 35675,
  690. FLOAT_MAT4: 35676,
  691. FLOAT_VEC2: 35664,
  692. FLOAT_VEC3: 35665,
  693. FLOAT_VEC4: 35666,
  694. LINEAR: 9729,
  695. REPEAT: 10497,
  696. SAMPLER_2D: 35678,
  697. POINTS: 0,
  698. LINES: 1,
  699. LINE_LOOP: 2,
  700. LINE_STRIP: 3,
  701. TRIANGLES: 4,
  702. TRIANGLE_STRIP: 5,
  703. TRIANGLE_FAN: 6,
  704. UNSIGNED_BYTE: 5121,
  705. UNSIGNED_SHORT: 5123
  706. };
  707. var WEBGL_COMPONENT_TYPES = {
  708. 5120: Int8Array,
  709. 5121: Uint8Array,
  710. 5122: Int16Array,
  711. 5123: Uint16Array,
  712. 5125: Uint32Array,
  713. 5126: Float32Array
  714. };
  715. var WEBGL_FILTERS = {
  716. 9728: THREE.NearestFilter,
  717. 9729: THREE.LinearFilter,
  718. 9984: THREE.NearestMipMapNearestFilter,
  719. 9985: THREE.LinearMipMapNearestFilter,
  720. 9986: THREE.NearestMipMapLinearFilter,
  721. 9987: THREE.LinearMipMapLinearFilter
  722. };
  723. var WEBGL_WRAPPINGS = {
  724. 33071: THREE.ClampToEdgeWrapping,
  725. 33648: THREE.MirroredRepeatWrapping,
  726. 10497: THREE.RepeatWrapping
  727. };
  728. var WEBGL_TYPE_SIZES = {
  729. 'SCALAR': 1,
  730. 'VEC2': 2,
  731. 'VEC3': 3,
  732. 'VEC4': 4,
  733. 'MAT2': 4,
  734. 'MAT3': 9,
  735. 'MAT4': 16
  736. };
  737. var ATTRIBUTES = {
  738. POSITION: 'position',
  739. NORMAL: 'normal',
  740. TANGENT: 'tangent',
  741. TEXCOORD_0: 'uv',
  742. TEXCOORD_1: 'uv2',
  743. COLOR_0: 'color',
  744. WEIGHTS_0: 'skinWeight',
  745. JOINTS_0: 'skinIndex',
  746. };
  747. var PATH_PROPERTIES = {
  748. scale: 'scale',
  749. translation: 'position',
  750. rotation: 'quaternion',
  751. weights: 'morphTargetInfluences'
  752. };
  753. var INTERPOLATION = {
  754. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  755. // keyframe track will be initialized with a default interpolation type, then modified.
  756. LINEAR: THREE.InterpolateLinear,
  757. STEP: THREE.InterpolateDiscrete
  758. };
  759. var ALPHA_MODES = {
  760. OPAQUE: 'OPAQUE',
  761. MASK: 'MASK',
  762. BLEND: 'BLEND'
  763. };
  764. var MIME_TYPE_FORMATS = {
  765. 'image/png': THREE.RGBAFormat,
  766. 'image/jpeg': THREE.RGBFormat
  767. };
  768. /* UTILITY FUNCTIONS */
  769. function resolveURL( url, path ) {
  770. // Invalid URL
  771. if ( typeof url !== 'string' || url === '' ) return '';
  772. // Absolute URL http://,https://,//
  773. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  774. // Data URI
  775. if ( /^data:.*,.*$/i.test( url ) ) return url;
  776. // Blob URL
  777. if ( /^blob:.*$/i.test( url ) ) return url;
  778. // Relative URL
  779. return path + url;
  780. }
  781. var defaultMaterial;
  782. /**
  783. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  784. */
  785. function createDefaultMaterial() {
  786. defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( {
  787. color: 0xFFFFFF,
  788. emissive: 0x000000,
  789. metalness: 1,
  790. roughness: 1,
  791. transparent: false,
  792. depthTest: true,
  793. side: THREE.FrontSide
  794. } );
  795. return defaultMaterial;
  796. }
  797. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  798. // Add unknown glTF extensions to an object's userData.
  799. for ( var name in objectDef.extensions ) {
  800. if ( knownExtensions[ name ] === undefined ) {
  801. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  802. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  803. }
  804. }
  805. }
  806. /**
  807. * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object
  808. * @param {GLTF.definition} gltfDef
  809. */
  810. function assignExtrasToUserData( object, gltfDef ) {
  811. if ( gltfDef.extras !== undefined ) {
  812. if ( typeof gltfDef.extras === 'object' ) {
  813. Object.assign( object.userData, gltfDef.extras );
  814. } else {
  815. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  816. }
  817. }
  818. }
  819. /**
  820. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  821. *
  822. * @param {THREE.BufferGeometry} geometry
  823. * @param {Array<GLTF.Target>} targets
  824. * @param {GLTFParser} parser
  825. * @return {Promise<THREE.BufferGeometry>}
  826. */
  827. function addMorphTargets( geometry, targets, parser ) {
  828. var hasMorphPosition = false;
  829. var hasMorphNormal = false;
  830. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  831. var target = targets[ i ];
  832. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  833. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  834. if ( hasMorphPosition && hasMorphNormal ) break;
  835. }
  836. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  837. var pendingPositionAccessors = [];
  838. var pendingNormalAccessors = [];
  839. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  840. var target = targets[ i ];
  841. if ( hasMorphPosition ) {
  842. var pendingAccessor = target.POSITION !== undefined
  843. ? parser.getDependency( 'accessor', target.POSITION )
  844. : geometry.attributes.position;
  845. pendingPositionAccessors.push( pendingAccessor );
  846. }
  847. if ( hasMorphNormal ) {
  848. var pendingAccessor = target.NORMAL !== undefined
  849. ? parser.getDependency( 'accessor', target.NORMAL )
  850. : geometry.attributes.normal;
  851. pendingNormalAccessors.push( pendingAccessor );
  852. }
  853. }
  854. return Promise.all( [
  855. Promise.all( pendingPositionAccessors ),
  856. Promise.all( pendingNormalAccessors )
  857. ] ).then( function ( accessors ) {
  858. var morphPositions = accessors[ 0 ];
  859. var morphNormals = accessors[ 1 ];
  860. // Clone morph target accessors before modifying them.
  861. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  862. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  863. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  864. }
  865. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  866. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  867. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  868. }
  869. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  870. var target = targets[ i ];
  871. var attributeName = 'morphTarget' + i;
  872. if ( hasMorphPosition ) {
  873. // Three.js morph position is absolute value. The formula is
  874. // basePosition
  875. // + weight0 * ( morphPosition0 - basePosition )
  876. // + weight1 * ( morphPosition1 - basePosition )
  877. // ...
  878. // while the glTF one is relative
  879. // basePosition
  880. // + weight0 * glTFmorphPosition0
  881. // + weight1 * glTFmorphPosition1
  882. // ...
  883. // then we need to convert from relative to absolute here.
  884. if ( target.POSITION !== undefined ) {
  885. var positionAttribute = morphPositions[ i ];
  886. positionAttribute.name = attributeName;
  887. var position = geometry.attributes.position;
  888. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  889. positionAttribute.setXYZ(
  890. j,
  891. positionAttribute.getX( j ) + position.getX( j ),
  892. positionAttribute.getY( j ) + position.getY( j ),
  893. positionAttribute.getZ( j ) + position.getZ( j )
  894. );
  895. }
  896. }
  897. }
  898. if ( hasMorphNormal ) {
  899. // see target.POSITION's comment
  900. if ( target.NORMAL !== undefined ) {
  901. var normalAttribute = morphNormals[ i ];
  902. normalAttribute.name = attributeName;
  903. var normal = geometry.attributes.normal;
  904. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  905. normalAttribute.setXYZ(
  906. j,
  907. normalAttribute.getX( j ) + normal.getX( j ),
  908. normalAttribute.getY( j ) + normal.getY( j ),
  909. normalAttribute.getZ( j ) + normal.getZ( j )
  910. );
  911. }
  912. }
  913. }
  914. }
  915. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  916. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  917. return geometry;
  918. } );
  919. }
  920. /**
  921. * @param {THREE.Mesh} mesh
  922. * @param {GLTF.Mesh} meshDef
  923. */
  924. function updateMorphTargets( mesh, meshDef ) {
  925. mesh.updateMorphTargets();
  926. if ( meshDef.weights !== undefined ) {
  927. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  928. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  929. }
  930. }
  931. // .extras has user-defined data, so check that .extras.targetNames is an array.
  932. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  933. var targetNames = meshDef.extras.targetNames;
  934. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  935. mesh.morphTargetDictionary = {};
  936. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  937. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  938. }
  939. } else {
  940. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  941. }
  942. }
  943. }
  944. function createPrimitiveKey( primitiveDef ) {
  945. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  946. var geometryKey;
  947. if ( dracoExtension ) {
  948. geometryKey = 'draco:' + dracoExtension.bufferView
  949. + ':' + dracoExtension.indices
  950. + ':' + createAttributesKey( dracoExtension.attributes );
  951. } else {
  952. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  953. }
  954. return geometryKey;
  955. }
  956. function createAttributesKey( attributes ) {
  957. var attributesKey = '';
  958. var keys = Object.keys( attributes ).sort();
  959. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  960. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  961. }
  962. return attributesKey;
  963. }
  964. function cloneBufferAttribute( attribute ) {
  965. if ( attribute.isInterleavedBufferAttribute ) {
  966. var count = attribute.count;
  967. var itemSize = attribute.itemSize;
  968. var array = attribute.array.slice( 0, count * itemSize );
  969. for ( var i = 0, j = 0; i < count; ++ i ) {
  970. array[ j ++ ] = attribute.getX( i );
  971. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  972. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  973. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  974. }
  975. return new THREE.BufferAttribute( array, itemSize, attribute.normalized );
  976. }
  977. return attribute.clone();
  978. }
  979. /* GLTF PARSER */
  980. function GLTFParser( json, extensions, options ) {
  981. this.json = json || {};
  982. this.extensions = extensions || {};
  983. this.options = options || {};
  984. // loader object cache
  985. this.cache = new GLTFRegistry();
  986. // BufferGeometry caching
  987. this.primitiveCache = {};
  988. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  989. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  990. this.fileLoader = new THREE.FileLoader( this.options.manager );
  991. this.fileLoader.setResponseType( 'arraybuffer' );
  992. if ( this.options.crossOrigin === 'use-credentials' ) {
  993. this.fileLoader.setWithCredentials( true );
  994. }
  995. }
  996. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  997. var parser = this;
  998. var json = this.json;
  999. var extensions = this.extensions;
  1000. // Clear the loader cache
  1001. this.cache.removeAll();
  1002. // Mark the special nodes/meshes in json for efficient parse
  1003. this.markDefs();
  1004. Promise.all( [
  1005. this.getDependencies( 'scene' ),
  1006. this.getDependencies( 'animation' ),
  1007. this.getDependencies( 'camera' ),
  1008. ] ).then( function ( dependencies ) {
  1009. var result = {
  1010. scene: dependencies[ 0 ][ json.scene || 0 ],
  1011. scenes: dependencies[ 0 ],
  1012. animations: dependencies[ 1 ],
  1013. cameras: dependencies[ 2 ],
  1014. asset: json.asset,
  1015. parser: parser,
  1016. userData: {}
  1017. };
  1018. addUnknownExtensionsToUserData( extensions, result, json );
  1019. assignExtrasToUserData( result, json );
  1020. onLoad( result );
  1021. } ).catch( onError );
  1022. };
  1023. /**
  1024. * Marks the special nodes/meshes in json for efficient parse.
  1025. */
  1026. GLTFParser.prototype.markDefs = function () {
  1027. var nodeDefs = this.json.nodes || [];
  1028. var skinDefs = this.json.skins || [];
  1029. var meshDefs = this.json.meshes || [];
  1030. var meshReferences = {};
  1031. var meshUses = {};
  1032. // Nothing in the node definition indicates whether it is a Bone or an
  1033. // Object3D. Use the skins' joint references to mark bones.
  1034. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1035. var joints = skinDefs[ skinIndex ].joints;
  1036. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1037. nodeDefs[ joints[ i ] ].isBone = true;
  1038. }
  1039. }
  1040. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1041. // avoid having more than one THREE.Mesh with the same name, count
  1042. // references and rename instances below.
  1043. //
  1044. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1045. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1046. var nodeDef = nodeDefs[ nodeIndex ];
  1047. if ( nodeDef.mesh !== undefined ) {
  1048. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1049. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1050. }
  1051. meshReferences[ nodeDef.mesh ] ++;
  1052. // Nothing in the mesh definition indicates whether it is
  1053. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1054. // to mark SkinnedMesh if node has skin.
  1055. if ( nodeDef.skin !== undefined ) {
  1056. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1057. }
  1058. }
  1059. }
  1060. this.json.meshReferences = meshReferences;
  1061. this.json.meshUses = meshUses;
  1062. };
  1063. /**
  1064. * Requests the specified dependency asynchronously, with caching.
  1065. * @param {string} type
  1066. * @param {number} index
  1067. * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>}
  1068. */
  1069. GLTFParser.prototype.getDependency = function ( type, index ) {
  1070. var cacheKey = type + ':' + index;
  1071. var dependency = this.cache.get( cacheKey );
  1072. if ( ! dependency ) {
  1073. switch ( type ) {
  1074. case 'scene':
  1075. dependency = this.loadScene( index );
  1076. break;
  1077. case 'node':
  1078. dependency = this.loadNode( index );
  1079. break;
  1080. case 'mesh':
  1081. dependency = this.loadMesh( index );
  1082. break;
  1083. case 'accessor':
  1084. dependency = this.loadAccessor( index );
  1085. break;
  1086. case 'bufferView':
  1087. dependency = this.loadBufferView( index );
  1088. break;
  1089. case 'buffer':
  1090. dependency = this.loadBuffer( index );
  1091. break;
  1092. case 'material':
  1093. dependency = this.loadMaterial( index );
  1094. break;
  1095. case 'texture':
  1096. dependency = this.loadTexture( index );
  1097. break;
  1098. case 'skin':
  1099. dependency = this.loadSkin( index );
  1100. break;
  1101. case 'animation':
  1102. dependency = this.loadAnimation( index );
  1103. break;
  1104. case 'camera':
  1105. dependency = this.loadCamera( index );
  1106. break;
  1107. case 'light':
  1108. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1109. break;
  1110. default:
  1111. throw new Error( 'Unknown type: ' + type );
  1112. }
  1113. this.cache.add( cacheKey, dependency );
  1114. }
  1115. return dependency;
  1116. };
  1117. /**
  1118. * Requests all dependencies of the specified type asynchronously, with caching.
  1119. * @param {string} type
  1120. * @return {Promise<Array<Object>>}
  1121. */
  1122. GLTFParser.prototype.getDependencies = function ( type ) {
  1123. var dependencies = this.cache.get( type );
  1124. if ( ! dependencies ) {
  1125. var parser = this;
  1126. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1127. dependencies = Promise.all( defs.map( function ( def, index ) {
  1128. return parser.getDependency( type, index );
  1129. } ) );
  1130. this.cache.add( type, dependencies );
  1131. }
  1132. return dependencies;
  1133. };
  1134. /**
  1135. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1136. * @param {number} bufferIndex
  1137. * @return {Promise<ArrayBuffer>}
  1138. */
  1139. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1140. var bufferDef = this.json.buffers[ bufferIndex ];
  1141. var loader = this.fileLoader;
  1142. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1143. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1144. }
  1145. // If present, GLB container is required to be the first buffer.
  1146. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1147. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1148. }
  1149. var options = this.options;
  1150. return new Promise( function ( resolve, reject ) {
  1151. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1152. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1153. } );
  1154. } );
  1155. };
  1156. /**
  1157. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1158. * @param {number} bufferViewIndex
  1159. * @return {Promise<ArrayBuffer>}
  1160. */
  1161. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1162. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1163. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1164. var byteLength = bufferViewDef.byteLength || 0;
  1165. var byteOffset = bufferViewDef.byteOffset || 0;
  1166. return buffer.slice( byteOffset, byteOffset + byteLength );
  1167. } );
  1168. };
  1169. /**
  1170. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1171. * @param {number} accessorIndex
  1172. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  1173. */
  1174. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1175. var parser = this;
  1176. var json = this.json;
  1177. var accessorDef = this.json.accessors[ accessorIndex ];
  1178. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1179. // Ignore empty accessors, which may be used to declare runtime
  1180. // information about attributes coming from another source (e.g. Draco
  1181. // compression extension).
  1182. return Promise.resolve( null );
  1183. }
  1184. var pendingBufferViews = [];
  1185. if ( accessorDef.bufferView !== undefined ) {
  1186. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1187. } else {
  1188. pendingBufferViews.push( null );
  1189. }
  1190. if ( accessorDef.sparse !== undefined ) {
  1191. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1192. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1193. }
  1194. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1195. var bufferView = bufferViews[ 0 ];
  1196. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1197. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1198. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1199. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1200. var itemBytes = elementBytes * itemSize;
  1201. var byteOffset = accessorDef.byteOffset || 0;
  1202. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1203. var normalized = accessorDef.normalized === true;
  1204. var array, bufferAttribute;
  1205. // The buffer is not interleaved if the stride is the item size in bytes.
  1206. if ( byteStride && byteStride !== itemBytes ) {
  1207. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  1208. var ib = parser.cache.get( ibCacheKey );
  1209. if ( ! ib ) {
  1210. // Use the full buffer if it's interleaved.
  1211. array = new TypedArray( bufferView );
  1212. // Integer parameters to IB/IBA are in array elements, not bytes.
  1213. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  1214. parser.cache.add( ibCacheKey, ib );
  1215. }
  1216. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1217. } else {
  1218. if ( bufferView === null ) {
  1219. array = new TypedArray( accessorDef.count * itemSize );
  1220. } else {
  1221. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1222. }
  1223. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  1224. }
  1225. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1226. if ( accessorDef.sparse !== undefined ) {
  1227. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1228. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1229. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1230. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1231. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1232. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1233. if ( bufferView !== null ) {
  1234. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1235. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1236. }
  1237. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1238. var index = sparseIndices[ i ];
  1239. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1240. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1241. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1242. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1243. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1244. }
  1245. }
  1246. return bufferAttribute;
  1247. } );
  1248. };
  1249. /**
  1250. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1251. * @param {number} textureIndex
  1252. * @return {Promise<THREE.Texture>}
  1253. */
  1254. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1255. var parser = this;
  1256. var json = this.json;
  1257. var options = this.options;
  1258. var textureLoader = this.textureLoader;
  1259. var URL = window.URL || window.webkitURL;
  1260. var textureDef = json.textures[ textureIndex ];
  1261. var textureExtensions = textureDef.extensions || {};
  1262. var source;
  1263. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1264. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1265. } else {
  1266. source = json.images[ textureDef.source ];
  1267. }
  1268. var sourceURI = source.uri;
  1269. var isObjectURL = false;
  1270. if ( source.bufferView !== undefined ) {
  1271. // Load binary image data from bufferView, if provided.
  1272. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1273. isObjectURL = true;
  1274. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1275. sourceURI = URL.createObjectURL( blob );
  1276. return sourceURI;
  1277. } );
  1278. }
  1279. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1280. // Load Texture resource.
  1281. var loader = THREE.Loader.Handlers.get( sourceURI );
  1282. if ( ! loader ) {
  1283. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1284. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1285. : textureLoader;
  1286. }
  1287. return new Promise( function ( resolve, reject ) {
  1288. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1289. } );
  1290. } ).then( function ( texture ) {
  1291. // Clean up resources and configure Texture.
  1292. if ( isObjectURL === true ) {
  1293. URL.revokeObjectURL( sourceURI );
  1294. }
  1295. texture.flipY = false;
  1296. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1297. // Ignore unknown mime types, like DDS files.
  1298. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  1299. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  1300. }
  1301. var samplers = json.samplers || {};
  1302. var sampler = samplers[ textureDef.sampler ] || {};
  1303. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1304. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1305. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1306. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1307. return texture;
  1308. } );
  1309. };
  1310. /**
  1311. * Asynchronously assigns a texture to the given material parameters.
  1312. * @param {Object} materialParams
  1313. * @param {string} mapName
  1314. * @param {Object} mapDef
  1315. * @return {Promise}
  1316. */
  1317. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1318. var parser = this;
  1319. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1320. if ( ! texture.isCompressedTexture ) {
  1321. switch ( mapName ) {
  1322. case 'aoMap':
  1323. case 'emissiveMap':
  1324. case 'metalnessMap':
  1325. case 'normalMap':
  1326. case 'roughnessMap':
  1327. texture.format = THREE.RGBFormat;
  1328. break;
  1329. }
  1330. }
  1331. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1332. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1333. if ( transform ) {
  1334. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1335. }
  1336. }
  1337. materialParams[ mapName ] = texture;
  1338. } );
  1339. };
  1340. /**
  1341. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1342. * already has a material (generated from the glTF material options alone)
  1343. * but reuse of the same glTF material may require multiple threejs materials
  1344. * to accomodate different primitive types, defines, etc. New materials will
  1345. * be created if necessary, and reused from a cache.
  1346. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance.
  1347. */
  1348. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1349. var geometry = mesh.geometry;
  1350. var material = mesh.material;
  1351. var extensions = this.extensions;
  1352. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1353. var useVertexColors = geometry.attributes.color !== undefined;
  1354. var useFlatShading = geometry.attributes.normal === undefined;
  1355. var useSkinning = mesh.isSkinnedMesh === true;
  1356. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1357. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1358. if ( mesh.isPoints ) {
  1359. var cacheKey = 'PointsMaterial:' + material.uuid;
  1360. var pointsMaterial = this.cache.get( cacheKey );
  1361. if ( ! pointsMaterial ) {
  1362. pointsMaterial = new THREE.PointsMaterial();
  1363. THREE.Material.prototype.copy.call( pointsMaterial, material );
  1364. pointsMaterial.color.copy( material.color );
  1365. pointsMaterial.map = material.map;
  1366. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1367. this.cache.add( cacheKey, pointsMaterial );
  1368. }
  1369. material = pointsMaterial;
  1370. } else if ( mesh.isLine ) {
  1371. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1372. var lineMaterial = this.cache.get( cacheKey );
  1373. if ( ! lineMaterial ) {
  1374. lineMaterial = new THREE.LineBasicMaterial();
  1375. THREE.Material.prototype.copy.call( lineMaterial, material );
  1376. lineMaterial.color.copy( material.color );
  1377. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1378. this.cache.add( cacheKey, lineMaterial );
  1379. }
  1380. material = lineMaterial;
  1381. }
  1382. // Clone the material if it will be modified
  1383. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1384. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1385. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1386. if ( useSkinning ) cacheKey += 'skinning:';
  1387. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1388. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1389. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1390. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1391. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1392. var cachedMaterial = this.cache.get( cacheKey );
  1393. if ( ! cachedMaterial ) {
  1394. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  1395. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  1396. : material.clone();
  1397. if ( useSkinning ) cachedMaterial.skinning = true;
  1398. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1399. if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors;
  1400. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1401. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1402. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1403. this.cache.add( cacheKey, cachedMaterial );
  1404. }
  1405. material = cachedMaterial;
  1406. }
  1407. // workarounds for mesh and geometry
  1408. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1409. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1410. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1411. }
  1412. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1413. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  1414. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1415. }
  1416. mesh.material = material;
  1417. };
  1418. /**
  1419. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1420. * @param {number} materialIndex
  1421. * @return {Promise<THREE.Material>}
  1422. */
  1423. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1424. var parser = this;
  1425. var json = this.json;
  1426. var extensions = this.extensions;
  1427. var materialDef = json.materials[ materialIndex ];
  1428. var materialType;
  1429. var materialParams = {};
  1430. var materialExtensions = materialDef.extensions || {};
  1431. var pending = [];
  1432. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1433. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1434. materialType = sgExtension.getMaterialType();
  1435. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1436. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1437. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1438. materialType = kmuExtension.getMaterialType();
  1439. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1440. } else {
  1441. // Specification:
  1442. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1443. materialType = THREE.MeshStandardMaterial;
  1444. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1445. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1446. materialParams.opacity = 1.0;
  1447. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1448. var array = metallicRoughness.baseColorFactor;
  1449. materialParams.color.fromArray( array );
  1450. materialParams.opacity = array[ 3 ];
  1451. }
  1452. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1453. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1454. }
  1455. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1456. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1457. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1458. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1459. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1460. }
  1461. }
  1462. if ( materialDef.doubleSided === true ) {
  1463. materialParams.side = THREE.DoubleSide;
  1464. }
  1465. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1466. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1467. materialParams.transparent = true;
  1468. } else {
  1469. materialParams.transparent = false;
  1470. if ( alphaMode === ALPHA_MODES.MASK ) {
  1471. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1472. }
  1473. }
  1474. if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1475. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1476. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1477. if ( materialDef.normalTexture.scale !== undefined ) {
  1478. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1479. }
  1480. }
  1481. if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1482. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1483. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1484. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1485. }
  1486. }
  1487. if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1488. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  1489. }
  1490. if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) {
  1491. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1492. }
  1493. return Promise.all( pending ).then( function () {
  1494. var material;
  1495. if ( materialType === THREE.ShaderMaterial ) {
  1496. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1497. } else {
  1498. material = new materialType( materialParams );
  1499. }
  1500. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1501. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1502. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  1503. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  1504. if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding;
  1505. assignExtrasToUserData( material, materialDef );
  1506. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1507. return material;
  1508. } );
  1509. };
  1510. /**
  1511. * @param {THREE.BufferGeometry} geometry
  1512. * @param {GLTF.Primitive} primitiveDef
  1513. * @param {GLTFParser} parser
  1514. * @return {Promise<THREE.BufferGeometry>}
  1515. */
  1516. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1517. var attributes = primitiveDef.attributes;
  1518. var pending = [];
  1519. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1520. return parser.getDependency( 'accessor', accessorIndex )
  1521. .then( function ( accessor ) {
  1522. geometry.addAttribute( attributeName, accessor );
  1523. } );
  1524. }
  1525. for ( var gltfAttributeName in attributes ) {
  1526. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1527. // Skip attributes already provided by e.g. Draco extension.
  1528. if ( threeAttributeName in geometry.attributes ) continue;
  1529. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1530. }
  1531. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1532. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1533. geometry.setIndex( accessor );
  1534. } );
  1535. pending.push( accessor );
  1536. }
  1537. assignExtrasToUserData( geometry, primitiveDef );
  1538. return Promise.all( pending ).then( function () {
  1539. return primitiveDef.targets !== undefined
  1540. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1541. : geometry;
  1542. } );
  1543. }
  1544. /**
  1545. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1546. *
  1547. * Creates BufferGeometries from primitives.
  1548. *
  1549. * @param {Array<GLTF.Primitive>} primitives
  1550. * @return {Promise<Array<THREE.BufferGeometry>>}
  1551. */
  1552. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1553. var parser = this;
  1554. var extensions = this.extensions;
  1555. var cache = this.primitiveCache;
  1556. function createDracoPrimitive( primitive ) {
  1557. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1558. .decodePrimitive( primitive, parser )
  1559. .then( function ( geometry ) {
  1560. return addPrimitiveAttributes( geometry, primitive, parser );
  1561. } );
  1562. }
  1563. var pending = [];
  1564. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1565. var primitive = primitives[ i ];
  1566. var cacheKey = createPrimitiveKey( primitive );
  1567. // See if we've already created this geometry
  1568. var cached = cache[ cacheKey ];
  1569. if ( cached ) {
  1570. // Use the cached geometry if it exists
  1571. pending.push( cached.promise );
  1572. } else {
  1573. var geometryPromise;
  1574. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1575. // Use DRACO geometry if available
  1576. geometryPromise = createDracoPrimitive( primitive );
  1577. } else {
  1578. // Otherwise create a new geometry
  1579. geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser );
  1580. }
  1581. // Cache this geometry
  1582. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1583. pending.push( geometryPromise );
  1584. }
  1585. }
  1586. return Promise.all( pending );
  1587. };
  1588. /**
  1589. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1590. * @param {number} meshIndex
  1591. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  1592. */
  1593. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1594. var parser = this;
  1595. var json = this.json;
  1596. var meshDef = json.meshes[ meshIndex ];
  1597. var primitives = meshDef.primitives;
  1598. var pending = [];
  1599. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1600. var material = primitives[ i ].material === undefined
  1601. ? createDefaultMaterial()
  1602. : this.getDependency( 'material', primitives[ i ].material );
  1603. pending.push( material );
  1604. }
  1605. return Promise.all( pending ).then( function ( originalMaterials ) {
  1606. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  1607. var meshes = [];
  1608. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1609. var geometry = geometries[ i ];
  1610. var primitive = primitives[ i ];
  1611. // 1. create Mesh
  1612. var mesh;
  1613. var material = originalMaterials[ i ];
  1614. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1615. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1616. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1617. primitive.mode === undefined ) {
  1618. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1619. mesh = meshDef.isSkinnedMesh === true
  1620. ? new THREE.SkinnedMesh( geometry, material )
  1621. : new THREE.Mesh( geometry, material );
  1622. if ( mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized ) {
  1623. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  1624. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  1625. mesh.normalizeSkinWeights();
  1626. }
  1627. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1628. mesh.drawMode = THREE.TriangleStripDrawMode;
  1629. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1630. mesh.drawMode = THREE.TriangleFanDrawMode;
  1631. }
  1632. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1633. mesh = new THREE.LineSegments( geometry, material );
  1634. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1635. mesh = new THREE.Line( geometry, material );
  1636. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1637. mesh = new THREE.LineLoop( geometry, material );
  1638. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1639. mesh = new THREE.Points( geometry, material );
  1640. } else {
  1641. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1642. }
  1643. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1644. updateMorphTargets( mesh, meshDef );
  1645. }
  1646. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1647. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1648. assignExtrasToUserData( mesh, meshDef );
  1649. parser.assignFinalMaterial( mesh );
  1650. meshes.push( mesh );
  1651. }
  1652. if ( meshes.length === 1 ) {
  1653. return meshes[ 0 ];
  1654. }
  1655. var group = new THREE.Group();
  1656. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1657. group.add( meshes[ i ] );
  1658. }
  1659. return group;
  1660. } );
  1661. } );
  1662. };
  1663. /**
  1664. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1665. * @param {number} cameraIndex
  1666. * @return {Promise<THREE.Camera>}
  1667. */
  1668. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1669. var camera;
  1670. var cameraDef = this.json.cameras[ cameraIndex ];
  1671. var params = cameraDef[ cameraDef.type ];
  1672. if ( ! params ) {
  1673. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1674. return;
  1675. }
  1676. if ( cameraDef.type === 'perspective' ) {
  1677. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1678. } else if ( cameraDef.type === 'orthographic' ) {
  1679. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1680. }
  1681. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1682. assignExtrasToUserData( camera, cameraDef );
  1683. return Promise.resolve( camera );
  1684. };
  1685. /**
  1686. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1687. * @param {number} skinIndex
  1688. * @return {Promise<Object>}
  1689. */
  1690. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1691. var skinDef = this.json.skins[ skinIndex ];
  1692. var skinEntry = { joints: skinDef.joints };
  1693. if ( skinDef.inverseBindMatrices === undefined ) {
  1694. return Promise.resolve( skinEntry );
  1695. }
  1696. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1697. skinEntry.inverseBindMatrices = accessor;
  1698. return skinEntry;
  1699. } );
  1700. };
  1701. /**
  1702. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1703. * @param {number} animationIndex
  1704. * @return {Promise<THREE.AnimationClip>}
  1705. */
  1706. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1707. var json = this.json;
  1708. var animationDef = json.animations[ animationIndex ];
  1709. var pendingNodes = [];
  1710. var pendingInputAccessors = [];
  1711. var pendingOutputAccessors = [];
  1712. var pendingSamplers = [];
  1713. var pendingTargets = [];
  1714. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1715. var channel = animationDef.channels[ i ];
  1716. var sampler = animationDef.samplers[ channel.sampler ];
  1717. var target = channel.target;
  1718. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1719. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1720. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1721. pendingNodes.push( this.getDependency( 'node', name ) );
  1722. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1723. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1724. pendingSamplers.push( sampler );
  1725. pendingTargets.push( target );
  1726. }
  1727. return Promise.all( [
  1728. Promise.all( pendingNodes ),
  1729. Promise.all( pendingInputAccessors ),
  1730. Promise.all( pendingOutputAccessors ),
  1731. Promise.all( pendingSamplers ),
  1732. Promise.all( pendingTargets )
  1733. ] ).then( function ( dependencies ) {
  1734. var nodes = dependencies[ 0 ];
  1735. var inputAccessors = dependencies[ 1 ];
  1736. var outputAccessors = dependencies[ 2 ];
  1737. var samplers = dependencies[ 3 ];
  1738. var targets = dependencies[ 4 ];
  1739. var tracks = [];
  1740. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1741. var node = nodes[ i ];
  1742. var inputAccessor = inputAccessors[ i ];
  1743. var outputAccessor = outputAccessors[ i ];
  1744. var sampler = samplers[ i ];
  1745. var target = targets[ i ];
  1746. if ( node === undefined ) continue;
  1747. node.updateMatrix();
  1748. node.matrixAutoUpdate = true;
  1749. var TypedKeyframeTrack;
  1750. switch ( PATH_PROPERTIES[ target.path ] ) {
  1751. case PATH_PROPERTIES.weights:
  1752. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1753. break;
  1754. case PATH_PROPERTIES.rotation:
  1755. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1756. break;
  1757. case PATH_PROPERTIES.position:
  1758. case PATH_PROPERTIES.scale:
  1759. default:
  1760. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1761. break;
  1762. }
  1763. var targetName = node.name ? node.name : node.uuid;
  1764. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1765. var targetNames = [];
  1766. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1767. // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh.
  1768. node.traverse( function ( object ) {
  1769. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1770. targetNames.push( object.name ? object.name : object.uuid );
  1771. }
  1772. } );
  1773. } else {
  1774. targetNames.push( targetName );
  1775. }
  1776. var outputArray = outputAccessor.array;
  1777. if ( outputAccessor.normalized ) {
  1778. var scale;
  1779. if ( outputArray.constructor === Int8Array ) {
  1780. scale = 1 / 127;
  1781. } else if ( outputArray.constructor === Uint8Array ) {
  1782. scale = 1 / 255;
  1783. } else if ( outputArray.constructor == Int16Array ) {
  1784. scale = 1 / 32767;
  1785. } else if ( outputArray.constructor === Uint16Array ) {
  1786. scale = 1 / 65535;
  1787. } else {
  1788. throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' );
  1789. }
  1790. var scaled = new Float32Array( outputArray.length );
  1791. for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) {
  1792. scaled[j] = outputArray[j] * scale;
  1793. }
  1794. outputArray = scaled;
  1795. }
  1796. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1797. var track = new TypedKeyframeTrack(
  1798. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1799. inputAccessor.array,
  1800. outputArray,
  1801. interpolation
  1802. );
  1803. // Override interpolation with custom factory method.
  1804. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1805. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1806. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1807. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1808. // must be divided by three to get the interpolant's sampleSize argument.
  1809. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1810. };
  1811. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  1812. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1813. }
  1814. tracks.push( track );
  1815. }
  1816. }
  1817. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1818. return new THREE.AnimationClip( name, undefined, tracks );
  1819. } );
  1820. };
  1821. /**
  1822. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1823. * @param {number} nodeIndex
  1824. * @return {Promise<THREE.Object3D>}
  1825. */
  1826. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1827. var json = this.json;
  1828. var extensions = this.extensions;
  1829. var parser = this;
  1830. var meshReferences = json.meshReferences;
  1831. var meshUses = json.meshUses;
  1832. var nodeDef = json.nodes[ nodeIndex ];
  1833. return ( function () {
  1834. // .isBone isn't in glTF spec. See .markDefs
  1835. if ( nodeDef.isBone === true ) {
  1836. return Promise.resolve( new THREE.Bone() );
  1837. } else if ( nodeDef.mesh !== undefined ) {
  1838. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1839. var node;
  1840. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1841. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1842. node = mesh.clone();
  1843. node.name += '_instance_' + instanceNum;
  1844. // onBeforeRender copy for Specular-Glossiness
  1845. node.onBeforeRender = mesh.onBeforeRender;
  1846. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  1847. node.children[ i ].name += '_instance_' + instanceNum;
  1848. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  1849. }
  1850. } else {
  1851. node = mesh;
  1852. }
  1853. // if weights are provided on the node, override weights on the mesh.
  1854. if ( nodeDef.weights !== undefined ) {
  1855. node.traverse( function ( o ) {
  1856. if ( ! o.isMesh ) return;
  1857. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  1858. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  1859. }
  1860. } );
  1861. }
  1862. return node;
  1863. } );
  1864. } else if ( nodeDef.camera !== undefined ) {
  1865. return parser.getDependency( 'camera', nodeDef.camera );
  1866. } else if ( nodeDef.extensions
  1867. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1868. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1869. return parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  1870. } else {
  1871. return Promise.resolve( new THREE.Object3D() );
  1872. }
  1873. }() ).then( function ( node ) {
  1874. if ( nodeDef.name !== undefined ) {
  1875. node.userData.name = nodeDef.name;
  1876. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1877. }
  1878. assignExtrasToUserData( node, nodeDef );
  1879. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  1880. if ( nodeDef.matrix !== undefined ) {
  1881. var matrix = new THREE.Matrix4();
  1882. matrix.fromArray( nodeDef.matrix );
  1883. node.applyMatrix( matrix );
  1884. } else {
  1885. if ( nodeDef.translation !== undefined ) {
  1886. node.position.fromArray( nodeDef.translation );
  1887. }
  1888. if ( nodeDef.rotation !== undefined ) {
  1889. node.quaternion.fromArray( nodeDef.rotation );
  1890. }
  1891. if ( nodeDef.scale !== undefined ) {
  1892. node.scale.fromArray( nodeDef.scale );
  1893. }
  1894. }
  1895. return node;
  1896. } );
  1897. };
  1898. /**
  1899. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  1900. * @param {number} sceneIndex
  1901. * @return {Promise<THREE.Scene>}
  1902. */
  1903. GLTFParser.prototype.loadScene = function () {
  1904. // scene node hierachy builder
  1905. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  1906. var nodeDef = json.nodes[ nodeId ];
  1907. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  1908. if ( nodeDef.skin === undefined ) return node;
  1909. // build skeleton here as well
  1910. var skinEntry;
  1911. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  1912. skinEntry = skin;
  1913. var pendingJoints = [];
  1914. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  1915. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  1916. }
  1917. return Promise.all( pendingJoints );
  1918. } ).then( function ( jointNodes ) {
  1919. var meshes = node.isGroup === true ? node.children : [ node ];
  1920. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1921. var mesh = meshes[ i ];
  1922. var bones = [];
  1923. var boneInverses = [];
  1924. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  1925. var jointNode = jointNodes[ j ];
  1926. if ( jointNode ) {
  1927. bones.push( jointNode );
  1928. var mat = new THREE.Matrix4();
  1929. if ( skinEntry.inverseBindMatrices !== undefined ) {
  1930. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  1931. }
  1932. boneInverses.push( mat );
  1933. } else {
  1934. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  1935. }
  1936. }
  1937. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  1938. }
  1939. return node;
  1940. } );
  1941. } ).then( function ( node ) {
  1942. // build node hierachy
  1943. parentObject.add( node );
  1944. var pending = [];
  1945. if ( nodeDef.children ) {
  1946. var children = nodeDef.children;
  1947. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1948. var child = children[ i ];
  1949. pending.push( buildNodeHierachy( child, node, json, parser ) );
  1950. }
  1951. }
  1952. return Promise.all( pending );
  1953. } );
  1954. }
  1955. return function loadScene( sceneIndex ) {
  1956. var json = this.json;
  1957. var extensions = this.extensions;
  1958. var sceneDef = this.json.scenes[ sceneIndex ];
  1959. var parser = this;
  1960. var scene = new THREE.Scene();
  1961. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  1962. assignExtrasToUserData( scene, sceneDef );
  1963. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  1964. var nodeIds = sceneDef.nodes || [];
  1965. var pending = [];
  1966. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  1967. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  1968. }
  1969. return Promise.all( pending ).then( function () {
  1970. return scene;
  1971. } );
  1972. };
  1973. }();
  1974. return GLTFLoader;
  1975. } )();