GLTFLoader.js 79 KB

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