GLTFLoader.js 82 KB

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