GLTFLoader.js 82 KB

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