GLTFLoader.js 83 KB

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