GLTF2Loader.js 65 KB

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