GLTF2Loader.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809
  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.GLTF2Loader = ( function () {
  9. function GLTF2Loader( manager ) {
  10. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11. }
  12. GLTF2Loader.prototype = {
  13. constructor: GLTF2Loader,
  14. load: function ( url, onLoad, onProgress, onError ) {
  15. var scope = this;
  16. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setResponseType( 'arraybuffer' );
  19. loader.load( url, function ( data ) {
  20. scope.parse( data, onLoad, path );
  21. }, onProgress, onError );
  22. },
  23. setCrossOrigin: function ( value ) {
  24. this.crossOrigin = value;
  25. },
  26. setPath: function ( value ) {
  27. this.path = value;
  28. },
  29. parse: function ( data, callback, path ) {
  30. var content;
  31. var extensions = {};
  32. var magic = convertUint8ArrayToString( new Uint8Array( data, 0, 4 ) );
  33. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  35. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36. } else {
  37. content = convertUint8ArrayToString( new Uint8Array( data ) );
  38. }
  39. var json = JSON.parse( content );
  40. if ( json.extensionsUsed ) {
  41. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  42. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  43. }
  44. if( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  45. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  46. }
  47. }
  48. console.time( 'GLTF2Loader' );
  49. var parser = new GLTFParser( json, extensions, {
  50. path: path || this.path,
  51. crossOrigin: this.crossOrigin
  52. } );
  53. parser.parse( function ( scene, scenes, cameras, animations ) {
  54. console.timeEnd( 'GLTF2Loader' );
  55. var glTF = {
  56. "scene": scene,
  57. "scenes": scenes,
  58. "cameras": cameras,
  59. "animations": animations
  60. };
  61. callback( glTF );
  62. } );
  63. }
  64. };
  65. /* GLTFREGISTRY */
  66. function GLTFRegistry() {
  67. var objects = {};
  68. return {
  69. get: function ( key ) {
  70. return objects[ key ];
  71. },
  72. add: function ( key, object ) {
  73. objects[ key ] = object;
  74. },
  75. remove: function ( key ) {
  76. delete objects[ key ];
  77. },
  78. removeAll: function () {
  79. objects = {};
  80. },
  81. update: function ( scene, camera ) {
  82. for ( var name in objects ) {
  83. var object = objects[ name ];
  84. if ( object.update ) {
  85. object.update( scene, camera );
  86. }
  87. }
  88. }
  89. };
  90. }
  91. /* GLTFSHADER */
  92. function GLTFShader( targetNode, allNodes ) {
  93. var boundUniforms = {};
  94. // bind each uniform to its source node
  95. var uniforms = targetNode.material.uniforms;
  96. for ( var uniformId in uniforms ) {
  97. var uniform = uniforms[ uniformId ];
  98. if ( uniform.semantic ) {
  99. var sourceNodeRef = uniform.node;
  100. var sourceNode = targetNode;
  101. if ( sourceNodeRef ) {
  102. sourceNode = allNodes[ sourceNodeRef ];
  103. }
  104. boundUniforms[ uniformId ] = {
  105. semantic: uniform.semantic,
  106. sourceNode: sourceNode,
  107. targetNode: targetNode,
  108. uniform: uniform
  109. };
  110. }
  111. }
  112. this.boundUniforms = boundUniforms;
  113. this._m4 = new THREE.Matrix4();
  114. }
  115. // Update - update all the uniform values
  116. GLTFShader.prototype.update = function ( scene, camera ) {
  117. var boundUniforms = this.boundUniforms;
  118. for ( var name in boundUniforms ) {
  119. var boundUniform = boundUniforms[ name ];
  120. switch ( boundUniform.semantic ) {
  121. case "MODELVIEW":
  122. var m4 = boundUniform.uniform.value;
  123. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  124. break;
  125. case "MODELVIEWINVERSETRANSPOSE":
  126. var m3 = boundUniform.uniform.value;
  127. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  128. m3.getNormalMatrix( this._m4 );
  129. break;
  130. case "PROJECTION":
  131. var m4 = boundUniform.uniform.value;
  132. m4.copy( camera.projectionMatrix );
  133. break;
  134. case "JOINTMATRIX":
  135. var m4v = boundUniform.uniform.value;
  136. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  137. // So it goes like this:
  138. // SkinnedMesh world matrix is already baked into MODELVIEW;
  139. // transform joints to local space,
  140. // then transform using joint's inverse
  141. m4v[ mi ]
  142. .getInverse( boundUniform.sourceNode.matrixWorld )
  143. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  144. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  145. .multiply( boundUniform.targetNode.bindMatrix );
  146. }
  147. break;
  148. default :
  149. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  150. break;
  151. }
  152. }
  153. };
  154. /*********************************/
  155. /********** EXTENSIONS ***********/
  156. /*********************************/
  157. var EXTENSIONS = {
  158. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  159. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  160. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
  161. };
  162. /* MATERIALS COMMON EXTENSION */
  163. function GLTFMaterialsCommonExtension( json ) {
  164. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  165. this.lights = {};
  166. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) || {};
  167. var lights = extension.lights || {};
  168. for ( var lightId in lights ) {
  169. var light = lights[ lightId ];
  170. var lightNode;
  171. var lightParams = light[ light.type ];
  172. var color = new THREE.Color().fromArray( lightParams.color );
  173. switch ( light.type ) {
  174. case "directional":
  175. lightNode = new THREE.DirectionalLight( color );
  176. lightNode.position.set( 0, 0, 1 );
  177. break;
  178. case "point":
  179. lightNode = new THREE.PointLight( color );
  180. break;
  181. case "spot":
  182. lightNode = new THREE.SpotLight( color );
  183. lightNode.position.set( 0, 0, 1 );
  184. break;
  185. case "ambient":
  186. lightNode = new THREE.AmbientLight( color );
  187. break;
  188. }
  189. if ( lightNode ) {
  190. this.lights[ lightId ] = lightNode;
  191. }
  192. }
  193. }
  194. /* BINARY EXTENSION */
  195. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  196. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  197. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  198. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  199. function GLTFBinaryExtension( data ) {
  200. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  201. this.content = null;
  202. this.body = null;
  203. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  204. this.header = {
  205. magic: convertUint8ArrayToString( new Uint8Array( data.slice( 0, 4 ) ) ),
  206. version: headerView.getUint32( 4, true ),
  207. length: headerView.getUint32( 8, true )
  208. };
  209. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  210. throw new Error( 'GLTF2Loader: Unsupported glTF-Binary header.' );
  211. } else if ( this.header.version < 2.0 ) {
  212. throw new Error( 'GLTF2Loader: Legacy binary file detected. Use GLTFLoader instead.' );
  213. }
  214. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  215. var chunkIndex = 0;
  216. while ( chunkIndex < chunkView.byteLength ) {
  217. var chunkLength = chunkView.getUint32( chunkIndex, true );
  218. chunkIndex += 4;
  219. var chunkType = chunkView.getUint32( chunkIndex, true );
  220. chunkIndex += 4;
  221. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  222. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  223. this.content = convertUint8ArrayToString( contentArray );
  224. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  225. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  226. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  227. }
  228. // Clients must ignore chunks with unknown types.
  229. chunkIndex += chunkLength;
  230. }
  231. if ( this.content === null ) {
  232. throw new Error( 'GLTF2Loader: JSON content not found.' );
  233. }
  234. }
  235. /* Specular-Glossiness Extension */
  236. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  237. return {
  238. extendParams: function ( params, material, dependencies ) {
  239. // specification
  240. // https://github.com/sbtron/glTF/tree/KHRpbrSpecGloss/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  241. var pbrSpecularGlossiness = material.extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  242. var shader = THREE.ShaderLib[ 'standard' ];
  243. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  244. var specularMapParsFragmentChunk = [
  245. '#ifdef USE_SPECULARMAP',
  246. ' uniform sampler2D specularMap;',
  247. '#endif'
  248. ].join( '\n' );
  249. var glossinessMapParsFragmentChunk = [
  250. '#ifdef USE_GLOSSINESSMAP',
  251. ' uniform sampler2D glossinessMap;',
  252. '#endif'
  253. ].join( '\n' );
  254. var specularMapFragmentChunk = [
  255. 'vec3 specularFactor = specular;',
  256. '#ifdef USE_SPECULARMAP',
  257. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  258. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  259. ' specularFactor *= texelSpecular.rgb;',
  260. '#endif'
  261. ].join( '\n' );
  262. var glossinessMapFragmentChunk = [
  263. 'float glossinessFactor = glossiness;',
  264. '#ifdef USE_GLOSSINESSMAP',
  265. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  266. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  267. ' glossinessFactor *= texelGlossiness.a;',
  268. '#endif'
  269. ].join( '\n' );
  270. var lightPhysicalFragmentChunk = [
  271. 'PhysicalMaterial material;',
  272. 'material.diffuseColor = diffuseColor.rgb;',
  273. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  274. 'material.specularColor = specularFactor.rgb;',
  275. ].join( '\n' );
  276. var fragmentShader = shader.fragmentShader
  277. .replace( '#include <specularmap_fragment>', '' )
  278. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  279. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  280. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  281. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  282. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  283. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  284. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  285. delete uniforms.roughness;
  286. delete uniforms.metalness;
  287. delete uniforms.roughnessMap;
  288. delete uniforms.metalnessMap;
  289. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  290. uniforms.glossiness = { value: 0.5 };
  291. uniforms.specularMap = { value: null };
  292. uniforms.glossinessMap = { value: null };
  293. params.vertexShader = shader.vertexShader;
  294. params.fragmentShader = fragmentShader;
  295. params.uniforms = uniforms;
  296. params.defines = { 'STANDARD': '' };
  297. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  298. params.opacity = 1.0;
  299. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  300. var array = pbrSpecularGlossiness.diffuseFactor;
  301. params.color.fromArray( array );
  302. params.opacity = array[ 3 ];
  303. }
  304. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  305. params.map = dependencies.textures[ pbrSpecularGlossiness.diffuseTexture.index ];
  306. }
  307. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  308. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  309. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  310. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  311. }
  312. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  313. params.glossinessMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];
  314. params.specularMap = dependencies.textures[ pbrSpecularGlossiness.specularGlossinessTexture.index ];
  315. }
  316. },
  317. createMaterial: function ( params ) {
  318. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  319. var material = new THREE.ShaderMaterial( {
  320. defines: params.defines,
  321. vertexShader: params.vertexShader,
  322. fragmentShader: params.fragmentShader,
  323. uniforms: params.uniforms,
  324. fog: true,
  325. lights: true,
  326. opacity: params.opacity,
  327. transparent: params.transparent
  328. } );
  329. material.color = params.color;
  330. material.map = params.map === undefined ? null : params.map;
  331. material.lightMap = null;
  332. material.lightMapIntensity = 1.0;
  333. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  334. material.aoMapIntensity = 1.0;
  335. material.emissive = params.emissive;
  336. material.emissiveIntensity = 1.0;
  337. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  338. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  339. material.bumpScale = 1;
  340. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  341. material.normalScale = new THREE.Vector2( 1, 1 );
  342. material.displacementMap = null;
  343. material.displacementScale = 1;
  344. material.displacementBias = 0;
  345. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  346. material.specular = params.specular;
  347. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  348. material.glossiness = params.glossiness;
  349. material.alphaMap = null;
  350. material.envMap = params.envMap === undefined ? null : params.envMap;
  351. material.envMapIntensity = 1.0;
  352. material.refractionRatio = 0.98;
  353. material.extensions.derivatives = true;
  354. return material;
  355. },
  356. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  357. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  358. var uniforms = material.uniforms;
  359. var defines = material.defines;
  360. uniforms.opacity.value = material.opacity;
  361. uniforms.diffuse.value.copy( material.color );
  362. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  363. uniforms.map.value = material.map;
  364. uniforms.specularMap.value = material.specularMap;
  365. uniforms.alphaMap.value = material.alphaMap;
  366. uniforms.lightMap.value = material.lightMap;
  367. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  368. uniforms.aoMap.value = material.aoMap;
  369. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  370. // uv repeat and offset setting priorities
  371. // 1. color map
  372. // 2. specular map
  373. // 3. normal map
  374. // 4. bump map
  375. // 5. alpha map
  376. // 6. emissive map
  377. var uvScaleMap;
  378. if ( material.map ) {
  379. uvScaleMap = material.map;
  380. } else if ( material.specularMap ) {
  381. uvScaleMap = material.specularMap;
  382. } else if ( material.displacementMap ) {
  383. uvScaleMap = material.displacementMap;
  384. } else if ( material.normalMap ) {
  385. uvScaleMap = material.normalMap;
  386. } else if ( material.bumpMap ) {
  387. uvScaleMap = material.bumpMap;
  388. } else if ( material.glossinessMap ) {
  389. uvScaleMap = material.glossinessMap;
  390. } else if ( material.alphaMap ) {
  391. uvScaleMap = material.alphaMap;
  392. } else if ( material.emissiveMap ) {
  393. uvScaleMap = material.emissiveMap;
  394. }
  395. if ( uvScaleMap !== undefined ) {
  396. // backwards compatibility
  397. if ( uvScaleMap.isWebGLRenderTarget ) {
  398. uvScaleMap = uvScaleMap.texture;
  399. }
  400. var offset = uvScaleMap.offset;
  401. var repeat = uvScaleMap.repeat;
  402. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  403. }
  404. uniforms.envMap.value = material.envMap;
  405. uniforms.envMapIntensity.value = material.envMapIntensity;
  406. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? -1 : 1;
  407. uniforms.refractionRatio.value = material.refractionRatio;
  408. uniforms.specular.value.copy( material.specular );
  409. uniforms.glossiness.value = material.glossiness;
  410. uniforms.glossinessMap.value = material.glossinessMap;
  411. uniforms.emissiveMap.value = material.emissiveMap;
  412. uniforms.bumpMap.value = material.bumpMap;
  413. uniforms.normalMap.value = material.normalMap;
  414. uniforms.displacementMap.value = material.displacementMap;
  415. uniforms.displacementScale.value = material.displacementScale;
  416. uniforms.displacementBias.value = material.displacementBias;
  417. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  418. defines.USE_GLOSSINESSMAP = '';
  419. // set USE_ROUGHNESSMAP to enable vUv
  420. defines.USE_ROUGHNESSMAP = ''
  421. }
  422. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  423. delete defines.USE_GLOSSINESSMAP;
  424. delete defines.USE_ROUGHNESSMAP;
  425. }
  426. }
  427. };
  428. }
  429. /*********************************/
  430. /********** INTERNALS ************/
  431. /*********************************/
  432. /* CONSTANTS */
  433. var WEBGL_CONSTANTS = {
  434. FLOAT: 5126,
  435. //FLOAT_MAT2: 35674,
  436. FLOAT_MAT3: 35675,
  437. FLOAT_MAT4: 35676,
  438. FLOAT_VEC2: 35664,
  439. FLOAT_VEC3: 35665,
  440. FLOAT_VEC4: 35666,
  441. LINEAR: 9729,
  442. REPEAT: 10497,
  443. SAMPLER_2D: 35678,
  444. TRIANGLES: 4,
  445. LINES: 1,
  446. UNSIGNED_BYTE: 5121,
  447. UNSIGNED_SHORT: 5123,
  448. VERTEX_SHADER: 35633,
  449. FRAGMENT_SHADER: 35632
  450. };
  451. var WEBGL_TYPE = {
  452. 5126: Number,
  453. //35674: THREE.Matrix2,
  454. 35675: THREE.Matrix3,
  455. 35676: THREE.Matrix4,
  456. 35664: THREE.Vector2,
  457. 35665: THREE.Vector3,
  458. 35666: THREE.Vector4,
  459. 35678: THREE.Texture
  460. };
  461. var WEBGL_COMPONENT_TYPES = {
  462. 5120: Int8Array,
  463. 5121: Uint8Array,
  464. 5122: Int16Array,
  465. 5123: Uint16Array,
  466. 5125: Uint32Array,
  467. 5126: Float32Array
  468. };
  469. var WEBGL_FILTERS = {
  470. 9728: THREE.NearestFilter,
  471. 9729: THREE.LinearFilter,
  472. 9984: THREE.NearestMipMapNearestFilter,
  473. 9985: THREE.LinearMipMapNearestFilter,
  474. 9986: THREE.NearestMipMapLinearFilter,
  475. 9987: THREE.LinearMipMapLinearFilter
  476. };
  477. var WEBGL_WRAPPINGS = {
  478. 33071: THREE.ClampToEdgeWrapping,
  479. 33648: THREE.MirroredRepeatWrapping,
  480. 10497: THREE.RepeatWrapping
  481. };
  482. var WEBGL_TEXTURE_FORMATS = {
  483. 6406: THREE.AlphaFormat,
  484. 6407: THREE.RGBFormat,
  485. 6408: THREE.RGBAFormat,
  486. 6409: THREE.LuminanceFormat,
  487. 6410: THREE.LuminanceAlphaFormat
  488. };
  489. var WEBGL_TEXTURE_DATATYPES = {
  490. 5121: THREE.UnsignedByteType,
  491. 32819: THREE.UnsignedShort4444Type,
  492. 32820: THREE.UnsignedShort5551Type,
  493. 33635: THREE.UnsignedShort565Type
  494. };
  495. var WEBGL_SIDES = {
  496. 1028: THREE.BackSide, // Culling front
  497. 1029: THREE.FrontSide // Culling back
  498. //1032: THREE.NoSide // Culling front and back, what to do?
  499. };
  500. var WEBGL_DEPTH_FUNCS = {
  501. 512: THREE.NeverDepth,
  502. 513: THREE.LessDepth,
  503. 514: THREE.EqualDepth,
  504. 515: THREE.LessEqualDepth,
  505. 516: THREE.GreaterEqualDepth,
  506. 517: THREE.NotEqualDepth,
  507. 518: THREE.GreaterEqualDepth,
  508. 519: THREE.AlwaysDepth
  509. };
  510. var WEBGL_BLEND_EQUATIONS = {
  511. 32774: THREE.AddEquation,
  512. 32778: THREE.SubtractEquation,
  513. 32779: THREE.ReverseSubtractEquation
  514. };
  515. var WEBGL_BLEND_FUNCS = {
  516. 0: THREE.ZeroFactor,
  517. 1: THREE.OneFactor,
  518. 768: THREE.SrcColorFactor,
  519. 769: THREE.OneMinusSrcColorFactor,
  520. 770: THREE.SrcAlphaFactor,
  521. 771: THREE.OneMinusSrcAlphaFactor,
  522. 772: THREE.DstAlphaFactor,
  523. 773: THREE.OneMinusDstAlphaFactor,
  524. 774: THREE.DstColorFactor,
  525. 775: THREE.OneMinusDstColorFactor,
  526. 776: THREE.SrcAlphaSaturateFactor
  527. // The followings are not supported by Three.js yet
  528. //32769: CONSTANT_COLOR,
  529. //32770: ONE_MINUS_CONSTANT_COLOR,
  530. //32771: CONSTANT_ALPHA,
  531. //32772: ONE_MINUS_CONSTANT_COLOR
  532. };
  533. var WEBGL_TYPE_SIZES = {
  534. 'SCALAR': 1,
  535. 'VEC2': 2,
  536. 'VEC3': 3,
  537. 'VEC4': 4,
  538. 'MAT2': 4,
  539. 'MAT3': 9,
  540. 'MAT4': 16
  541. };
  542. var PATH_PROPERTIES = {
  543. scale: 'scale',
  544. translation: 'position',
  545. rotation: 'quaternion',
  546. weights: 'morphTargetInfluences'
  547. };
  548. var INTERPOLATION = {
  549. LINEAR: THREE.InterpolateLinear,
  550. STEP: THREE.InterpolateDiscrete
  551. };
  552. var STATES_ENABLES = {
  553. 2884: 'CULL_FACE',
  554. 2929: 'DEPTH_TEST',
  555. 3042: 'BLEND',
  556. 3089: 'SCISSOR_TEST',
  557. 32823: 'POLYGON_OFFSET_FILL',
  558. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  559. };
  560. /* UTILITY FUNCTIONS */
  561. function _each( object, callback, thisObj ) {
  562. if ( !object ) {
  563. return Promise.resolve();
  564. }
  565. var results;
  566. var fns = [];
  567. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  568. results = [];
  569. var length = object.length;
  570. for ( var idx = 0; idx < length; idx ++ ) {
  571. var value = callback.call( thisObj || this, object[ idx ], idx );
  572. if ( value ) {
  573. fns.push( value );
  574. if ( value instanceof Promise ) {
  575. value.then( function( key, value ) {
  576. results[ key ] = value;
  577. }.bind( this, idx ));
  578. } else {
  579. results[ idx ] = value;
  580. }
  581. }
  582. }
  583. } else {
  584. results = {};
  585. for ( var key in object ) {
  586. if ( object.hasOwnProperty( key ) ) {
  587. var value = callback.call( thisObj || this, object[ key ], key );
  588. if ( value ) {
  589. fns.push( value );
  590. if ( value instanceof Promise ) {
  591. value.then( function( key, value ) {
  592. results[ key ] = value;
  593. }.bind( this, key ));
  594. } else {
  595. results[ key ] = value;
  596. }
  597. }
  598. }
  599. }
  600. }
  601. return Promise.all( fns ).then( function() {
  602. return results;
  603. });
  604. }
  605. function resolveURL( url, path ) {
  606. // Invalid URL
  607. if ( typeof url !== 'string' || url === '' )
  608. return '';
  609. // Absolute URL http://,https://,//
  610. if ( /^(https?:)?\/\//i.test( url ) ) {
  611. return url;
  612. }
  613. // Data URI
  614. if ( /^data:.*,.*$/i.test( url ) ) {
  615. return url;
  616. }
  617. // Blob URL
  618. if ( /^blob:.*$/i.test( url ) ) {
  619. return url;
  620. }
  621. // Relative URL
  622. return ( path || '' ) + url;
  623. }
  624. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  625. // throws a "maximum call stack size exceeded" error for large arrays.
  626. function convertUint8ArrayToString( array ) {
  627. var s = '';
  628. for ( var i = 0; i < array.length; i ++ ) {
  629. s += String.fromCharCode( array[ i ] );
  630. }
  631. return s;
  632. }
  633. // Three.js seems too dependent on attribute names so globally
  634. // replace those in the shader code
  635. function replaceTHREEShaderAttributes( shaderText, technique ) {
  636. // Expected technique attributes
  637. var attributes = {};
  638. for ( var attributeId in technique.attributes ) {
  639. var pname = technique.attributes[ attributeId ];
  640. var param = technique.parameters[ pname ];
  641. var atype = param.type;
  642. var semantic = param.semantic;
  643. attributes[ attributeId ] = {
  644. type: atype,
  645. semantic: semantic
  646. };
  647. }
  648. // Figure out which attributes to change in technique
  649. var shaderParams = technique.parameters;
  650. var shaderAttributes = technique.attributes;
  651. var params = {};
  652. for ( var attributeId in attributes ) {
  653. var pname = shaderAttributes[ attributeId ];
  654. var shaderParam = shaderParams[ pname ];
  655. var semantic = shaderParam.semantic;
  656. if ( semantic ) {
  657. params[ attributeId ] = shaderParam;
  658. }
  659. }
  660. for ( var pname in params ) {
  661. var param = params[ pname ];
  662. var semantic = param.semantic;
  663. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  664. switch ( semantic ) {
  665. case 'POSITION':
  666. shaderText = shaderText.replace( regEx, 'position' );
  667. break;
  668. case 'NORMAL':
  669. shaderText = shaderText.replace( regEx, 'normal' );
  670. break;
  671. case 'TEXCOORD_0':
  672. case 'TEXCOORD0':
  673. case 'TEXCOORD':
  674. shaderText = shaderText.replace( regEx, 'uv' );
  675. break;
  676. case 'TEXCOORD_1':
  677. shaderText = shaderText.replace( regEx, 'uv2' );
  678. break;
  679. case 'COLOR_0':
  680. case 'COLOR0':
  681. case 'COLOR':
  682. shaderText = shaderText.replace( regEx, 'color' );
  683. break;
  684. case 'WEIGHTS_0':
  685. case 'WEIGHT': // WEIGHT semantic deprecated.
  686. shaderText = shaderText.replace( regEx, 'skinWeight' );
  687. break;
  688. case 'JOINTS_0':
  689. case 'JOINT': // JOINT semantic deprecated.
  690. shaderText = shaderText.replace( regEx, 'skinIndex' );
  691. break;
  692. }
  693. }
  694. return shaderText;
  695. }
  696. function createDefaultMaterial() {
  697. return new THREE.MeshPhongMaterial( {
  698. color: 0x00000,
  699. emissive: 0x888888,
  700. specular: 0x000000,
  701. shininess: 0,
  702. transparent: false,
  703. depthTest: true,
  704. side: THREE.FrontSide
  705. } );
  706. }
  707. // Deferred constructor for RawShaderMaterial types
  708. function DeferredShaderMaterial( params ) {
  709. this.isDeferredShaderMaterial = true;
  710. this.params = params;
  711. }
  712. DeferredShaderMaterial.prototype.create = function () {
  713. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  714. for ( var uniformId in this.params.uniforms ) {
  715. var originalUniform = this.params.uniforms[ uniformId ];
  716. if ( originalUniform.value instanceof THREE.Texture ) {
  717. uniforms[ uniformId ].value = originalUniform.value;
  718. uniforms[ uniformId ].value.needsUpdate = true;
  719. }
  720. uniforms[ uniformId ].semantic = originalUniform.semantic;
  721. uniforms[ uniformId ].node = originalUniform.node;
  722. }
  723. this.params.uniforms = uniforms;
  724. return new THREE.RawShaderMaterial( this.params );
  725. };
  726. /* GLTF PARSER */
  727. function GLTFParser( json, extensions, options ) {
  728. this.json = json || {};
  729. this.extensions = extensions || {};
  730. this.options = options || {};
  731. // loader object cache
  732. this.cache = new GLTFRegistry();
  733. }
  734. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  735. var _dependencies = {};
  736. for ( var i = 0; i < dependencies.length; i ++ ) {
  737. var dependency = dependencies[ i ];
  738. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  739. var cached = this.cache.get( dependency );
  740. if ( cached !== undefined ) {
  741. _dependencies[ dependency ] = cached;
  742. } else if ( this[ fnName ] ) {
  743. var fn = this[ fnName ]();
  744. this.cache.add( dependency, fn );
  745. _dependencies[ dependency ] = fn;
  746. }
  747. }
  748. return _each( _dependencies, function ( dependency ) {
  749. return dependency;
  750. } );
  751. };
  752. GLTFParser.prototype.parse = function ( callback ) {
  753. var json = this.json;
  754. // Clear the loader cache
  755. this.cache.removeAll();
  756. // Fire the callback on complete
  757. this._withDependencies( [
  758. "scenes",
  759. "cameras",
  760. "animations"
  761. ] ).then( function ( dependencies ) {
  762. var scenes = [];
  763. for ( var name in dependencies.scenes ) {
  764. scenes.push( dependencies.scenes[ name ] );
  765. }
  766. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  767. var cameras = [];
  768. for ( var name in dependencies.cameras ) {
  769. var camera = dependencies.cameras[ name ];
  770. cameras.push( camera );
  771. }
  772. var animations = [];
  773. for ( var name in dependencies.animations ) {
  774. animations.push( dependencies.animations[ name ] );
  775. }
  776. callback( scene, scenes, cameras, animations );
  777. } );
  778. };
  779. GLTFParser.prototype.loadShaders = function () {
  780. var json = this.json;
  781. var options = this.options;
  782. return this._withDependencies( [
  783. "bufferViews"
  784. ] ).then( function ( dependencies ) {
  785. return _each( json.shaders, function ( shader ) {
  786. if ( shader.bufferView !== undefined ) {
  787. var bufferView = dependencies.bufferViews[ shader.bufferView ];
  788. var array = new Uint8Array( bufferView );
  789. return convertUint8ArrayToString( array );
  790. }
  791. return new Promise( function ( resolve ) {
  792. var loader = new THREE.FileLoader();
  793. loader.setResponseType( 'text' );
  794. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  795. resolve( shaderText );
  796. } );
  797. } );
  798. } );
  799. } );
  800. };
  801. GLTFParser.prototype.loadBuffers = function () {
  802. var json = this.json;
  803. var extensions = this.extensions;
  804. var options = this.options;
  805. return _each( json.buffers, function ( buffer, name ) {
  806. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  807. // If present, GLB container is required to be the first buffer.
  808. if ( buffer.uri === undefined && name === 0 ) {
  809. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  810. }
  811. return new Promise( function ( resolve ) {
  812. var loader = new THREE.FileLoader();
  813. loader.setResponseType( 'arraybuffer' );
  814. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  815. resolve( buffer );
  816. } );
  817. } );
  818. } else {
  819. console.warn( 'THREE.GLTF2Loader: ' + buffer.type + ' buffer type is not supported' );
  820. }
  821. } );
  822. };
  823. GLTFParser.prototype.loadBufferViews = function () {
  824. var json = this.json;
  825. return this._withDependencies( [
  826. "buffers"
  827. ] ).then( function ( dependencies ) {
  828. return _each( json.bufferViews, function ( bufferView ) {
  829. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  830. var byteLength = bufferView.byteLength || 0;
  831. var byteOffset = bufferView.byteOffset || 0;
  832. return arraybuffer.slice( byteOffset, byteOffset + byteLength );
  833. } );
  834. } );
  835. };
  836. GLTFParser.prototype.loadAccessors = function () {
  837. var json = this.json;
  838. return this._withDependencies( [
  839. "bufferViews"
  840. ] ).then( function ( dependencies ) {
  841. return _each( json.accessors, function ( accessor ) {
  842. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  843. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  844. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  845. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  846. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  847. var itemBytes = elementBytes * itemSize;
  848. var array;
  849. // The buffer is not interleaved if the stride is the item size in bytes.
  850. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  851. // Use the full buffer if it's interleaved.
  852. array = new TypedArray( arraybuffer );
  853. // Integer parameters to IB/IBA are in array elements, not bytes.
  854. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  855. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  856. } else {
  857. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  858. return new THREE.BufferAttribute( array, itemSize );
  859. }
  860. } );
  861. } );
  862. };
  863. GLTFParser.prototype.loadTextures = function () {
  864. var json = this.json;
  865. var options = this.options;
  866. return this._withDependencies( [
  867. "bufferViews"
  868. ] ).then( function ( dependencies ) {
  869. return _each( json.textures, function ( texture ) {
  870. if ( texture.source !== undefined ) {
  871. return new Promise( function ( resolve ) {
  872. var source = json.images[ texture.source ];
  873. var sourceUri = source.uri;
  874. var urlCreator;
  875. if ( source.bufferView !== undefined ) {
  876. var bufferView = dependencies.bufferViews[ source.bufferView ];
  877. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  878. urlCreator = window.URL || window.webkitURL;
  879. sourceUri = urlCreator.createObjectURL( blob );
  880. }
  881. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  882. if ( textureLoader === null ) {
  883. textureLoader = new THREE.TextureLoader();
  884. }
  885. textureLoader.setCrossOrigin( options.crossOrigin );
  886. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  887. if ( urlCreator !== undefined ) {
  888. urlCreator.revokeObjectURL( sourceUri );
  889. }
  890. _texture.flipY = false;
  891. if ( texture.name !== undefined ) _texture.name = texture.name;
  892. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  893. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  894. console.warn( 'THREE.GLTF2Loader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  895. 'internalFormat will be forced to be the same value as format.' );
  896. }
  897. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  898. var samplers = json.samplers || {};
  899. var sampler = samplers[ texture.sampler ] || {};
  900. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  901. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.NearestMipMapLinearFilter;
  902. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  903. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  904. resolve( _texture );
  905. }, undefined, function () {
  906. resolve();
  907. } );
  908. } );
  909. }
  910. } );
  911. } );
  912. };
  913. GLTFParser.prototype.loadMaterials = function () {
  914. var json = this.json;
  915. var extensions = this.extensions;
  916. return this._withDependencies( [
  917. "shaders",
  918. "textures"
  919. ] ).then( function ( dependencies ) {
  920. return _each( json.materials, function ( material ) {
  921. var materialType;
  922. var materialValues = {};
  923. var materialParams = {};
  924. var khr_material;
  925. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  926. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  927. }
  928. if ( khr_material ) {
  929. // don't copy over unused values to avoid material warning spam
  930. var keys = [ 'ambient', 'emission', 'transparent', 'transparency', 'doubleSided' ];
  931. switch ( khr_material.technique ) {
  932. case 'BLINN' :
  933. case 'PHONG' :
  934. materialType = THREE.MeshPhongMaterial;
  935. keys.push( 'diffuse', 'specular', 'shininess' );
  936. break;
  937. case 'LAMBERT' :
  938. materialType = THREE.MeshLambertMaterial;
  939. keys.push( 'diffuse' );
  940. break;
  941. case 'CONSTANT' :
  942. default :
  943. materialType = THREE.MeshBasicMaterial;
  944. break;
  945. }
  946. keys.forEach( function( v ) {
  947. if ( khr_material.values[ v ] !== undefined ) materialValues[ v ] = khr_material.values[ v ];
  948. } );
  949. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  950. materialParams.side = THREE.DoubleSide;
  951. }
  952. if ( khr_material.transparent || materialValues.transparent ) {
  953. materialParams.transparent = true;
  954. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  955. }
  956. } else if ( material.technique === undefined ) {
  957. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  958. materialType = THREE.ShaderMaterial;
  959. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].extendParams( materialParams, material, dependencies );
  960. } else if ( material.pbrMetallicRoughness !== undefined ) {
  961. // specification
  962. // https://github.com/sbtron/glTF/blob/30de0b365d1566b1bbd8b9c140f9e995d3203226/specification/2.0/README.md#metallic-roughness-material
  963. materialType = THREE.MeshStandardMaterial;
  964. if ( material.pbrMetallicRoughness !== undefined ) {
  965. var metallicRoughness = material.pbrMetallicRoughness;
  966. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  967. materialParams.opacity = 1.0;
  968. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  969. var array = metallicRoughness.baseColorFactor;
  970. materialParams.color.fromArray( array );
  971. materialParams.opacity = array[ 3 ];
  972. }
  973. if ( metallicRoughness.baseColorTexture !== undefined ) {
  974. materialParams.map = dependencies.textures[ metallicRoughness.baseColorTexture.index ];
  975. }
  976. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  977. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  978. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  979. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  980. // Note that currently metalnessMap would be entirely ignored because
  981. // Three.js and glTF specification use different texture channels for metalness
  982. // (Blue: Three.js, Red: glTF).
  983. // But glTF specification team is discussing if they can change.
  984. // Let's keep an eye on it so far.
  985. //
  986. // https://github.com/KhronosGroup/glTF/issues/857
  987. materialParams.metalnessMap = dependencies.textures[ textureIndex ];
  988. materialParams.roughnessMap = dependencies.textures[ textureIndex ];
  989. }
  990. }
  991. } else {
  992. materialType = THREE.MeshPhongMaterial;
  993. }
  994. if ( material.doubleSided === true ) {
  995. materialParams.side = THREE.DoubleSide;
  996. }
  997. if ( materialParams.opacity !== undefined && materialParams.opacity < 1.0 ||
  998. ( materialParams.map !== undefined &&
  999. ( materialParams.map.format === THREE.AlphaFormat ||
  1000. materialParams.map.format === THREE.RGBAFormat ||
  1001. materialParams.map.format === THREE.LuminanceAlphaFormat ) ) ) {
  1002. materialParams.transparent = true;
  1003. } else {
  1004. materialParams.transparent = false;
  1005. }
  1006. if ( material.normalTexture !== undefined ) {
  1007. materialParams.normalMap = dependencies.textures[ material.normalTexture.index ];
  1008. }
  1009. if ( material.occlusionTexture !== undefined ) {
  1010. materialParams.aoMap = dependencies.textures[ material.occlusionTexture.index ];
  1011. }
  1012. if ( material.emissiveTexture !== undefined ) {
  1013. materialParams.emissiveMap = dependencies.textures[ material.emissiveTexture.index ];
  1014. }
  1015. materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  1016. if ( material.emissiveFactor !== undefined ) {
  1017. materialParams.emissive.fromArray( material.emissiveFactor );
  1018. }
  1019. Object.assign( materialValues, material.values );
  1020. } else {
  1021. materialType = DeferredShaderMaterial;
  1022. var technique = json.techniques[ material.technique ];
  1023. materialParams.uniforms = {};
  1024. var program = json.programs[ technique.program ];
  1025. if ( program ) {
  1026. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  1027. if ( ! materialParams.fragmentShader ) {
  1028. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  1029. materialType = THREE.MeshPhongMaterial;
  1030. }
  1031. var vertexShader = dependencies.shaders[ program.vertexShader ];
  1032. if ( ! vertexShader ) {
  1033. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  1034. materialType = THREE.MeshPhongMaterial;
  1035. }
  1036. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  1037. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  1038. var uniforms = technique.uniforms;
  1039. for ( var uniformId in uniforms ) {
  1040. var pname = uniforms[ uniformId ];
  1041. var shaderParam = technique.parameters[ pname ];
  1042. var ptype = shaderParam.type;
  1043. if ( WEBGL_TYPE[ ptype ] ) {
  1044. var pcount = shaderParam.count;
  1045. var value;
  1046. if ( material.values !== undefined ) value = material.values[ pname ];
  1047. var uvalue = new WEBGL_TYPE[ ptype ]();
  1048. var usemantic = shaderParam.semantic;
  1049. var unode = shaderParam.node;
  1050. switch ( ptype ) {
  1051. case WEBGL_CONSTANTS.FLOAT:
  1052. uvalue = shaderParam.value;
  1053. if ( pname == "transparency" ) {
  1054. materialParams.transparent = true;
  1055. }
  1056. if ( value !== undefined ) {
  1057. uvalue = value;
  1058. }
  1059. break;
  1060. case WEBGL_CONSTANTS.FLOAT_VEC2:
  1061. case WEBGL_CONSTANTS.FLOAT_VEC3:
  1062. case WEBGL_CONSTANTS.FLOAT_VEC4:
  1063. case WEBGL_CONSTANTS.FLOAT_MAT3:
  1064. if ( shaderParam && shaderParam.value ) {
  1065. uvalue.fromArray( shaderParam.value );
  1066. }
  1067. if ( value ) {
  1068. uvalue.fromArray( value );
  1069. }
  1070. break;
  1071. case WEBGL_CONSTANTS.FLOAT_MAT2:
  1072. // what to do?
  1073. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  1074. break;
  1075. case WEBGL_CONSTANTS.FLOAT_MAT4:
  1076. if ( pcount ) {
  1077. uvalue = new Array( pcount );
  1078. for ( var mi = 0; mi < pcount; mi ++ ) {
  1079. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  1080. }
  1081. if ( shaderParam && shaderParam.value ) {
  1082. var m4v = shaderParam.value;
  1083. uvalue.fromArray( m4v );
  1084. }
  1085. if ( value ) {
  1086. uvalue.fromArray( value );
  1087. }
  1088. } else {
  1089. if ( shaderParam && shaderParam.value ) {
  1090. var m4 = shaderParam.value;
  1091. uvalue.fromArray( m4 );
  1092. }
  1093. if ( value ) {
  1094. uvalue.fromArray( value );
  1095. }
  1096. }
  1097. break;
  1098. case WEBGL_CONSTANTS.SAMPLER_2D:
  1099. if ( value !== undefined ) {
  1100. uvalue = dependencies.textures[ value ];
  1101. } else if ( shaderParam.value !== undefined ) {
  1102. uvalue = dependencies.textures[ shaderParam.value ];
  1103. } else {
  1104. uvalue = null;
  1105. }
  1106. break;
  1107. }
  1108. materialParams.uniforms[ uniformId ] = {
  1109. value: uvalue,
  1110. semantic: usemantic,
  1111. node: unode
  1112. };
  1113. } else {
  1114. throw new Error( "Unknown shader uniform param type: " + ptype );
  1115. }
  1116. }
  1117. var states = technique.states || {};
  1118. var enables = states.enable || [];
  1119. var functions = states.functions || {};
  1120. var enableCullFace = false;
  1121. var enableDepthTest = false;
  1122. var enableBlend = false;
  1123. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  1124. var enable = enables[ i ];
  1125. switch ( STATES_ENABLES[ enable ] ) {
  1126. case 'CULL_FACE':
  1127. enableCullFace = true;
  1128. break;
  1129. case 'DEPTH_TEST':
  1130. enableDepthTest = true;
  1131. break;
  1132. case 'BLEND':
  1133. enableBlend = true;
  1134. break;
  1135. // TODO: implement
  1136. case 'SCISSOR_TEST':
  1137. case 'POLYGON_OFFSET_FILL':
  1138. case 'SAMPLE_ALPHA_TO_COVERAGE':
  1139. break;
  1140. default:
  1141. throw new Error( "Unknown technique.states.enable: " + enable );
  1142. }
  1143. }
  1144. if ( enableCullFace ) {
  1145. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  1146. } else {
  1147. materialParams.side = THREE.DoubleSide;
  1148. }
  1149. materialParams.depthTest = enableDepthTest;
  1150. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  1151. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  1152. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  1153. materialParams.transparent = enableBlend;
  1154. var blendEquationSeparate = functions.blendEquationSeparate;
  1155. if ( blendEquationSeparate !== undefined ) {
  1156. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  1157. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  1158. } else {
  1159. materialParams.blendEquation = THREE.AddEquation;
  1160. materialParams.blendEquationAlpha = THREE.AddEquation;
  1161. }
  1162. var blendFuncSeparate = functions.blendFuncSeparate;
  1163. if ( blendFuncSeparate !== undefined ) {
  1164. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  1165. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  1166. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  1167. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  1168. } else {
  1169. materialParams.blendSrc = THREE.OneFactor;
  1170. materialParams.blendDst = THREE.ZeroFactor;
  1171. materialParams.blendSrcAlpha = THREE.OneFactor;
  1172. materialParams.blendDstAlpha = THREE.ZeroFactor;
  1173. }
  1174. }
  1175. }
  1176. if ( Array.isArray( materialValues.diffuse ) ) {
  1177. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  1178. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  1179. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  1180. }
  1181. delete materialParams.diffuse;
  1182. if ( typeof( materialValues.reflective ) === 'string' ) {
  1183. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  1184. }
  1185. if ( typeof( materialValues.bump ) === 'string' ) {
  1186. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  1187. }
  1188. if ( Array.isArray( materialValues.emission ) ) {
  1189. if ( materialType === THREE.MeshBasicMaterial ) {
  1190. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  1191. } else {
  1192. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  1193. }
  1194. } else if ( typeof( materialValues.emission ) === 'string' ) {
  1195. if ( materialType === THREE.MeshBasicMaterial ) {
  1196. materialParams.map = dependencies.textures[ materialValues.emission ];
  1197. } else {
  1198. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  1199. }
  1200. }
  1201. if ( Array.isArray( materialValues.specular ) ) {
  1202. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  1203. } else if ( typeof( materialValues.specular ) === 'string' ) {
  1204. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  1205. }
  1206. if ( materialValues.shininess !== undefined ) {
  1207. materialParams.shininess = materialValues.shininess;
  1208. }
  1209. var _material;
  1210. if ( materialType === THREE.ShaderMaterial ) {
  1211. _material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1212. } else {
  1213. _material = new materialType( materialParams );
  1214. }
  1215. if ( material.name !== undefined ) _material.name = material.name;
  1216. return _material;
  1217. } );
  1218. } );
  1219. };
  1220. GLTFParser.prototype.loadMeshes = function () {
  1221. var json = this.json;
  1222. return this._withDependencies( [
  1223. "accessors",
  1224. "materials"
  1225. ] ).then( function ( dependencies ) {
  1226. return _each( json.meshes, function ( mesh ) {
  1227. var group = new THREE.Group();
  1228. if ( mesh.name !== undefined ) group.name = mesh.name;
  1229. if ( mesh.extras ) group.userData = mesh.extras;
  1230. var primitives = mesh.primitives || [];
  1231. for ( var name in primitives ) {
  1232. var primitive = primitives[ name ];
  1233. var material = primitive.material !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  1234. var geometry;
  1235. var meshNode;
  1236. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  1237. geometry = new THREE.BufferGeometry();
  1238. var attributes = primitive.attributes;
  1239. for ( var attributeId in attributes ) {
  1240. var attributeEntry = attributes[ attributeId ];
  1241. if ( attributeEntry === undefined ) return;
  1242. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1243. switch ( attributeId ) {
  1244. case 'POSITION':
  1245. geometry.addAttribute( 'position', bufferAttribute );
  1246. break;
  1247. case 'NORMAL':
  1248. geometry.addAttribute( 'normal', bufferAttribute );
  1249. break;
  1250. case 'TEXCOORD_0':
  1251. case 'TEXCOORD0':
  1252. case 'TEXCOORD':
  1253. geometry.addAttribute( 'uv', bufferAttribute );
  1254. break;
  1255. case 'TEXCOORD_1':
  1256. geometry.addAttribute( 'uv2', bufferAttribute );
  1257. break;
  1258. case 'COLOR_0':
  1259. case 'COLOR0':
  1260. case 'COLOR':
  1261. geometry.addAttribute( 'color', bufferAttribute );
  1262. break;
  1263. case 'WEIGHTS_0':
  1264. case 'WEIGHT': // WEIGHT semantic deprecated.
  1265. geometry.addAttribute( 'skinWeight', bufferAttribute );
  1266. break;
  1267. case 'JOINTS_0':
  1268. case 'JOINT': // JOINT semantic deprecated.
  1269. geometry.addAttribute( 'skinIndex', bufferAttribute );
  1270. break;
  1271. }
  1272. }
  1273. if ( primitive.indices !== undefined ) {
  1274. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1275. }
  1276. if ( material.aoMap !== undefined
  1277. && geometry.attributes.uv2 === undefined
  1278. && geometry.attributes.uv !== undefined ) {
  1279. console.log( 'GLTF2Loader: Duplicating UVs to support aoMap.' );
  1280. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1281. }
  1282. meshNode = new THREE.Mesh( geometry, material );
  1283. meshNode.castShadow = true;
  1284. if ( primitive.targets !== undefined ) {
  1285. geometry.morphTargets = [];
  1286. var targets = primitive.targets;
  1287. var morphAttributes = geometry.morphAttributes;
  1288. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1289. var target = targets[ i ];
  1290. geometry.morphTargets.push( { name: 'morphTarget' + i } );
  1291. if ( target.POSITION !== undefined ) {
  1292. material.morphTargets = true;
  1293. if ( morphAttributes.position === undefined ) morphAttributes.position = [];
  1294. // Three.js morph formula is
  1295. // position
  1296. // + weight0 * ( morphTarget0 - position )
  1297. // + weight1 * ( morphTarget1 - position )
  1298. // ...
  1299. // while the glTF one is
  1300. // position
  1301. // + weight0 * morphTarget0
  1302. // + weight1 * morphTarget1
  1303. // ...
  1304. // then adding position to morphTarget.
  1305. // morphTarget should depend on mesh, so cloning attribute.
  1306. var attribute = dependencies.accessors[ target.POSITION ].clone();
  1307. var position = geometry.attributes.position;
  1308. for ( var j = 0, jl = attribute.array.length; j < jl; j ++ ) {
  1309. attribute.array[ j ] += position.array[ j ];
  1310. }
  1311. morphAttributes.position.push( attribute );
  1312. }
  1313. if ( target.NORMAL !== undefined ) {
  1314. material.morphNormals = true;
  1315. if ( morphAttributes.normal === undefined ) morphAttributes.normal = [];
  1316. // see target.POSITION's comment
  1317. var attribute = dependencies.accessors[ target.NORMAL ].clone();
  1318. var normal = geometry.attributes.normal;
  1319. for ( var j = 0, jl = attribute.array.length; j < jl; j ++ ) {
  1320. attribute.array[ j ] += normal.array[ j ];
  1321. }
  1322. morphAttributes.normal.push( attribute );
  1323. }
  1324. // TODO: implement
  1325. if ( target.TANGENT !== undefined ) {
  1326. }
  1327. }
  1328. meshNode.updateMorphTargets();
  1329. if ( mesh.weights !== undefined ) {
  1330. for ( var i = 0, il = mesh.weights.length; i < il; i ++ ) {
  1331. meshNode.morphTargetInfluences[ i ] = mesh.weights[ i ];
  1332. }
  1333. }
  1334. }
  1335. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1336. geometry = new THREE.BufferGeometry();
  1337. var attributes = primitive.attributes;
  1338. for ( var attributeId in attributes ) {
  1339. var attributeEntry = attributes[ attributeId ];
  1340. if ( ! attributeEntry ) return;
  1341. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1342. switch ( attributeId ) {
  1343. case 'POSITION':
  1344. geometry.addAttribute( 'position', bufferAttribute );
  1345. break;
  1346. case 'COLOR_0':
  1347. case 'COLOR0':
  1348. case 'COLOR':
  1349. geometry.addAttribute( 'color', bufferAttribute );
  1350. break;
  1351. }
  1352. }
  1353. if ( primitive.indices !== undefined ) {
  1354. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1355. meshNode = new THREE.LineSegments( geometry, material );
  1356. } else {
  1357. meshNode = new THREE.Line( geometry, material );
  1358. }
  1359. } else {
  1360. throw new Error( "Only triangular and line primitives are supported" );
  1361. }
  1362. if ( geometry.attributes.color !== undefined ) {
  1363. material.vertexColors = THREE.VertexColors;
  1364. material.needsUpdate = true;
  1365. }
  1366. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1367. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1368. group.add( meshNode );
  1369. }
  1370. return group;
  1371. } );
  1372. } );
  1373. };
  1374. GLTFParser.prototype.loadCameras = function () {
  1375. var json = this.json;
  1376. return _each( json.cameras, function ( camera ) {
  1377. if ( camera.type == "perspective" && camera.perspective ) {
  1378. var yfov = camera.perspective.yfov;
  1379. var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1;
  1380. // According to COLLADA spec...
  1381. // aspectRatio = xfov / yfov
  1382. var xfov = yfov * aspectRatio;
  1383. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  1384. if ( camera.name !== undefined ) _camera.name = camera.name;
  1385. if ( camera.extras ) _camera.userData = camera.extras;
  1386. return _camera;
  1387. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  1388. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  1389. if ( camera.name !== undefined ) _camera.name = camera.name;
  1390. if ( camera.extras ) _camera.userData = camera.extras;
  1391. return _camera;
  1392. }
  1393. } );
  1394. };
  1395. GLTFParser.prototype.loadSkins = function () {
  1396. var json = this.json;
  1397. return this._withDependencies( [
  1398. "accessors"
  1399. ] ).then( function ( dependencies ) {
  1400. return _each( json.skins, function ( skin ) {
  1401. var bindShapeMatrix = new THREE.Matrix4();
  1402. if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix );
  1403. var _skin = {
  1404. bindShapeMatrix: bindShapeMatrix,
  1405. jointNames: skin.jointNames,
  1406. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1407. };
  1408. return _skin;
  1409. } );
  1410. } );
  1411. };
  1412. GLTFParser.prototype.loadAnimations = function () {
  1413. var json = this.json;
  1414. return this._withDependencies( [
  1415. "accessors",
  1416. "nodes"
  1417. ] ).then( function ( dependencies ) {
  1418. return _each( json.animations, function ( animation, animationId ) {
  1419. var tracks = [];
  1420. for ( var channelId in animation.channels ) {
  1421. var channel = animation.channels[ channelId ];
  1422. var sampler = animation.samplers[ channel.sampler ];
  1423. if ( sampler ) {
  1424. var target = channel.target;
  1425. var name = target.node || target.id; // NOTE: target.id is deprecated.
  1426. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1427. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1428. var inputAccessor = dependencies.accessors[ input ];
  1429. var outputAccessor = dependencies.accessors[ output ];
  1430. var node = dependencies.nodes[ name ];
  1431. if ( node ) {
  1432. node.updateMatrix();
  1433. node.matrixAutoUpdate = true;
  1434. var TypedKeyframeTrack;
  1435. switch ( PATH_PROPERTIES[ target.path ] ) {
  1436. case PATH_PROPERTIES.weights:
  1437. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  1438. break;
  1439. case PATH_PROPERTIES.rotation:
  1440. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  1441. break;
  1442. case PATH_PROPERTIES.position:
  1443. case PATH_PROPERTIES.scale:
  1444. default:
  1445. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  1446. break;
  1447. }
  1448. var targetName = node.name ? node.name : node.uuid;
  1449. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1450. var targetNames = [];
  1451. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1452. // node should be THREE.Group here but
  1453. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  1454. // the property of a mesh object under node.
  1455. // So finding targets here.
  1456. node.traverse( function ( object ) {
  1457. if ( object.isMesh === true && object.material.morphTargets === true ) {
  1458. targetNames.push( object.name ? object.name : object.uuid );
  1459. }
  1460. } );
  1461. } else {
  1462. targetNames.push( targetName );
  1463. }
  1464. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1465. // buffers before creating a truncated copy to keep. Because buffers may
  1466. // be reused by other tracks, make copies here.
  1467. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1468. tracks.push( new TypedKeyframeTrack(
  1469. targetNames[ i ] + '.' + PATH_PROPERTIES[ target.path ],
  1470. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1471. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1472. interpolation
  1473. ) );
  1474. }
  1475. }
  1476. }
  1477. }
  1478. var name = animation.name !== undefined ? animation.name : "animation_" + animationId;
  1479. return new THREE.AnimationClip( name, undefined, tracks );
  1480. } );
  1481. } );
  1482. };
  1483. GLTFParser.prototype.loadNodes = function () {
  1484. var json = this.json;
  1485. var extensions = this.extensions;
  1486. var scope = this;
  1487. return _each( json.nodes, function ( node ) {
  1488. var matrix = new THREE.Matrix4();
  1489. var _node;
  1490. if ( node.jointName ) {
  1491. _node = new THREE.Bone();
  1492. _node.name = node.name !== undefined ? node.name : node.jointName;
  1493. _node.jointName = node.jointName;
  1494. } else {
  1495. _node = new THREE.Object3D();
  1496. if ( node.name !== undefined ) _node.name = node.name;
  1497. }
  1498. if ( node.extras ) _node.userData = node.extras;
  1499. if ( node.matrix !== undefined ) {
  1500. matrix.fromArray( node.matrix );
  1501. _node.applyMatrix( matrix );
  1502. } else {
  1503. if ( node.translation !== undefined ) {
  1504. _node.position.fromArray( node.translation );
  1505. }
  1506. if ( node.rotation !== undefined ) {
  1507. _node.quaternion.fromArray( node.rotation );
  1508. }
  1509. if ( node.scale !== undefined ) {
  1510. _node.scale.fromArray( node.scale );
  1511. }
  1512. }
  1513. return _node;
  1514. } ).then( function ( __nodes ) {
  1515. return scope._withDependencies( [
  1516. "meshes",
  1517. "skins",
  1518. "cameras"
  1519. ] ).then( function ( dependencies ) {
  1520. return _each( __nodes, function ( _node, nodeId ) {
  1521. var node = json.nodes[ nodeId ];
  1522. var meshes;
  1523. if ( node.mesh !== undefined) {
  1524. meshes = [ node.mesh ];
  1525. } else if ( node.meshes !== undefined ) {
  1526. console.warn( 'GLTF2Loader: Legacy glTF file detected. Nodes may have no more than 1 mesh.' );
  1527. meshes = node.meshes;
  1528. }
  1529. if ( meshes !== undefined ) {
  1530. for ( var meshId in meshes ) {
  1531. var mesh = meshes[ meshId ];
  1532. var group = dependencies.meshes[ mesh ];
  1533. if ( group === undefined ) {
  1534. console.warn( 'GLTF2Loader: Couldn\'t find node "' + mesh + '".' );
  1535. continue;
  1536. }
  1537. for ( var childrenId in group.children ) {
  1538. var child = group.children[ childrenId ];
  1539. // clone Mesh to add to _node
  1540. var originalMaterial = child.material;
  1541. var originalGeometry = child.geometry;
  1542. var originalUserData = child.userData;
  1543. var originalName = child.name;
  1544. var material;
  1545. if ( originalMaterial.isDeferredShaderMaterial ) {
  1546. originalMaterial = material = originalMaterial.create();
  1547. } else {
  1548. material = originalMaterial;
  1549. }
  1550. switch ( child.type ) {
  1551. case 'LineSegments':
  1552. child = new THREE.LineSegments( originalGeometry, material );
  1553. break;
  1554. case 'LineLoop':
  1555. child = new THREE.LineLoop( originalGeometry, material );
  1556. break;
  1557. case 'Line':
  1558. child = new THREE.Line( originalGeometry, material );
  1559. break;
  1560. default:
  1561. child = new THREE.Mesh( originalGeometry, material );
  1562. }
  1563. child.castShadow = true;
  1564. child.userData = originalUserData;
  1565. child.name = originalName;
  1566. var skinEntry;
  1567. if ( node.skin !== undefined ) {
  1568. skinEntry = dependencies.skins[ node.skin ];
  1569. }
  1570. // Replace Mesh with SkinnedMesh in library
  1571. if ( skinEntry ) {
  1572. var getJointNode = function ( jointId ) {
  1573. var keys = Object.keys( __nodes );
  1574. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1575. var n = __nodes[ keys[ i ] ];
  1576. if ( n.jointName === jointId ) return n;
  1577. }
  1578. return null;
  1579. };
  1580. var geometry = originalGeometry;
  1581. var material = originalMaterial;
  1582. material.skinning = true;
  1583. child = new THREE.SkinnedMesh( geometry, material, false );
  1584. child.castShadow = true;
  1585. child.userData = originalUserData;
  1586. child.name = originalName;
  1587. var bones = [];
  1588. var boneInverses = [];
  1589. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  1590. var jointId = skinEntry.jointNames[ i ];
  1591. var jointNode = getJointNode( jointId );
  1592. if ( jointNode ) {
  1593. bones.push( jointNode );
  1594. var m = skinEntry.inverseBindMatrices.array;
  1595. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1596. boneInverses.push( mat );
  1597. } else {
  1598. console.warn( "WARNING: joint: '" + jointId + "' could not be found" );
  1599. }
  1600. }
  1601. child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  1602. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  1603. var children = parentJson[ property ];
  1604. if ( children === undefined ) return;
  1605. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1606. var nodeId = children[ i ];
  1607. var bone = __nodes[ nodeId ];
  1608. var boneJson = json.nodes[ nodeId ];
  1609. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  1610. parentObject.add( bone );
  1611. buildBoneGraph( boneJson, bone, 'children' );
  1612. }
  1613. }
  1614. };
  1615. buildBoneGraph( node, child, 'skeletons' );
  1616. }
  1617. _node.add( child );
  1618. }
  1619. }
  1620. }
  1621. if ( node.camera !== undefined ) {
  1622. var camera = dependencies.cameras[ node.camera ];
  1623. _node.add( camera );
  1624. }
  1625. if ( node.extensions
  1626. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  1627. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  1628. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  1629. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  1630. _node.add( light );
  1631. }
  1632. return _node;
  1633. } );
  1634. } );
  1635. } );
  1636. };
  1637. GLTFParser.prototype.loadScenes = function () {
  1638. var json = this.json;
  1639. var extensions = this.extensions;
  1640. // scene node hierachy builder
  1641. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1642. var _node = allNodes[ nodeId ];
  1643. parentObject.add( _node );
  1644. var node = json.nodes[ nodeId ];
  1645. if ( node.children ) {
  1646. var children = node.children;
  1647. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1648. var child = children[ i ];
  1649. buildNodeHierachy( child, _node, allNodes );
  1650. }
  1651. }
  1652. }
  1653. return this._withDependencies( [
  1654. "nodes"
  1655. ] ).then( function ( dependencies ) {
  1656. return _each( json.scenes, function ( scene ) {
  1657. var _scene = new THREE.Scene();
  1658. if ( scene.name !== undefined ) _scene.name = scene.name;
  1659. if ( scene.extras ) _scene.userData = scene.extras;
  1660. var nodes = scene.nodes || [];
  1661. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1662. var nodeId = nodes[ i ];
  1663. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1664. }
  1665. _scene.traverse( function ( child ) {
  1666. // Register raw material meshes with GLTF2Loader.Shaders
  1667. if ( child.material && child.material.isRawShaderMaterial ) {
  1668. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1669. child.onBeforeRender = function(renderer, scene, camera){
  1670. this.gltfShader.update(scene, camera);
  1671. };
  1672. }
  1673. // for Specular-Glossiness.
  1674. if ( child.material && child.material.type === 'ShaderMaterial' ) {
  1675. child.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1676. }
  1677. } );
  1678. return _scene;
  1679. } );
  1680. } );
  1681. };
  1682. return GLTF2Loader;
  1683. } )();