GLTFLoader.js 78 KB

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