GLTFLoader.js 86 KB

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