GLTFLoader.js 80 KB

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