GLTFLoader.js 79 KB

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