GLTFLoader.js 79 KB

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