GLTF2Loader.js 65 KB

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