GLTFLoader.js 79 KB

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