GLTFLoader.js 82 KB

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