GLTFLoader.js 79 KB

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