GLTFLoader.js 79 KB

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