GLTFLoader.js 83 KB

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