GLTFLoader.js 57 KB

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