GLTFLoader.js 56 KB

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