GLTFLoader.js 67 KB

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