GLTFLoader.js 81 KB

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