GLTFLoader.js 58 KB

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