GLTFLoader.js 79 KB

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