GLTFLoader.js 80 KB

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