GLTFLoader.js 80 KB

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