GLTFLoader.js 71 KB

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