GLTFLoader.js 82 KB

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