2
0

GLTFLoader.js 56 KB

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