GLTFLoader.js 82 KB

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