GLTFLoader.js 80 KB

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