GLTFLoader.js 84 KB

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