GLTFLoader.js 71 KB

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