GLTFLoader.js 82 KB

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