GLTFLoader.js 82 KB

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