GLTFLoader.js 79 KB

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