2
0

GLTFLoader.js 82 KB

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