GLTFLoader.js 81 KB

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