GLTFLoader.js 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511
  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. THREE.GLTFLoader = ( function () {
  9. function GLTFLoader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. }
  12. GLTFLoader.prototype = {
  13. constructor: GLTFLoader,
  14. crossOrigin: 'Anonymous',
  15. load: function ( url, onLoad, onProgress, onError ) {
  16. var scope = this;
  17. var path = this.path !== undefined ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  18. var loader = new THREE.FileLoader( scope.manager );
  19. loader.setResponseType( 'arraybuffer' );
  20. loader.load( url, function ( data ) {
  21. try {
  22. scope.parse( data, path, onLoad, onError );
  23. } catch ( e ) {
  24. if ( onError !== undefined ) {
  25. // For SyntaxError or TypeError, return a generic failure message.
  26. onError( e.constructor === Error ? e : new Error( 'THREE.GLTFLoader: Unable to parse model.' ) );
  27. }
  28. }
  29. }, onProgress, onError );
  30. },
  31. setCrossOrigin: function ( value ) {
  32. this.crossOrigin = value;
  33. },
  34. setPath: function ( value ) {
  35. this.path = value;
  36. },
  37. parse: function ( data, path, onLoad, onError ) {
  38. var content;
  39. var extensions = {};
  40. if ( typeof data === 'string' ) {
  41. content = data;
  42. } else {
  43. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  44. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  45. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  46. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  47. } else {
  48. content = convertUint8ArrayToString( new Uint8Array( data ) );
  49. }
  50. }
  51. var json = JSON.parse( content );
  52. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  53. onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.' ) );
  54. return;
  55. }
  56. if ( json.extensionsUsed ) {
  57. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  58. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  59. }
  60. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  61. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  62. }
  63. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  64. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  65. }
  66. }
  67. console.time( 'GLTFLoader' );
  68. var parser = new GLTFParser( json, extensions, {
  69. path: path || this.path || '',
  70. crossOrigin: this.crossOrigin,
  71. manager: this.manager
  72. } );
  73. parser.parse( function ( scene, scenes, cameras, animations ) {
  74. console.timeEnd( 'GLTFLoader' );
  75. var glTF = {
  76. scene: scene,
  77. scenes: scenes,
  78. cameras: cameras,
  79. animations: animations
  80. };
  81. onLoad( glTF );
  82. }, onError );
  83. }
  84. };
  85. /* GLTFREGISTRY */
  86. function GLTFRegistry() {
  87. var objects = {};
  88. return {
  89. get: function ( key ) {
  90. return objects[ key ];
  91. },
  92. add: function ( key, object ) {
  93. objects[ key ] = object;
  94. },
  95. remove: function ( key ) {
  96. delete objects[ key ];
  97. },
  98. removeAll: function () {
  99. objects = {};
  100. }
  101. };
  102. }
  103. /*********************************/
  104. /********** EXTENSIONS ***********/
  105. /*********************************/
  106. var EXTENSIONS = {
  107. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  108. KHR_LIGHTS: 'KHR_lights',
  109. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  110. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
  111. };
  112. /**
  113. * Lights Extension
  114. *
  115. * Specification: PENDING
  116. */
  117. function GLTFLightsExtension( json ) {
  118. this.name = EXTENSIONS.KHR_LIGHTS;
  119. this.lights = {};
  120. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  121. var lights = extension.lights || {};
  122. for ( var lightId in lights ) {
  123. var light = lights[ lightId ];
  124. var lightNode;
  125. var color = new THREE.Color().fromArray( light.color );
  126. switch ( light.type ) {
  127. case 'directional':
  128. lightNode = new THREE.DirectionalLight( color );
  129. lightNode.position.set( 0, 0, 1 );
  130. break;
  131. case 'point':
  132. lightNode = new THREE.PointLight( color );
  133. break;
  134. case 'spot':
  135. lightNode = new THREE.SpotLight( color );
  136. lightNode.position.set( 0, 0, 1 );
  137. break;
  138. case 'ambient':
  139. lightNode = new THREE.AmbientLight( color );
  140. break;
  141. }
  142. if ( lightNode ) {
  143. if ( light.constantAttenuation !== undefined ) {
  144. lightNode.intensity = light.constantAttenuation;
  145. }
  146. if ( light.linearAttenuation !== undefined ) {
  147. lightNode.distance = 1 / light.linearAttenuation;
  148. }
  149. if ( light.quadraticAttenuation !== undefined ) {
  150. lightNode.decay = light.quadraticAttenuation;
  151. }
  152. if ( light.fallOffAngle !== undefined ) {
  153. lightNode.angle = light.fallOffAngle;
  154. }
  155. if ( light.fallOffExponent !== undefined ) {
  156. console.warn( 'THREE.GLTFLoader:: light.fallOffExponent not currently supported.' );
  157. }
  158. lightNode.name = light.name || ( 'light_' + lightId );
  159. this.lights[ lightId ] = lightNode;
  160. }
  161. }
  162. }
  163. /**
  164. * Common Materials Extension
  165. *
  166. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
  167. */
  168. function GLTFMaterialsCommonExtension( json ) {
  169. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  170. }
  171. GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {
  172. var khrMaterial = material.extensions[ this.name ];
  173. switch ( khrMaterial.type ) {
  174. case 'commonBlinn' :
  175. case 'commonPhong' :
  176. return THREE.MeshPhongMaterial;
  177. case 'commonLambert' :
  178. return THREE.MeshLambertMaterial;
  179. case 'commonConstant' :
  180. default :
  181. return THREE.MeshBasicMaterial;
  182. }
  183. };
  184. GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  185. var khrMaterial = material.extensions[ this.name ];
  186. var pending = [];
  187. var keys = [];
  188. // TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
  189. switch ( khrMaterial.type ) {
  190. case 'commonBlinn' :
  191. case 'commonPhong' :
  192. keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
  193. break;
  194. case 'commonLambert' :
  195. keys.push( 'diffuseFactor', 'diffuseTexture' );
  196. break;
  197. case 'commonConstant' :
  198. default :
  199. break;
  200. }
  201. var materialValues = {};
  202. keys.forEach( function ( v ) {
  203. if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];
  204. } );
  205. if ( materialValues.diffuseFactor !== undefined ) {
  206. materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
  207. materialParams.opacity = materialValues.diffuseFactor[ 3 ];
  208. }
  209. if ( materialValues.diffuseTexture !== undefined ) {
  210. pending.push( parser.assignTexture( materialParams, 'map', materialValues.diffuseTexture.index ) );
  211. }
  212. if ( materialValues.specularFactor !== undefined ) {
  213. materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );
  214. }
  215. if ( materialValues.specularTexture !== undefined ) {
  216. pending.push( parser.assignTexture( materialParams, 'specularMap', materialValues.specularTexture.index ) );
  217. }
  218. if ( materialValues.shininessFactor !== undefined ) {
  219. materialParams.shininess = materialValues.shininessFactor;
  220. }
  221. return Promise.all( pending );
  222. };
  223. /* BINARY EXTENSION */
  224. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  225. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  226. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  227. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  228. function GLTFBinaryExtension( data ) {
  229. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  230. this.content = null;
  231. this.body = null;
  232. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  233. this.header = {
  234. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  235. version: headerView.getUint32( 4, true ),
  236. length: headerView.getUint32( 8, true )
  237. };
  238. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  239. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  240. } else if ( this.header.version < 2.0 ) {
  241. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use GLTFLoader instead.' );
  242. }
  243. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  244. var chunkIndex = 0;
  245. while ( chunkIndex < chunkView.byteLength ) {
  246. var chunkLength = chunkView.getUint32( chunkIndex, true );
  247. chunkIndex += 4;
  248. var chunkType = chunkView.getUint32( chunkIndex, true );
  249. chunkIndex += 4;
  250. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  251. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  252. this.content = convertUint8ArrayToString( contentArray );
  253. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  254. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  255. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  256. }
  257. // Clients must ignore chunks with unknown types.
  258. chunkIndex += chunkLength;
  259. }
  260. if ( this.content === null ) {
  261. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  262. }
  263. }
  264. /**
  265. * Specular-Glossiness Extension
  266. *
  267. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  268. */
  269. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  270. return {
  271. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  272. specularGlossinessParams: [
  273. 'color',
  274. 'map',
  275. 'lightMap',
  276. 'lightMapIntensity',
  277. 'aoMap',
  278. 'aoMapIntensity',
  279. 'emissive',
  280. 'emissiveIntensity',
  281. 'emissiveMap',
  282. 'bumpMap',
  283. 'bumpScale',
  284. 'normalMap',
  285. 'displacementMap',
  286. 'displacementScale',
  287. 'displacementBias',
  288. 'specularMap',
  289. 'specular',
  290. 'glossinessMap',
  291. 'glossiness',
  292. 'alphaMap',
  293. 'envMap',
  294. 'envMapIntensity',
  295. 'refractionRatio',
  296. ],
  297. getMaterialType: function () {
  298. return THREE.ShaderMaterial;
  299. },
  300. extendParams: function ( params, material, parser ) {
  301. var pbrSpecularGlossiness = material.extensions[ this.name ];
  302. var shader = THREE.ShaderLib[ 'standard' ];
  303. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  304. var specularMapParsFragmentChunk = [
  305. '#ifdef USE_SPECULARMAP',
  306. ' uniform sampler2D specularMap;',
  307. '#endif'
  308. ].join( '\n' );
  309. var glossinessMapParsFragmentChunk = [
  310. '#ifdef USE_GLOSSINESSMAP',
  311. ' uniform sampler2D glossinessMap;',
  312. '#endif'
  313. ].join( '\n' );
  314. var specularMapFragmentChunk = [
  315. 'vec3 specularFactor = specular;',
  316. '#ifdef USE_SPECULARMAP',
  317. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  318. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  319. ' specularFactor *= texelSpecular.rgb;',
  320. '#endif'
  321. ].join( '\n' );
  322. var glossinessMapFragmentChunk = [
  323. 'float glossinessFactor = glossiness;',
  324. '#ifdef USE_GLOSSINESSMAP',
  325. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  326. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  327. ' glossinessFactor *= texelGlossiness.a;',
  328. '#endif'
  329. ].join( '\n' );
  330. var lightPhysicalFragmentChunk = [
  331. 'PhysicalMaterial material;',
  332. 'material.diffuseColor = diffuseColor.rgb;',
  333. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  334. 'material.specularColor = specularFactor.rgb;',
  335. ].join( '\n' );
  336. var fragmentShader = shader.fragmentShader
  337. .replace( '#include <specularmap_fragment>', '' )
  338. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  339. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  340. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  341. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  342. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  343. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  344. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  345. delete uniforms.roughness;
  346. delete uniforms.metalness;
  347. delete uniforms.roughnessMap;
  348. delete uniforms.metalnessMap;
  349. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  350. uniforms.glossiness = { value: 0.5 };
  351. uniforms.specularMap = { value: null };
  352. uniforms.glossinessMap = { value: null };
  353. params.vertexShader = shader.vertexShader;
  354. params.fragmentShader = fragmentShader;
  355. params.uniforms = uniforms;
  356. params.defines = { 'STANDARD': '' };
  357. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  358. params.opacity = 1.0;
  359. var pending = [];
  360. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  361. var array = pbrSpecularGlossiness.diffuseFactor;
  362. params.color.fromArray( array );
  363. params.opacity = array[ 3 ];
  364. }
  365. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  366. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  367. }
  368. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  369. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  370. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  371. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  372. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  373. }
  374. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  375. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  376. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  377. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  378. }
  379. return Promise.all( pending );
  380. },
  381. createMaterial: function ( params ) {
  382. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  383. var material = new THREE.ShaderMaterial( {
  384. defines: params.defines,
  385. vertexShader: params.vertexShader,
  386. fragmentShader: params.fragmentShader,
  387. uniforms: params.uniforms,
  388. fog: true,
  389. lights: true,
  390. opacity: params.opacity,
  391. transparent: params.transparent
  392. } );
  393. material.isGLTFSpecularGlossinessMaterial = true;
  394. material.color = params.color;
  395. material.map = params.map === undefined ? null : params.map;
  396. material.lightMap = null;
  397. material.lightMapIntensity = 1.0;
  398. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  399. material.aoMapIntensity = 1.0;
  400. material.emissive = params.emissive;
  401. material.emissiveIntensity = 1.0;
  402. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  403. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  404. material.bumpScale = 1;
  405. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  406. if ( params.normalScale ) material.normalScale = params.normalScale;
  407. material.displacementMap = null;
  408. material.displacementScale = 1;
  409. material.displacementBias = 0;
  410. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  411. material.specular = params.specular;
  412. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  413. material.glossiness = params.glossiness;
  414. material.alphaMap = null;
  415. material.envMap = params.envMap === undefined ? null : params.envMap;
  416. material.envMapIntensity = 1.0;
  417. material.refractionRatio = 0.98;
  418. material.extensions.derivatives = true;
  419. return material;
  420. },
  421. /**
  422. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  423. * copy only properties it knows about or inherits, and misses many properties that would
  424. * normally be defined by MeshStandardMaterial.
  425. *
  426. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  427. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  428. * AND also updating `.onBeforeRender` on the parent mesh.
  429. *
  430. * @param {THREE.ShaderMaterial} source
  431. * @return {THREE.ShaderMaterial}
  432. */
  433. cloneMaterial: function ( source ) {
  434. var target = source.clone();
  435. target.isGLTFSpecularGlossinessMaterial = true;
  436. var params = this.specularGlossinessParams;
  437. for ( var i = 0; i < params.length; i ++ ) {
  438. target[ params[ i ] ] = source[ params[ i ] ];
  439. }
  440. return target;
  441. },
  442. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  443. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  444. var uniforms = material.uniforms;
  445. var defines = material.defines;
  446. uniforms.opacity.value = material.opacity;
  447. uniforms.diffuse.value.copy( material.color );
  448. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  449. uniforms.map.value = material.map;
  450. uniforms.specularMap.value = material.specularMap;
  451. uniforms.alphaMap.value = material.alphaMap;
  452. uniforms.lightMap.value = material.lightMap;
  453. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  454. uniforms.aoMap.value = material.aoMap;
  455. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  456. // uv repeat and offset setting priorities
  457. // 1. color map
  458. // 2. specular map
  459. // 3. normal map
  460. // 4. bump map
  461. // 5. alpha map
  462. // 6. emissive map
  463. var uvScaleMap;
  464. if ( material.map ) {
  465. uvScaleMap = material.map;
  466. } else if ( material.specularMap ) {
  467. uvScaleMap = material.specularMap;
  468. } else if ( material.displacementMap ) {
  469. uvScaleMap = material.displacementMap;
  470. } else if ( material.normalMap ) {
  471. uvScaleMap = material.normalMap;
  472. } else if ( material.bumpMap ) {
  473. uvScaleMap = material.bumpMap;
  474. } else if ( material.glossinessMap ) {
  475. uvScaleMap = material.glossinessMap;
  476. } else if ( material.alphaMap ) {
  477. uvScaleMap = material.alphaMap;
  478. } else if ( material.emissiveMap ) {
  479. uvScaleMap = material.emissiveMap;
  480. }
  481. if ( uvScaleMap !== undefined ) {
  482. // backwards compatibility
  483. if ( uvScaleMap.isWebGLRenderTarget ) {
  484. uvScaleMap = uvScaleMap.texture;
  485. }
  486. var offset;
  487. var repeat;
  488. if ( uvScaleMap.matrix !== undefined ) {
  489. // > r88.
  490. if ( uvScaleMap.matrixAutoUpdate === true ) {
  491. offset = uvScaleMap.offset;
  492. repeat = uvScaleMap.repeat;
  493. var rotation = uvScaleMap.rotation;
  494. var center = uvScaleMap.center;
  495. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  496. }
  497. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  498. } else {
  499. // <= r87. Remove when reasonable.
  500. offset = uvScaleMap.offset;
  501. repeat = uvScaleMap.repeat;
  502. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  503. }
  504. }
  505. uniforms.envMap.value = material.envMap;
  506. uniforms.envMapIntensity.value = material.envMapIntensity;
  507. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  508. uniforms.refractionRatio.value = material.refractionRatio;
  509. uniforms.specular.value.copy( material.specular );
  510. uniforms.glossiness.value = material.glossiness;
  511. uniforms.glossinessMap.value = material.glossinessMap;
  512. uniforms.emissiveMap.value = material.emissiveMap;
  513. uniforms.bumpMap.value = material.bumpMap;
  514. uniforms.normalMap.value = material.normalMap;
  515. uniforms.displacementMap.value = material.displacementMap;
  516. uniforms.displacementScale.value = material.displacementScale;
  517. uniforms.displacementBias.value = material.displacementBias;
  518. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  519. defines.USE_GLOSSINESSMAP = '';
  520. // set USE_ROUGHNESSMAP to enable vUv
  521. defines.USE_ROUGHNESSMAP = '';
  522. }
  523. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  524. delete defines.USE_GLOSSINESSMAP;
  525. delete defines.USE_ROUGHNESSMAP;
  526. }
  527. }
  528. };
  529. }
  530. /*********************************/
  531. /********** INTERNALS ************/
  532. /*********************************/
  533. /* CONSTANTS */
  534. var WEBGL_CONSTANTS = {
  535. FLOAT: 5126,
  536. //FLOAT_MAT2: 35674,
  537. FLOAT_MAT3: 35675,
  538. FLOAT_MAT4: 35676,
  539. FLOAT_VEC2: 35664,
  540. FLOAT_VEC3: 35665,
  541. FLOAT_VEC4: 35666,
  542. LINEAR: 9729,
  543. REPEAT: 10497,
  544. SAMPLER_2D: 35678,
  545. POINTS: 0,
  546. LINES: 1,
  547. LINE_LOOP: 2,
  548. LINE_STRIP: 3,
  549. TRIANGLES: 4,
  550. TRIANGLE_STRIP: 5,
  551. TRIANGLE_FAN: 6,
  552. UNSIGNED_BYTE: 5121,
  553. UNSIGNED_SHORT: 5123
  554. };
  555. var WEBGL_TYPE = {
  556. 5126: Number,
  557. //35674: THREE.Matrix2,
  558. 35675: THREE.Matrix3,
  559. 35676: THREE.Matrix4,
  560. 35664: THREE.Vector2,
  561. 35665: THREE.Vector3,
  562. 35666: THREE.Vector4,
  563. 35678: THREE.Texture
  564. };
  565. var WEBGL_COMPONENT_TYPES = {
  566. 5120: Int8Array,
  567. 5121: Uint8Array,
  568. 5122: Int16Array,
  569. 5123: Uint16Array,
  570. 5125: Uint32Array,
  571. 5126: Float32Array
  572. };
  573. var WEBGL_FILTERS = {
  574. 9728: THREE.NearestFilter,
  575. 9729: THREE.LinearFilter,
  576. 9984: THREE.NearestMipMapNearestFilter,
  577. 9985: THREE.LinearMipMapNearestFilter,
  578. 9986: THREE.NearestMipMapLinearFilter,
  579. 9987: THREE.LinearMipMapLinearFilter
  580. };
  581. var WEBGL_WRAPPINGS = {
  582. 33071: THREE.ClampToEdgeWrapping,
  583. 33648: THREE.MirroredRepeatWrapping,
  584. 10497: THREE.RepeatWrapping
  585. };
  586. var WEBGL_TEXTURE_FORMATS = {
  587. 6406: THREE.AlphaFormat,
  588. 6407: THREE.RGBFormat,
  589. 6408: THREE.RGBAFormat,
  590. 6409: THREE.LuminanceFormat,
  591. 6410: THREE.LuminanceAlphaFormat
  592. };
  593. var WEBGL_TEXTURE_DATATYPES = {
  594. 5121: THREE.UnsignedByteType,
  595. 32819: THREE.UnsignedShort4444Type,
  596. 32820: THREE.UnsignedShort5551Type,
  597. 33635: THREE.UnsignedShort565Type
  598. };
  599. var WEBGL_SIDES = {
  600. 1028: THREE.BackSide, // Culling front
  601. 1029: THREE.FrontSide // Culling back
  602. //1032: THREE.NoSide // Culling front and back, what to do?
  603. };
  604. var WEBGL_DEPTH_FUNCS = {
  605. 512: THREE.NeverDepth,
  606. 513: THREE.LessDepth,
  607. 514: THREE.EqualDepth,
  608. 515: THREE.LessEqualDepth,
  609. 516: THREE.GreaterEqualDepth,
  610. 517: THREE.NotEqualDepth,
  611. 518: THREE.GreaterEqualDepth,
  612. 519: THREE.AlwaysDepth
  613. };
  614. var WEBGL_BLEND_EQUATIONS = {
  615. 32774: THREE.AddEquation,
  616. 32778: THREE.SubtractEquation,
  617. 32779: THREE.ReverseSubtractEquation
  618. };
  619. var WEBGL_BLEND_FUNCS = {
  620. 0: THREE.ZeroFactor,
  621. 1: THREE.OneFactor,
  622. 768: THREE.SrcColorFactor,
  623. 769: THREE.OneMinusSrcColorFactor,
  624. 770: THREE.SrcAlphaFactor,
  625. 771: THREE.OneMinusSrcAlphaFactor,
  626. 772: THREE.DstAlphaFactor,
  627. 773: THREE.OneMinusDstAlphaFactor,
  628. 774: THREE.DstColorFactor,
  629. 775: THREE.OneMinusDstColorFactor,
  630. 776: THREE.SrcAlphaSaturateFactor
  631. // The followings are not supported by Three.js yet
  632. //32769: CONSTANT_COLOR,
  633. //32770: ONE_MINUS_CONSTANT_COLOR,
  634. //32771: CONSTANT_ALPHA,
  635. //32772: ONE_MINUS_CONSTANT_COLOR
  636. };
  637. var WEBGL_TYPE_SIZES = {
  638. 'SCALAR': 1,
  639. 'VEC2': 2,
  640. 'VEC3': 3,
  641. 'VEC4': 4,
  642. 'MAT2': 4,
  643. 'MAT3': 9,
  644. 'MAT4': 16
  645. };
  646. var PATH_PROPERTIES = {
  647. scale: 'scale',
  648. translation: 'position',
  649. rotation: 'quaternion',
  650. weights: 'morphTargetInfluences'
  651. };
  652. var INTERPOLATION = {
  653. CATMULLROMSPLINE: THREE.InterpolateSmooth,
  654. CUBICSPLINE: THREE.InterpolateSmooth,
  655. LINEAR: THREE.InterpolateLinear,
  656. STEP: THREE.InterpolateDiscrete
  657. };
  658. var STATES_ENABLES = {
  659. 2884: 'CULL_FACE',
  660. 2929: 'DEPTH_TEST',
  661. 3042: 'BLEND',
  662. 3089: 'SCISSOR_TEST',
  663. 32823: 'POLYGON_OFFSET_FILL',
  664. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  665. };
  666. var ALPHA_MODES = {
  667. OPAQUE: 'OPAQUE',
  668. MASK: 'MASK',
  669. BLEND: 'BLEND'
  670. };
  671. /* UTILITY FUNCTIONS */
  672. function _each( object, callback, thisObj ) {
  673. if ( ! object ) {
  674. return Promise.resolve();
  675. }
  676. var results;
  677. var fns = [];
  678. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  679. results = [];
  680. var length = object.length;
  681. for ( var idx = 0; idx < length; idx ++ ) {
  682. var value = callback.call( thisObj || this, object[ idx ], idx );
  683. if ( value ) {
  684. if ( value instanceof Promise ) {
  685. value = value.then( function ( key, value ) {
  686. results[ key ] = value;
  687. }.bind( this, idx ) );
  688. } else {
  689. results[ idx ] = value;
  690. }
  691. fns.push( value );
  692. }
  693. }
  694. } else {
  695. results = {};
  696. for ( var key in object ) {
  697. if ( object.hasOwnProperty( key ) ) {
  698. var value = callback.call( thisObj || this, object[ key ], key );
  699. if ( value ) {
  700. if ( value instanceof Promise ) {
  701. value = value.then( function ( key, value ) {
  702. results[ key ] = value;
  703. }.bind( this, key ) );
  704. } else {
  705. results[ key ] = value;
  706. }
  707. fns.push( value );
  708. }
  709. }
  710. }
  711. }
  712. return Promise.all( fns ).then( function () {
  713. return results;
  714. } );
  715. }
  716. function resolveURL( url, path ) {
  717. // Invalid URL
  718. if ( typeof url !== 'string' || url === '' )
  719. return '';
  720. // Absolute URL http://,https://,//
  721. if ( /^(https?:)?\/\//i.test( url ) ) {
  722. return url;
  723. }
  724. // Data URI
  725. if ( /^data:.*,.*$/i.test( url ) ) {
  726. return url;
  727. }
  728. // Blob URL
  729. if ( /^blob:.*$/i.test( url ) ) {
  730. return url;
  731. }
  732. // Relative URL
  733. return path + url;
  734. }
  735. function convertUint8ArrayToString( array ) {
  736. if ( window.TextDecoder !== undefined ) {
  737. return new TextDecoder().decode( array );
  738. }
  739. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  740. // throws a "maximum call stack size exceeded" error for large arrays.
  741. var s = '';
  742. for ( var i = 0, il = array.length; i < il; i ++ ) {
  743. s += String.fromCharCode( array[ i ] );
  744. }
  745. return s;
  746. }
  747. /**
  748. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  749. */
  750. function createDefaultMaterial() {
  751. return new THREE.MeshStandardMaterial( {
  752. color: 0xFFFFFF,
  753. emissive: 0x000000,
  754. metalness: 1,
  755. roughness: 1,
  756. transparent: false,
  757. depthTest: true,
  758. side: THREE.FrontSide
  759. } );
  760. }
  761. /**
  762. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  763. *
  764. * TODO: Implement support for morph targets on TANGENT attribute.
  765. *
  766. * @param {THREE.Mesh} mesh
  767. * @param {GLTF.Mesh} meshDef
  768. * @param {GLTF.Primitive} primitiveDef
  769. * @param {Object} dependencies
  770. */
  771. function addMorphTargets( mesh, meshDef, primitiveDef, dependencies ) {
  772. var geometry = mesh.geometry;
  773. var material = mesh.material;
  774. var targets = primitiveDef.targets;
  775. var morphAttributes = geometry.morphAttributes;
  776. morphAttributes.position = [];
  777. morphAttributes.normal = [];
  778. material.morphTargets = true;
  779. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  780. var target = targets[ i ];
  781. var attributeName = 'morphTarget' + i;
  782. var positionAttribute, normalAttribute;
  783. if ( target.POSITION !== undefined ) {
  784. // Three.js morph formula is
  785. // position
  786. // + weight0 * ( morphTarget0 - position )
  787. // + weight1 * ( morphTarget1 - position )
  788. // ...
  789. // while the glTF one is
  790. // position
  791. // + weight0 * morphTarget0
  792. // + weight1 * morphTarget1
  793. // ...
  794. // then adding position to morphTarget.
  795. // So morphTarget value will depend on mesh's position, then cloning attribute
  796. // for the case if attribute is shared among two or more meshes.
  797. positionAttribute = dependencies.accessors[ target.POSITION ].clone();
  798. var position = geometry.attributes.position;
  799. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  800. positionAttribute.setXYZ(
  801. j,
  802. positionAttribute.getX( j ) + position.getX( j ),
  803. positionAttribute.getY( j ) + position.getY( j ),
  804. positionAttribute.getZ( j ) + position.getZ( j )
  805. );
  806. }
  807. } else if ( geometry.attributes.position ) {
  808. // Copying the original position not to affect the final position.
  809. // See the formula above.
  810. positionAttribute = geometry.attributes.position.clone();
  811. }
  812. if ( positionAttribute !== undefined ) {
  813. positionAttribute.name = attributeName;
  814. morphAttributes.position.push( positionAttribute );
  815. }
  816. if ( target.NORMAL !== undefined ) {
  817. material.morphNormals = true;
  818. // see target.POSITION's comment
  819. normalAttribute = dependencies.accessors[ target.NORMAL ].clone();
  820. var normal = geometry.attributes.normal;
  821. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  822. normalAttribute.setXYZ(
  823. j,
  824. normalAttribute.getX( j ) + normal.getX( j ),
  825. normalAttribute.getY( j ) + normal.getY( j ),
  826. normalAttribute.getZ( j ) + normal.getZ( j )
  827. );
  828. }
  829. } else if ( geometry.attributes.normal !== undefined ) {
  830. normalAttribute = geometry.attributes.normal.clone();
  831. }
  832. if ( normalAttribute !== undefined ) {
  833. normalAttribute.name = attributeName;
  834. morphAttributes.normal.push( normalAttribute );
  835. }
  836. }
  837. mesh.updateMorphTargets();
  838. if ( meshDef.weights !== undefined ) {
  839. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  840. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  841. }
  842. }
  843. }
  844. /* GLTF PARSER */
  845. function GLTFParser( json, extensions, options ) {
  846. this.json = json || {};
  847. this.extensions = extensions || {};
  848. this.options = options || {};
  849. // loader object cache
  850. this.cache = new GLTFRegistry();
  851. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  852. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  853. this.fileLoader = new THREE.FileLoader( this.options.manager );
  854. this.fileLoader.setResponseType( 'arraybuffer' );
  855. }
  856. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  857. var _dependencies = {};
  858. for ( var i = 0; i < dependencies.length; i ++ ) {
  859. var dependency = dependencies[ i ];
  860. var fnName = 'load' + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  861. var cached = this.cache.get( dependency );
  862. if ( cached !== undefined ) {
  863. _dependencies[ dependency ] = cached;
  864. } else if ( this[ fnName ] ) {
  865. var fn = this[ fnName ]();
  866. this.cache.add( dependency, fn );
  867. _dependencies[ dependency ] = fn;
  868. }
  869. }
  870. return _each( _dependencies, function ( dependency ) {
  871. return dependency;
  872. } );
  873. };
  874. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  875. var json = this.json;
  876. var parser = this;
  877. // Clear the loader cache
  878. this.cache.removeAll();
  879. // Fire the callback on complete
  880. this._withDependencies( [
  881. 'scenes',
  882. 'animations'
  883. ] ).then( function ( dependencies ) {
  884. var scenes = dependencies.scenes || [];
  885. var scene = scenes[ json.scene || 0 ];
  886. var animations = dependencies.animations || [];
  887. parser.getDependencies( 'camera' ).then( function ( cameras ) {
  888. onLoad( scene, scenes, cameras, animations );
  889. } ).catch( onError );
  890. } ).catch( onError );
  891. };
  892. /**
  893. * Requests the specified dependency asynchronously, with caching.
  894. * @param {string} type
  895. * @param {number} index
  896. * @return {Promise<Object>}
  897. */
  898. GLTFParser.prototype.getDependency = function ( type, index ) {
  899. var cacheKey = type + ':' + index;
  900. var dependency = this.cache.get( cacheKey );
  901. if ( ! dependency ) {
  902. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  903. dependency = this[ fnName ]( index );
  904. this.cache.add( cacheKey, dependency );
  905. }
  906. return dependency;
  907. };
  908. /**
  909. * Requests all dependencies of the specified type asynchronously, with caching.
  910. * @param {string} type
  911. * @return {Promise<Array<Object>>}
  912. */
  913. GLTFParser.prototype.getDependencies = function ( type ) {
  914. var parser = this;
  915. var defs = this.json[ type + 's' ] || [];
  916. return Promise.all( defs.map( function ( def, index ) {
  917. return parser.getDependency( type, index );
  918. } ) );
  919. };
  920. /**
  921. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  922. * @param {number} bufferIndex
  923. * @return {Promise<ArrayBuffer>}
  924. */
  925. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  926. var bufferDef = this.json.buffers[ bufferIndex ];
  927. var loader = this.fileLoader;
  928. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  929. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  930. }
  931. // If present, GLB container is required to be the first buffer.
  932. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  933. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  934. }
  935. var options = this.options;
  936. return new Promise( function ( resolve, reject ) {
  937. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  938. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  939. } );
  940. } );
  941. };
  942. /**
  943. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  944. * @param {number} bufferViewIndex
  945. * @return {Promise<ArrayBuffer>}
  946. */
  947. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  948. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  949. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  950. var byteLength = bufferViewDef.byteLength || 0;
  951. var byteOffset = bufferViewDef.byteOffset || 0;
  952. return buffer.slice( byteOffset, byteOffset + byteLength );
  953. } );
  954. };
  955. GLTFParser.prototype.loadAccessors = function () {
  956. var parser = this;
  957. var json = this.json;
  958. return _each( json.accessors, function ( accessor ) {
  959. return parser.getDependency( 'bufferView', accessor.bufferView ).then( function ( bufferView ) {
  960. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  961. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  962. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  963. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  964. var itemBytes = elementBytes * itemSize;
  965. var byteStride = json.bufferViews[ accessor.bufferView ].byteStride;
  966. var normalized = accessor.normalized === true;
  967. var array;
  968. // The buffer is not interleaved if the stride is the item size in bytes.
  969. if ( byteStride && byteStride !== itemBytes ) {
  970. // Use the full buffer if it's interleaved.
  971. array = new TypedArray( bufferView );
  972. // Integer parameters to IB/IBA are in array elements, not bytes.
  973. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  974. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes, normalized );
  975. } else {
  976. array = new TypedArray( bufferView, accessor.byteOffset, accessor.count * itemSize );
  977. return new THREE.BufferAttribute( array, itemSize, normalized );
  978. }
  979. } );
  980. } );
  981. };
  982. /**
  983. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  984. * @param {number} textureIndex
  985. * @return {Promise<THREE.Texture>}
  986. */
  987. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  988. var parser = this;
  989. var json = this.json;
  990. var options = this.options;
  991. var textureLoader = this.textureLoader;
  992. var URL = window.URL || window.webkitURL;
  993. var textureDef = json.textures[ textureIndex ];
  994. var source = json.images[ textureDef.source ];
  995. var sourceURI = source.uri;
  996. var isObjectURL = false;
  997. if ( source.bufferView !== undefined ) {
  998. // Load binary image data from bufferView, if provided.
  999. sourceURI = parser.getDependency( 'bufferView', source.bufferView )
  1000. .then( function ( bufferView ) {
  1001. isObjectURL = true;
  1002. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1003. sourceURI = URL.createObjectURL( blob );
  1004. return sourceURI;
  1005. } );
  1006. }
  1007. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1008. // Load Texture resource.
  1009. var loader = THREE.Loader.Handlers.get( sourceURI ) || textureLoader;
  1010. return new Promise( function ( resolve, reject ) {
  1011. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1012. } );
  1013. } ).then( function ( texture ) {
  1014. // Clean up resources and configure Texture.
  1015. if ( isObjectURL === true ) {
  1016. URL.revokeObjectURL( sourceURI );
  1017. }
  1018. texture.flipY = false;
  1019. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1020. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  1021. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  1022. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  1023. 'internalFormat will be forced to be the same value as format.' );
  1024. }
  1025. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  1026. var samplers = json.samplers || {};
  1027. var sampler = samplers[ textureDef.sampler ] || {};
  1028. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  1029. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  1030. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  1031. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  1032. return texture;
  1033. } );
  1034. };
  1035. /**
  1036. * Asynchronously assigns a texture to the given material parameters.
  1037. * @param {Object} materialParams
  1038. * @param {string} textureName
  1039. * @param {number} textureIndex
  1040. * @return {Promise}
  1041. */
  1042. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  1043. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  1044. materialParams[ textureName ] = texture;
  1045. } );
  1046. };
  1047. /**
  1048. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1049. * @return {Promise<Array<THREE.Material>>}
  1050. */
  1051. GLTFParser.prototype.loadMaterials = function () {
  1052. var parser = this;
  1053. var json = this.json;
  1054. var extensions = this.extensions;
  1055. return _each( json.materials, function ( material ) {
  1056. var materialType;
  1057. var materialParams = {};
  1058. var materialExtensions = material.extensions || {};
  1059. var pending = [];
  1060. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  1061. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  1062. materialType = khcExtension.getMaterialType( material );
  1063. pending.push( khcExtension.extendParams( materialParams, material, parser ) );
  1064. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1065. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1066. materialType = sgExtension.getMaterialType( material );
  1067. pending.push( sgExtension.extendParams( materialParams, material, parser ) );
  1068. } else if ( material.pbrMetallicRoughness !== undefined ) {
  1069. // Specification:
  1070. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1071. materialType = THREE.MeshStandardMaterial;
  1072. var metallicRoughness = material.pbrMetallicRoughness;
  1073. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  1074. materialParams.opacity = 1.0;
  1075. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1076. var array = metallicRoughness.baseColorFactor;
  1077. materialParams.color.fromArray( array );
  1078. materialParams.opacity = array[ 3 ];
  1079. }
  1080. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1081. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  1082. }
  1083. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1084. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1085. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1086. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  1087. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  1088. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  1089. }
  1090. } else {
  1091. materialType = THREE.MeshPhongMaterial;
  1092. }
  1093. if ( material.doubleSided === true ) {
  1094. materialParams.side = THREE.DoubleSide;
  1095. }
  1096. var alphaMode = material.alphaMode || ALPHA_MODES.OPAQUE;
  1097. if ( alphaMode !== ALPHA_MODES.OPAQUE ) {
  1098. materialParams.transparent = true;
  1099. if ( alphaMode === ALPHA_MODES.MASK ) {
  1100. materialParams.alphaTest = material.alphaCutoff !== undefined ? material.alphaCutoff : 0.5;
  1101. }
  1102. } else {
  1103. materialParams.transparent = false;
  1104. }
  1105. if ( material.normalTexture !== undefined ) {
  1106. pending.push( parser.assignTexture( materialParams, 'normalMap', material.normalTexture.index ) );
  1107. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  1108. if ( material.normalTexture.scale !== undefined ) {
  1109. materialParams.normalScale.set( material.normalTexture.scale, material.normalTexture.scale );
  1110. }
  1111. }
  1112. if ( material.occlusionTexture !== undefined ) {
  1113. pending.push( parser.assignTexture( materialParams, 'aoMap', material.occlusionTexture.index ) );
  1114. if ( material.occlusionTexture.strength !== undefined ) {
  1115. materialParams.aoMapIntensity = material.occlusionTexture.strength;
  1116. }
  1117. }
  1118. if ( material.emissiveFactor !== undefined ) {
  1119. if ( materialType === THREE.MeshBasicMaterial ) {
  1120. materialParams.color = new THREE.Color().fromArray( material.emissiveFactor );
  1121. } else {
  1122. materialParams.emissive = new THREE.Color().fromArray( material.emissiveFactor );
  1123. }
  1124. }
  1125. if ( material.emissiveTexture !== undefined ) {
  1126. if ( materialType === THREE.MeshBasicMaterial ) {
  1127. pending.push( parser.assignTexture( materialParams, 'map', material.emissiveTexture.index ) );
  1128. } else {
  1129. pending.push( parser.assignTexture( materialParams, 'emissiveMap', material.emissiveTexture.index ) );
  1130. }
  1131. }
  1132. return Promise.all( pending ).then( function () {
  1133. var _material;
  1134. if ( materialType === THREE.ShaderMaterial ) {
  1135. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1136. } else {
  1137. _material = new materialType( materialParams );
  1138. }
  1139. if ( material.name !== undefined ) _material.name = material.name;
  1140. // Normal map textures use OpenGL conventions:
  1141. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  1142. if ( _material.normalScale ) {
  1143. _material.normalScale.x = - _material.normalScale.x;
  1144. }
  1145. // emissiveTexture and baseColorTexture use sRGB encoding.
  1146. if ( _material.map ) _material.map.encoding = THREE.sRGBEncoding;
  1147. if ( _material.emissiveMap ) _material.emissiveMap.encoding = THREE.sRGBEncoding;
  1148. if ( material.extras ) _material.userData = material.extras;
  1149. return _material;
  1150. } );
  1151. } );
  1152. };
  1153. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1154. return this._withDependencies( [
  1155. 'accessors',
  1156. ] ).then( function ( dependencies ) {
  1157. return _each( primitives, function ( primitive ) {
  1158. var geometry = new THREE.BufferGeometry();
  1159. var attributes = primitive.attributes;
  1160. for ( var attributeId in attributes ) {
  1161. var attributeEntry = attributes[ attributeId ];
  1162. if ( attributeEntry === undefined ) return;
  1163. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1164. switch ( attributeId ) {
  1165. case 'POSITION':
  1166. geometry.addAttribute( 'position', bufferAttribute );
  1167. break;
  1168. case 'NORMAL':
  1169. geometry.addAttribute( 'normal', bufferAttribute );
  1170. break;
  1171. case 'TEXCOORD_0':
  1172. case 'TEXCOORD0':
  1173. case 'TEXCOORD':
  1174. geometry.addAttribute( 'uv', bufferAttribute );
  1175. break;
  1176. case 'TEXCOORD_1':
  1177. geometry.addAttribute( 'uv2', bufferAttribute );
  1178. break;
  1179. case 'COLOR_0':
  1180. case 'COLOR0':
  1181. case 'COLOR':
  1182. geometry.addAttribute( 'color', bufferAttribute );
  1183. break;
  1184. case 'WEIGHTS_0':
  1185. case 'WEIGHT': // WEIGHT semantic deprecated.
  1186. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1187. break;
  1188. case 'JOINTS_0':
  1189. case 'JOINT': // JOINT semantic deprecated.
  1190. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1191. break;
  1192. }
  1193. }
  1194. if ( primitive.indices !== undefined ) {
  1195. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1196. }
  1197. return geometry;
  1198. } );
  1199. } );
  1200. };
  1201. /**
  1202. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1203. */
  1204. GLTFParser.prototype.loadMeshes = function () {
  1205. var scope = this;
  1206. var json = this.json;
  1207. var extensions = this.extensions;
  1208. return this._withDependencies( [
  1209. 'accessors',
  1210. 'materials'
  1211. ] ).then( function ( dependencies ) {
  1212. return _each( json.meshes, function ( meshDef, meshIndex ) {
  1213. var group = new THREE.Group();
  1214. var primitives = meshDef.primitives || [];
  1215. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  1216. for ( var i = 0; i < primitives.length; i ++ ) {
  1217. var primitive = primitives[ i ];
  1218. var geometry = geometries[ i ];
  1219. var material = primitive.material === undefined
  1220. ? createDefaultMaterial()
  1221. : dependencies.materials[ primitive.material ];
  1222. if ( material.aoMap
  1223. && geometry.attributes.uv2 === undefined
  1224. && geometry.attributes.uv !== undefined ) {
  1225. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1226. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1227. }
  1228. var useVertexColors = geometry.attributes.color !== undefined;
  1229. var useFlatShading = geometry.attributes.normal === undefined;
  1230. if ( useVertexColors || useFlatShading ) {
  1231. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1232. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1233. material = specGlossExtension.cloneMaterial( material );
  1234. } else {
  1235. material = material.clone();
  1236. }
  1237. }
  1238. if ( useVertexColors ) {
  1239. material.vertexColors = THREE.VertexColors;
  1240. material.needsUpdate = true;
  1241. }
  1242. if ( useFlatShading ) {
  1243. material.flatShading = true;
  1244. }
  1245. var mesh;
  1246. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1247. mesh = new THREE.Mesh( geometry, material );
  1248. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1249. mesh = new THREE.Mesh( geometry, material );
  1250. mesh.drawMode = THREE.TriangleStripDrawMode;
  1251. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1252. mesh = new THREE.Mesh( geometry, material );
  1253. mesh.drawMode = THREE.TriangleFanDrawMode;
  1254. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1255. mesh = new THREE.LineSegments( geometry, material );
  1256. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1257. mesh = new THREE.Line( geometry, material );
  1258. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1259. mesh = new THREE.LineLoop( geometry, material );
  1260. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1261. mesh = new THREE.Points( geometry, material );
  1262. } else {
  1263. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ', primitive.mode );
  1264. }
  1265. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1266. if ( primitive.targets !== undefined ) {
  1267. addMorphTargets( mesh, meshDef, primitive, dependencies );
  1268. }
  1269. if ( primitive.extras ) mesh.userData = primitive.extras;
  1270. if ( primitives.length > 1 ) {
  1271. mesh.name += '_' + i;
  1272. group.add( mesh );
  1273. } else {
  1274. return mesh;
  1275. }
  1276. }
  1277. return group;
  1278. } );
  1279. } );
  1280. } );
  1281. };
  1282. /**
  1283. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1284. * @param {number} cameraIndex
  1285. * @return {Promise<THREE.Camera>}
  1286. */
  1287. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1288. var camera;
  1289. var cameraDef = this.json.cameras[ cameraIndex ];
  1290. var params = cameraDef[ cameraDef.type ];
  1291. if ( ! params ) {
  1292. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1293. return;
  1294. }
  1295. if ( cameraDef.type === 'perspective' ) {
  1296. var aspectRatio = params.aspectRatio || 1;
  1297. var xfov = params.yfov * aspectRatio;
  1298. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  1299. } else if ( cameraDef.type === 'orthographic' ) {
  1300. camera = new THREE.OrthographicCamera( params.xmag / -2, params.xmag / 2, params.ymag / 2, params.ymag / -2, params.znear, params.zfar );
  1301. }
  1302. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1303. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  1304. return Promise.resolve( camera );
  1305. };
  1306. GLTFParser.prototype.loadSkins = function () {
  1307. var json = this.json;
  1308. return this._withDependencies( [
  1309. 'accessors'
  1310. ] ).then( function ( dependencies ) {
  1311. return _each( json.skins, function ( skin ) {
  1312. var _skin = {
  1313. joints: skin.joints,
  1314. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1315. };
  1316. return _skin;
  1317. } );
  1318. } );
  1319. };
  1320. GLTFParser.prototype.loadAnimations = function () {
  1321. var json = this.json;
  1322. return this._withDependencies( [
  1323. 'accessors',
  1324. 'nodes'
  1325. ] ).then( function ( dependencies ) {
  1326. return _each( json.animations, function ( animation, animationId ) {
  1327. var tracks = [];
  1328. for ( var i = 0; i < animation.channels.length; i ++ ) {
  1329. var channel = animation.channels[ i ];
  1330. var sampler = animation.samplers[ channel.sampler ];
  1331. if ( sampler ) {
  1332. var target = channel.target;
  1333. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1334. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1335. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1336. var inputAccessor = dependencies.accessors[ input ];
  1337. var outputAccessor = dependencies.accessors[ output ];
  1338. var node = dependencies.nodes[ name ];
  1339. if ( node ) {
  1340. node.updateMatrix();
  1341. node.matrixAutoUpdate = true;
  1342. var TypedKeyframeTrack;
  1343. switch ( PATH_PROPERTIES[ target.path ] ) {
  1344. case PATH_PROPERTIES.weights:
  1345. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1346. break;
  1347. case PATH_PROPERTIES.rotation:
  1348. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1349. break;
  1350. case PATH_PROPERTIES.position:
  1351. case PATH_PROPERTIES.scale:
  1352. default:
  1353. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1354. break;
  1355. }
  1356. var targetName = node.name ? node.name : node.uuid;
  1357. if ( sampler.interpolation === 'CATMULLROMSPLINE' ) {
  1358. console.warn( 'THREE.GLTFLoader: CATMULLROMSPLINE interpolation is not supported. Using CUBICSPLINE instead.' );
  1359. }
  1360. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1361. var targetNames = [];
  1362. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1363. // node should be THREE.Group here but
  1364. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1365. // the property of a mesh object under node.
  1366. // So finding targets here.
  1367. node.traverse( function ( object ) {
  1368. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1369. targetNames.push( object.name ? object.name : object.uuid );
  1370. }
  1371. } );
  1372. } else {
  1373. targetNames.push( targetName );
  1374. }
  1375. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1376. // buffers before creating a truncated copy to keep. Because buffers may
  1377. // be reused by other tracks, make copies here.
  1378. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1379. tracks.push( new TypedKeyframeTrack(
  1380. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1381. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1382. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1383. interpolation
  1384. ) );
  1385. }
  1386. }
  1387. }
  1388. }
  1389. var name = animation.name !== undefined ? animation.name : 'animation_' + animationId;
  1390. return new THREE.AnimationClip( name, undefined, tracks );
  1391. } );
  1392. } );
  1393. };
  1394. GLTFParser.prototype.loadNodes = function () {
  1395. var json = this.json;
  1396. var extensions = this.extensions;
  1397. var scope = this;
  1398. var nodes = json.nodes || [];
  1399. var skins = json.skins || [];
  1400. var meshReferences = {};
  1401. var meshUses = {};
  1402. // Nothing in the node definition indicates whether it is a Bone or an
  1403. // Object3D. Use the skins' joint references to mark bones.
  1404. for ( var skinIndex in skins ) {
  1405. var joints = skins[ skinIndex ].joints;
  1406. for ( var i = 0; i < joints.length; ++ i ) {
  1407. nodes[ joints[ i ] ].isBone = true;
  1408. }
  1409. }
  1410. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1411. // avoid having more than one THREE.Mesh with the same name, count
  1412. // references and rename instances below.
  1413. //
  1414. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1415. for ( var nodeIndex in nodes ) {
  1416. var nodeDef = nodes[ nodeIndex ];
  1417. if ( nodeDef.mesh !== undefined ) {
  1418. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1419. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1420. }
  1421. meshReferences[ nodeDef.mesh ]++;
  1422. }
  1423. }
  1424. return scope._withDependencies( [
  1425. 'meshes',
  1426. 'skins',
  1427. 'cameras'
  1428. ] ).then( function ( dependencies ) {
  1429. return _each( json.nodes, function ( nodeDef ) {
  1430. if ( nodeDef.isBone === true ) {
  1431. return new THREE.Bone();
  1432. } else if ( nodeDef.mesh !== undefined ) {
  1433. var mesh = dependencies.meshes[ nodeDef.mesh ].clone();
  1434. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1435. mesh.name += '_instance_' + meshUses[ nodeDef.mesh ]++;
  1436. }
  1437. return mesh;
  1438. } else if ( nodeDef.camera !== undefined ) {
  1439. return scope.getDependency( 'camera', nodeDef.camera );
  1440. } else if ( nodeDef.extensions
  1441. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1442. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1443. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1444. return lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  1445. } else {
  1446. return new THREE.Object3D();
  1447. }
  1448. } ).then( function ( __nodes ) {
  1449. return _each( __nodes, function ( node, nodeIndex ) {
  1450. var nodeDef = json.nodes[ nodeIndex ];
  1451. if ( nodeDef.name !== undefined ) {
  1452. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  1453. }
  1454. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  1455. if ( nodeDef.matrix !== undefined ) {
  1456. var matrix = new THREE.Matrix4();
  1457. matrix.fromArray( nodeDef.matrix );
  1458. node.applyMatrix( matrix );
  1459. } else {
  1460. if ( nodeDef.translation !== undefined ) {
  1461. node.position.fromArray( nodeDef.translation );
  1462. }
  1463. if ( nodeDef.rotation !== undefined ) {
  1464. node.quaternion.fromArray( nodeDef.rotation );
  1465. }
  1466. if ( nodeDef.scale !== undefined ) {
  1467. node.scale.fromArray( nodeDef.scale );
  1468. }
  1469. }
  1470. if ( nodeDef.skin !== undefined ) {
  1471. var skinnedMeshes = [];
  1472. var meshes = node.children.length > 0 ? node.children : [ node ];
  1473. for ( var i = 0; i < meshes.length; i ++ ) {
  1474. var mesh = meshes[ i ];
  1475. var skinEntry = dependencies.skins[ nodeDef.skin ];
  1476. // Replace Mesh with SkinnedMesh.
  1477. var geometry = mesh.geometry;
  1478. var material = mesh.material;
  1479. material.skinning = true;
  1480. var skinnedMesh = new THREE.SkinnedMesh( geometry, material );
  1481. skinnedMesh.morphTargetInfluences = mesh.morphTargetInfluences;
  1482. skinnedMesh.userData = mesh.userData;
  1483. skinnedMesh.name = mesh.name;
  1484. var bones = [];
  1485. var boneInverses = [];
  1486. for ( var j = 0, l = skinEntry.joints.length; j < l; j ++ ) {
  1487. var jointId = skinEntry.joints[ j ];
  1488. var jointNode = __nodes[ jointId ];
  1489. if ( jointNode ) {
  1490. bones.push( jointNode );
  1491. var m = skinEntry.inverseBindMatrices.array;
  1492. var mat = new THREE.Matrix4().fromArray( m, j * 16 );
  1493. boneInverses.push( mat );
  1494. } else {
  1495. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  1496. }
  1497. }
  1498. skinnedMesh.bind( new THREE.Skeleton( bones, boneInverses ), skinnedMesh.matrixWorld );
  1499. skinnedMeshes.push( skinnedMesh );
  1500. }
  1501. if ( node.children.length > 0 ) {
  1502. node.remove.apply( node, node.children );
  1503. node.add.apply( node, skinnedMeshes );
  1504. } else {
  1505. node = skinnedMeshes[ 0 ];
  1506. }
  1507. }
  1508. return node;
  1509. } );
  1510. } );
  1511. } );
  1512. };
  1513. GLTFParser.prototype.loadScenes = function () {
  1514. var json = this.json;
  1515. var extensions = this.extensions;
  1516. // scene node hierachy builder
  1517. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1518. var _node = allNodes[ nodeId ];
  1519. parentObject.add( _node );
  1520. var node = json.nodes[ nodeId ];
  1521. if ( node.children ) {
  1522. var children = node.children;
  1523. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1524. var child = children[ i ];
  1525. buildNodeHierachy( child, _node, allNodes );
  1526. }
  1527. }
  1528. }
  1529. return this._withDependencies( [
  1530. 'nodes'
  1531. ] ).then( function ( dependencies ) {
  1532. return _each( json.scenes, function ( scene ) {
  1533. var _scene = new THREE.Scene();
  1534. if ( scene.name !== undefined ) _scene.name = scene.name;
  1535. if ( scene.extras ) _scene.userData = scene.extras;
  1536. var nodes = scene.nodes || [];
  1537. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1538. var nodeId = nodes[ i ];
  1539. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1540. }
  1541. _scene.traverse( function ( child ) {
  1542. // for Specular-Glossiness.
  1543. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial ) {
  1544. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1545. }
  1546. } );
  1547. // Ambient lighting, if present, is always attached to the scene root.
  1548. if ( scene.extensions
  1549. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ]
  1550. && scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  1551. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  1552. _scene.add( lights[ scene.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  1553. }
  1554. return _scene;
  1555. } );
  1556. } );
  1557. };
  1558. return GLTFLoader;
  1559. } )();