GLTFLoader.js 58 KB

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