LegacyGLTFLoader.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211
  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. */
  7. THREE.LegacyGLTFLoader = ( function () {
  8. function LegacyGLTFLoader( manager ) {
  9. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10. }
  11. LegacyGLTFLoader.prototype = {
  12. constructor: LegacyGLTFLoader,
  13. crossOrigin: 'Anonymous',
  14. load: function ( url, onLoad, onProgress, onError ) {
  15. var scope = this;
  16. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  17. var loader = new THREE.FileLoader( scope.manager );
  18. loader.setResponseType( 'arraybuffer' );
  19. loader.load( url, function ( data ) {
  20. scope.parse( data, path, onLoad );
  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, path, callback ) {
  30. var content;
  31. var extensions = {};
  32. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  33. if ( magic === BINARY_EXTENSION_HEADER_DEFAULTS.magic ) {
  34. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  35. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  36. } else {
  37. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  38. }
  39. var json = JSON.parse( content );
  40. if ( json.extensionsUsed && json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  41. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  42. }
  43. console.time( 'LegacyGLTFLoader' );
  44. var parser = new GLTFParser( json, extensions, {
  45. path: path || this.path,
  46. crossOrigin: this.crossOrigin
  47. } );
  48. parser.parse( function ( scene, scenes, cameras, animations ) {
  49. console.timeEnd( 'LegacyGLTFLoader' );
  50. var glTF = {
  51. "scene": scene,
  52. "scenes": scenes,
  53. "cameras": cameras,
  54. "animations": animations
  55. };
  56. callback( glTF );
  57. } );
  58. }
  59. };
  60. /* GLTFREGISTRY */
  61. function GLTFRegistry() {
  62. var objects = {};
  63. return {
  64. get: function ( key ) {
  65. return objects[ key ];
  66. },
  67. add: function ( key, object ) {
  68. objects[ key ] = object;
  69. },
  70. remove: function ( key ) {
  71. delete objects[ key ];
  72. },
  73. removeAll: function () {
  74. objects = {};
  75. },
  76. update: function ( scene, camera ) {
  77. for ( var name in objects ) {
  78. var object = objects[ name ];
  79. if ( object.update ) {
  80. object.update( scene, camera );
  81. }
  82. }
  83. }
  84. };
  85. }
  86. /* GLTFSHADERS */
  87. LegacyGLTFLoader.Shaders = {
  88. update: function () {
  89. console.warn( 'THREE.LegacyGLTFLoader.Shaders has been deprecated, and now updates automatically.' );
  90. }
  91. };
  92. /* GLTFSHADER */
  93. function GLTFShader( targetNode, allNodes ) {
  94. var boundUniforms = {};
  95. // bind each uniform to its source node
  96. var uniforms = targetNode.material.uniforms;
  97. for ( var uniformId in uniforms ) {
  98. var uniform = uniforms[ uniformId ];
  99. if ( uniform.semantic ) {
  100. var sourceNodeRef = uniform.node;
  101. var sourceNode = targetNode;
  102. if ( sourceNodeRef ) {
  103. sourceNode = allNodes[ sourceNodeRef ];
  104. }
  105. boundUniforms[ uniformId ] = {
  106. semantic: uniform.semantic,
  107. sourceNode: sourceNode,
  108. targetNode: targetNode,
  109. uniform: uniform
  110. };
  111. }
  112. }
  113. this.boundUniforms = boundUniforms;
  114. this._m4 = new THREE.Matrix4();
  115. }
  116. // Update - update all the uniform values
  117. GLTFShader.prototype.update = function ( scene, camera ) {
  118. var boundUniforms = this.boundUniforms;
  119. for ( var name in boundUniforms ) {
  120. var boundUniform = boundUniforms[ name ];
  121. switch ( boundUniform.semantic ) {
  122. case "MODELVIEW":
  123. var m4 = boundUniform.uniform.value;
  124. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  125. break;
  126. case "MODELVIEWINVERSETRANSPOSE":
  127. var m3 = boundUniform.uniform.value;
  128. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  129. m3.getNormalMatrix( this._m4 );
  130. break;
  131. case "PROJECTION":
  132. var m4 = boundUniform.uniform.value;
  133. m4.copy( camera.projectionMatrix );
  134. break;
  135. case "JOINTMATRIX":
  136. var m4v = boundUniform.uniform.value;
  137. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  138. // So it goes like this:
  139. // SkinnedMesh world matrix is already baked into MODELVIEW;
  140. // transform joints to local space,
  141. // then transform using joint's inverse
  142. m4v[ mi ]
  143. .getInverse( boundUniform.sourceNode.matrixWorld )
  144. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  145. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  146. .multiply( boundUniform.targetNode.bindMatrix );
  147. }
  148. break;
  149. default :
  150. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  151. break;
  152. }
  153. }
  154. };
  155. /* ANIMATION */
  156. LegacyGLTFLoader.Animations = {
  157. update: function () {
  158. console.warn( 'THREE.LegacyGLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  159. }
  160. };
  161. /*********************************/
  162. /********** EXTENSIONS ***********/
  163. /*********************************/
  164. var EXTENSIONS = {
  165. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  166. KHR_MATERIALS_COMMON: 'KHR_materials_common'
  167. };
  168. /* MATERIALS COMMON EXTENSION */
  169. function GLTFMaterialsCommonExtension( json ) {
  170. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  171. this.lights = {};
  172. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) || {};
  173. var lights = extension.lights || {};
  174. for ( var lightId in lights ) {
  175. var light = lights[ lightId ];
  176. var lightNode;
  177. var lightParams = light[ light.type ];
  178. var color = new THREE.Color().fromArray( lightParams.color );
  179. switch ( light.type ) {
  180. case "directional":
  181. lightNode = new THREE.DirectionalLight( color );
  182. lightNode.position.set( 0, 0, 1 );
  183. break;
  184. case "point":
  185. lightNode = new THREE.PointLight( color );
  186. break;
  187. case "spot":
  188. lightNode = new THREE.SpotLight( color );
  189. lightNode.position.set( 0, 0, 1 );
  190. break;
  191. case "ambient":
  192. lightNode = new THREE.AmbientLight( color );
  193. break;
  194. }
  195. if ( lightNode ) {
  196. this.lights[ lightId ] = lightNode;
  197. }
  198. }
  199. }
  200. /* BINARY EXTENSION */
  201. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  202. var BINARY_EXTENSION_HEADER_DEFAULTS = { magic: 'glTF', version: 1, contentFormat: 0 };
  203. var BINARY_EXTENSION_HEADER_LENGTH = 20;
  204. function GLTFBinaryExtension( data ) {
  205. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  206. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  207. var header = {
  208. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  209. version: headerView.getUint32( 4, true ),
  210. length: headerView.getUint32( 8, true ),
  211. contentLength: headerView.getUint32( 12, true ),
  212. contentFormat: headerView.getUint32( 16, true )
  213. };
  214. for ( var key in BINARY_EXTENSION_HEADER_DEFAULTS ) {
  215. var value = BINARY_EXTENSION_HEADER_DEFAULTS[ key ];
  216. if ( header[ key ] !== value ) {
  217. throw new Error( 'Unsupported glTF-Binary header: Expected "%s" to be "%s".', key, value );
  218. }
  219. }
  220. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH, header.contentLength );
  221. this.header = header;
  222. this.content = THREE.LoaderUtils.decodeText( contentArray );
  223. this.body = data.slice( BINARY_EXTENSION_HEADER_LENGTH + header.contentLength, header.length );
  224. }
  225. GLTFBinaryExtension.prototype.loadShader = function ( shader, bufferViews ) {
  226. var bufferView = bufferViews[ shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].bufferView ];
  227. var array = new Uint8Array( bufferView );
  228. return THREE.LoaderUtils.decodeText( array );
  229. };
  230. /*********************************/
  231. /********** INTERNALS ************/
  232. /*********************************/
  233. /* CONSTANTS */
  234. var WEBGL_CONSTANTS = {
  235. FLOAT: 5126,
  236. //FLOAT_MAT2: 35674,
  237. FLOAT_MAT3: 35675,
  238. FLOAT_MAT4: 35676,
  239. FLOAT_VEC2: 35664,
  240. FLOAT_VEC3: 35665,
  241. FLOAT_VEC4: 35666,
  242. LINEAR: 9729,
  243. REPEAT: 10497,
  244. SAMPLER_2D: 35678,
  245. TRIANGLES: 4,
  246. LINES: 1,
  247. UNSIGNED_BYTE: 5121,
  248. UNSIGNED_SHORT: 5123,
  249. VERTEX_SHADER: 35633,
  250. FRAGMENT_SHADER: 35632
  251. };
  252. var WEBGL_TYPE = {
  253. 5126: Number,
  254. //35674: THREE.Matrix2,
  255. 35675: THREE.Matrix3,
  256. 35676: THREE.Matrix4,
  257. 35664: THREE.Vector2,
  258. 35665: THREE.Vector3,
  259. 35666: THREE.Vector4,
  260. 35678: THREE.Texture
  261. };
  262. var WEBGL_COMPONENT_TYPES = {
  263. 5120: Int8Array,
  264. 5121: Uint8Array,
  265. 5122: Int16Array,
  266. 5123: Uint16Array,
  267. 5125: Uint32Array,
  268. 5126: Float32Array
  269. };
  270. var WEBGL_FILTERS = {
  271. 9728: THREE.NearestFilter,
  272. 9729: THREE.LinearFilter,
  273. 9984: THREE.NearestMipMapNearestFilter,
  274. 9985: THREE.LinearMipMapNearestFilter,
  275. 9986: THREE.NearestMipMapLinearFilter,
  276. 9987: THREE.LinearMipMapLinearFilter
  277. };
  278. var WEBGL_WRAPPINGS = {
  279. 33071: THREE.ClampToEdgeWrapping,
  280. 33648: THREE.MirroredRepeatWrapping,
  281. 10497: THREE.RepeatWrapping
  282. };
  283. var WEBGL_TEXTURE_FORMATS = {
  284. 6406: THREE.AlphaFormat,
  285. 6407: THREE.RGBFormat,
  286. 6408: THREE.RGBAFormat,
  287. 6409: THREE.LuminanceFormat,
  288. 6410: THREE.LuminanceAlphaFormat
  289. };
  290. var WEBGL_TEXTURE_DATATYPES = {
  291. 5121: THREE.UnsignedByteType,
  292. 32819: THREE.UnsignedShort4444Type,
  293. 32820: THREE.UnsignedShort5551Type,
  294. 33635: THREE.UnsignedShort565Type
  295. };
  296. var WEBGL_SIDES = {
  297. 1028: THREE.BackSide, // Culling front
  298. 1029: THREE.FrontSide // Culling back
  299. //1032: THREE.NoSide // Culling front and back, what to do?
  300. };
  301. var WEBGL_DEPTH_FUNCS = {
  302. 512: THREE.NeverDepth,
  303. 513: THREE.LessDepth,
  304. 514: THREE.EqualDepth,
  305. 515: THREE.LessEqualDepth,
  306. 516: THREE.GreaterEqualDepth,
  307. 517: THREE.NotEqualDepth,
  308. 518: THREE.GreaterEqualDepth,
  309. 519: THREE.AlwaysDepth
  310. };
  311. var WEBGL_BLEND_EQUATIONS = {
  312. 32774: THREE.AddEquation,
  313. 32778: THREE.SubtractEquation,
  314. 32779: THREE.ReverseSubtractEquation
  315. };
  316. var WEBGL_BLEND_FUNCS = {
  317. 0: THREE.ZeroFactor,
  318. 1: THREE.OneFactor,
  319. 768: THREE.SrcColorFactor,
  320. 769: THREE.OneMinusSrcColorFactor,
  321. 770: THREE.SrcAlphaFactor,
  322. 771: THREE.OneMinusSrcAlphaFactor,
  323. 772: THREE.DstAlphaFactor,
  324. 773: THREE.OneMinusDstAlphaFactor,
  325. 774: THREE.DstColorFactor,
  326. 775: THREE.OneMinusDstColorFactor,
  327. 776: THREE.SrcAlphaSaturateFactor
  328. // The followings are not supported by Three.js yet
  329. //32769: CONSTANT_COLOR,
  330. //32770: ONE_MINUS_CONSTANT_COLOR,
  331. //32771: CONSTANT_ALPHA,
  332. //32772: ONE_MINUS_CONSTANT_COLOR
  333. };
  334. var WEBGL_TYPE_SIZES = {
  335. 'SCALAR': 1,
  336. 'VEC2': 2,
  337. 'VEC3': 3,
  338. 'VEC4': 4,
  339. 'MAT2': 4,
  340. 'MAT3': 9,
  341. 'MAT4': 16
  342. };
  343. var PATH_PROPERTIES = {
  344. scale: 'scale',
  345. translation: 'position',
  346. rotation: 'quaternion'
  347. };
  348. var INTERPOLATION = {
  349. LINEAR: THREE.InterpolateLinear,
  350. STEP: THREE.InterpolateDiscrete
  351. };
  352. var STATES_ENABLES = {
  353. 2884: 'CULL_FACE',
  354. 2929: 'DEPTH_TEST',
  355. 3042: 'BLEND',
  356. 3089: 'SCISSOR_TEST',
  357. 32823: 'POLYGON_OFFSET_FILL',
  358. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  359. };
  360. /* UTILITY FUNCTIONS */
  361. function _each( object, callback, thisObj ) {
  362. if ( !object ) {
  363. return Promise.resolve();
  364. }
  365. var results;
  366. var fns = [];
  367. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  368. results = [];
  369. var length = object.length;
  370. for ( var idx = 0; idx < length; idx ++ ) {
  371. var value = callback.call( thisObj || this, object[ idx ], idx );
  372. if ( value ) {
  373. fns.push( value );
  374. if ( value instanceof Promise ) {
  375. value.then( function( key, value ) {
  376. results[ key ] = value;
  377. }.bind( this, idx ));
  378. } else {
  379. results[ idx ] = value;
  380. }
  381. }
  382. }
  383. } else {
  384. results = {};
  385. for ( var key in object ) {
  386. if ( object.hasOwnProperty( key ) ) {
  387. var value = callback.call( thisObj || this, object[ key ], key );
  388. if ( value ) {
  389. fns.push( value );
  390. if ( value instanceof Promise ) {
  391. value.then( function( key, value ) {
  392. results[ key ] = value;
  393. }.bind( this, key ));
  394. } else {
  395. results[ key ] = value;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. return Promise.all( fns ).then( function() {
  402. return results;
  403. });
  404. }
  405. function resolveURL( url, path ) {
  406. // Invalid URL
  407. if ( typeof url !== 'string' || url === '' )
  408. return '';
  409. // Absolute URL http://,https://,//
  410. if ( /^(https?:)?\/\//i.test( url ) ) {
  411. return url;
  412. }
  413. // Data URI
  414. if ( /^data:.*,.*$/i.test( url ) ) {
  415. return url;
  416. }
  417. // Relative URL
  418. return ( path || '' ) + url;
  419. }
  420. // Three.js seems too dependent on attribute names so globally
  421. // replace those in the shader code
  422. function replaceTHREEShaderAttributes( shaderText, technique ) {
  423. // Expected technique attributes
  424. var attributes = {};
  425. for ( var attributeId in technique.attributes ) {
  426. var pname = technique.attributes[ attributeId ];
  427. var param = technique.parameters[ pname ];
  428. var atype = param.type;
  429. var semantic = param.semantic;
  430. attributes[ attributeId ] = {
  431. type: atype,
  432. semantic: semantic
  433. };
  434. }
  435. // Figure out which attributes to change in technique
  436. var shaderParams = technique.parameters;
  437. var shaderAttributes = technique.attributes;
  438. var params = {};
  439. for ( var attributeId in attributes ) {
  440. var pname = shaderAttributes[ attributeId ];
  441. var shaderParam = shaderParams[ pname ];
  442. var semantic = shaderParam.semantic;
  443. if ( semantic ) {
  444. params[ attributeId ] = shaderParam;
  445. }
  446. }
  447. for ( var pname in params ) {
  448. var param = params[ pname ];
  449. var semantic = param.semantic;
  450. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  451. switch ( semantic ) {
  452. case "POSITION":
  453. shaderText = shaderText.replace( regEx, 'position' );
  454. break;
  455. case "NORMAL":
  456. shaderText = shaderText.replace( regEx, 'normal' );
  457. break;
  458. case 'TEXCOORD_0':
  459. case 'TEXCOORD0':
  460. case 'TEXCOORD':
  461. shaderText = shaderText.replace( regEx, 'uv' );
  462. break;
  463. case 'TEXCOORD_1':
  464. shaderText = shaderText.replace( regEx, 'uv2' );
  465. break;
  466. case 'COLOR_0':
  467. case 'COLOR0':
  468. case 'COLOR':
  469. shaderText = shaderText.replace( regEx, 'color' );
  470. break;
  471. case "WEIGHT":
  472. shaderText = shaderText.replace( regEx, 'skinWeight' );
  473. break;
  474. case "JOINT":
  475. shaderText = shaderText.replace( regEx, 'skinIndex' );
  476. break;
  477. }
  478. }
  479. return shaderText;
  480. }
  481. function createDefaultMaterial() {
  482. return new THREE.MeshPhongMaterial( {
  483. color: 0x00000,
  484. emissive: 0x888888,
  485. specular: 0x000000,
  486. shininess: 0,
  487. transparent: false,
  488. depthTest: true,
  489. side: THREE.FrontSide
  490. } );
  491. }
  492. // Deferred constructor for RawShaderMaterial types
  493. function DeferredShaderMaterial( params ) {
  494. this.isDeferredShaderMaterial = true;
  495. this.params = params;
  496. }
  497. DeferredShaderMaterial.prototype.create = function () {
  498. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  499. for ( var uniformId in this.params.uniforms ) {
  500. var originalUniform = this.params.uniforms[ uniformId ];
  501. if ( originalUniform.value instanceof THREE.Texture ) {
  502. uniforms[ uniformId ].value = originalUniform.value;
  503. uniforms[ uniformId ].value.needsUpdate = true;
  504. }
  505. uniforms[ uniformId ].semantic = originalUniform.semantic;
  506. uniforms[ uniformId ].node = originalUniform.node;
  507. }
  508. this.params.uniforms = uniforms;
  509. return new THREE.RawShaderMaterial( this.params );
  510. };
  511. /* GLTF PARSER */
  512. function GLTFParser( json, extensions, options ) {
  513. this.json = json || {};
  514. this.extensions = extensions || {};
  515. this.options = options || {};
  516. // loader object cache
  517. this.cache = new GLTFRegistry();
  518. }
  519. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  520. var _dependencies = {};
  521. for ( var i = 0; i < dependencies.length; i ++ ) {
  522. var dependency = dependencies[ i ];
  523. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  524. var cached = this.cache.get( dependency );
  525. if ( cached !== undefined ) {
  526. _dependencies[ dependency ] = cached;
  527. } else if ( this[ fnName ] ) {
  528. var fn = this[ fnName ]();
  529. this.cache.add( dependency, fn );
  530. _dependencies[ dependency ] = fn;
  531. }
  532. }
  533. return _each( _dependencies, function ( dependency ) {
  534. return dependency;
  535. } );
  536. };
  537. GLTFParser.prototype.parse = function ( callback ) {
  538. var json = this.json;
  539. // Clear the loader cache
  540. this.cache.removeAll();
  541. // Fire the callback on complete
  542. this._withDependencies( [
  543. "scenes",
  544. "cameras",
  545. "animations"
  546. ] ).then( function ( dependencies ) {
  547. var scenes = [];
  548. for ( var name in dependencies.scenes ) {
  549. scenes.push( dependencies.scenes[ name ] );
  550. }
  551. var scene = json.scene !== undefined ? dependencies.scenes[ json.scene ] : scenes[ 0 ];
  552. var cameras = [];
  553. for ( var name in dependencies.cameras ) {
  554. var camera = dependencies.cameras[ name ];
  555. cameras.push( camera );
  556. }
  557. var animations = [];
  558. for ( var name in dependencies.animations ) {
  559. animations.push( dependencies.animations[ name ] );
  560. }
  561. callback( scene, scenes, cameras, animations );
  562. } );
  563. };
  564. GLTFParser.prototype.loadShaders = function () {
  565. var json = this.json;
  566. var extensions = this.extensions;
  567. var options = this.options;
  568. return this._withDependencies( [
  569. "bufferViews"
  570. ] ).then( function ( dependencies ) {
  571. return _each( json.shaders, function ( shader ) {
  572. if ( shader.extensions && shader.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  573. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].loadShader( shader, dependencies.bufferViews );
  574. }
  575. return new Promise( function ( resolve ) {
  576. var loader = new THREE.FileLoader();
  577. loader.setResponseType( 'text' );
  578. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  579. resolve( shaderText );
  580. } );
  581. } );
  582. } );
  583. } );
  584. };
  585. GLTFParser.prototype.loadBuffers = function () {
  586. var json = this.json;
  587. var extensions = this.extensions;
  588. var options = this.options;
  589. return _each( json.buffers, function ( buffer, name ) {
  590. if ( name === BINARY_EXTENSION_BUFFER_NAME ) {
  591. return extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body;
  592. }
  593. if ( buffer.type === 'arraybuffer' || buffer.type === undefined ) {
  594. return new Promise( function ( resolve ) {
  595. var loader = new THREE.FileLoader();
  596. loader.setResponseType( 'arraybuffer' );
  597. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  598. resolve( buffer );
  599. } );
  600. } );
  601. } else {
  602. console.warn( 'THREE.LegacyGLTFLoader: ' + buffer.type + ' buffer type is not supported' );
  603. }
  604. } );
  605. };
  606. GLTFParser.prototype.loadBufferViews = function () {
  607. var json = this.json;
  608. return this._withDependencies( [
  609. "buffers"
  610. ] ).then( function ( dependencies ) {
  611. return _each( json.bufferViews, function ( bufferView ) {
  612. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  613. var byteLength = bufferView.byteLength !== undefined ? bufferView.byteLength : 0;
  614. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + byteLength );
  615. } );
  616. } );
  617. };
  618. GLTFParser.prototype.loadAccessors = function () {
  619. var json = this.json;
  620. return this._withDependencies( [
  621. "bufferViews"
  622. ] ).then( function ( dependencies ) {
  623. return _each( json.accessors, function ( accessor ) {
  624. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  625. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  626. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  627. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  628. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  629. var itemBytes = elementBytes * itemSize;
  630. // The buffer is not interleaved if the stride is the item size in bytes.
  631. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  632. // Use the full buffer if it's interleaved.
  633. var array = new TypedArray( arraybuffer );
  634. // Integer parameters to IB/IBA are in array elements, not bytes.
  635. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  636. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  637. } else {
  638. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  639. return new THREE.BufferAttribute( array, itemSize );
  640. }
  641. } );
  642. } );
  643. };
  644. GLTFParser.prototype.loadTextures = function () {
  645. var json = this.json;
  646. var extensions = this.extensions;
  647. var options = this.options;
  648. return this._withDependencies( [
  649. "bufferViews"
  650. ] ).then( function ( dependencies ) {
  651. return _each( json.textures, function ( texture ) {
  652. if ( texture.source ) {
  653. return new Promise( function ( resolve ) {
  654. var source = json.images[ texture.source ];
  655. var sourceUri = source.uri;
  656. var isObjectURL = false;
  657. if ( source.extensions && source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ] ) {
  658. var metadata = source.extensions[ EXTENSIONS.KHR_BINARY_GLTF ];
  659. var bufferView = dependencies.bufferViews[ metadata.bufferView ];
  660. var blob = new Blob( [ bufferView ], { type: metadata.mimeType } );
  661. sourceUri = URL.createObjectURL( blob );
  662. isObjectURL = true;
  663. }
  664. var textureLoader = THREE.Loader.Handlers.get( sourceUri );
  665. if ( textureLoader === null ) {
  666. textureLoader = new THREE.TextureLoader();
  667. }
  668. textureLoader.setCrossOrigin( options.crossOrigin );
  669. textureLoader.load( resolveURL( sourceUri, options.path ), function ( _texture ) {
  670. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  671. _texture.flipY = false;
  672. if ( texture.name !== undefined ) _texture.name = texture.name;
  673. _texture.format = texture.format !== undefined ? WEBGL_TEXTURE_FORMATS[ texture.format ] : THREE.RGBAFormat;
  674. if ( texture.internalFormat !== undefined && _texture.format !== WEBGL_TEXTURE_FORMATS[ texture.internalFormat ] ) {
  675. console.warn( 'THREE.LegacyGLTFLoader: Three.js doesn\'t support texture internalFormat which is different from texture format. ' +
  676. 'internalFormat will be forced to be the same value as format.' );
  677. }
  678. _texture.type = texture.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ texture.type ] : THREE.UnsignedByteType;
  679. if ( texture.sampler ) {
  680. var sampler = json.samplers[ texture.sampler ];
  681. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  682. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.NearestMipMapLinearFilter;
  683. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  684. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  685. }
  686. resolve( _texture );
  687. }, undefined, function () {
  688. if ( isObjectURL ) URL.revokeObjectURL( sourceUri );
  689. resolve();
  690. } );
  691. } );
  692. }
  693. } );
  694. } );
  695. };
  696. GLTFParser.prototype.loadMaterials = function () {
  697. var json = this.json;
  698. return this._withDependencies( [
  699. "shaders",
  700. "textures"
  701. ] ).then( function ( dependencies ) {
  702. return _each( json.materials, function ( material ) {
  703. var materialType;
  704. var materialValues = {};
  705. var materialParams = {};
  706. var khr_material;
  707. if ( material.extensions && material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  708. khr_material = material.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  709. }
  710. if ( khr_material ) {
  711. // don't copy over unused values to avoid material warning spam
  712. var keys = [ 'ambient', 'emission', 'transparent', 'transparency', 'doubleSided' ];
  713. switch ( khr_material.technique ) {
  714. case 'BLINN' :
  715. case 'PHONG' :
  716. materialType = THREE.MeshPhongMaterial;
  717. keys.push( 'diffuse', 'specular', 'shininess' );
  718. break;
  719. case 'LAMBERT' :
  720. materialType = THREE.MeshLambertMaterial;
  721. keys.push( 'diffuse' );
  722. break;
  723. case 'CONSTANT' :
  724. default :
  725. materialType = THREE.MeshBasicMaterial;
  726. break;
  727. }
  728. keys.forEach( function( v ) {
  729. if ( khr_material.values[ v ] !== undefined ) materialValues[ v ] = khr_material.values[ v ];
  730. } );
  731. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  732. materialParams.side = THREE.DoubleSide;
  733. }
  734. if ( khr_material.transparent || materialValues.transparent ) {
  735. materialParams.transparent = true;
  736. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  737. }
  738. } else if ( material.technique === undefined ) {
  739. materialType = THREE.MeshPhongMaterial;
  740. Object.assign( materialValues, material.values );
  741. } else {
  742. materialType = DeferredShaderMaterial;
  743. var technique = json.techniques[ material.technique ];
  744. materialParams.uniforms = {};
  745. var program = json.programs[ technique.program ];
  746. if ( program ) {
  747. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  748. if ( ! materialParams.fragmentShader ) {
  749. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  750. materialType = THREE.MeshPhongMaterial;
  751. }
  752. var vertexShader = dependencies.shaders[ program.vertexShader ];
  753. if ( ! vertexShader ) {
  754. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  755. materialType = THREE.MeshPhongMaterial;
  756. }
  757. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  758. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  759. var uniforms = technique.uniforms;
  760. for ( var uniformId in uniforms ) {
  761. var pname = uniforms[ uniformId ];
  762. var shaderParam = technique.parameters[ pname ];
  763. var ptype = shaderParam.type;
  764. if ( WEBGL_TYPE[ ptype ] ) {
  765. var pcount = shaderParam.count;
  766. var value;
  767. if ( material.values !== undefined ) value = material.values[ pname ];
  768. var uvalue = new WEBGL_TYPE[ ptype ]();
  769. var usemantic = shaderParam.semantic;
  770. var unode = shaderParam.node;
  771. switch ( ptype ) {
  772. case WEBGL_CONSTANTS.FLOAT:
  773. uvalue = shaderParam.value;
  774. if ( pname == "transparency" ) {
  775. materialParams.transparent = true;
  776. }
  777. if ( value !== undefined ) {
  778. uvalue = value;
  779. }
  780. break;
  781. case WEBGL_CONSTANTS.FLOAT_VEC2:
  782. case WEBGL_CONSTANTS.FLOAT_VEC3:
  783. case WEBGL_CONSTANTS.FLOAT_VEC4:
  784. case WEBGL_CONSTANTS.FLOAT_MAT3:
  785. if ( shaderParam && shaderParam.value ) {
  786. uvalue.fromArray( shaderParam.value );
  787. }
  788. if ( value ) {
  789. uvalue.fromArray( value );
  790. }
  791. break;
  792. case WEBGL_CONSTANTS.FLOAT_MAT2:
  793. // what to do?
  794. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  795. break;
  796. case WEBGL_CONSTANTS.FLOAT_MAT4:
  797. if ( pcount ) {
  798. uvalue = new Array( pcount );
  799. for ( var mi = 0; mi < pcount; mi ++ ) {
  800. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  801. }
  802. if ( shaderParam && shaderParam.value ) {
  803. var m4v = shaderParam.value;
  804. uvalue.fromArray( m4v );
  805. }
  806. if ( value ) {
  807. uvalue.fromArray( value );
  808. }
  809. } else {
  810. if ( shaderParam && shaderParam.value ) {
  811. var m4 = shaderParam.value;
  812. uvalue.fromArray( m4 );
  813. }
  814. if ( value ) {
  815. uvalue.fromArray( value );
  816. }
  817. }
  818. break;
  819. case WEBGL_CONSTANTS.SAMPLER_2D:
  820. if ( value !== undefined ) {
  821. uvalue = dependencies.textures[ value ];
  822. } else if ( shaderParam.value !== undefined ) {
  823. uvalue = dependencies.textures[ shaderParam.value ];
  824. } else {
  825. uvalue = null;
  826. }
  827. break;
  828. }
  829. materialParams.uniforms[ uniformId ] = {
  830. value: uvalue,
  831. semantic: usemantic,
  832. node: unode
  833. };
  834. } else {
  835. throw new Error( "Unknown shader uniform param type: " + ptype );
  836. }
  837. }
  838. var states = technique.states || {};
  839. var enables = states.enable || [];
  840. var functions = states.functions || {};
  841. var enableCullFace = false;
  842. var enableDepthTest = false;
  843. var enableBlend = false;
  844. for ( var i = 0, il = enables.length; i < il; i ++ ) {
  845. var enable = enables[ i ];
  846. switch ( STATES_ENABLES[ enable ] ) {
  847. case 'CULL_FACE':
  848. enableCullFace = true;
  849. break;
  850. case 'DEPTH_TEST':
  851. enableDepthTest = true;
  852. break;
  853. case 'BLEND':
  854. enableBlend = true;
  855. break;
  856. // TODO: implement
  857. case 'SCISSOR_TEST':
  858. case 'POLYGON_OFFSET_FILL':
  859. case 'SAMPLE_ALPHA_TO_COVERAGE':
  860. break;
  861. default:
  862. throw new Error( "Unknown technique.states.enable: " + enable );
  863. }
  864. }
  865. if ( enableCullFace ) {
  866. materialParams.side = functions.cullFace !== undefined ? WEBGL_SIDES[ functions.cullFace ] : THREE.FrontSide;
  867. } else {
  868. materialParams.side = THREE.DoubleSide;
  869. }
  870. materialParams.depthTest = enableDepthTest;
  871. materialParams.depthFunc = functions.depthFunc !== undefined ? WEBGL_DEPTH_FUNCS[ functions.depthFunc ] : THREE.LessDepth;
  872. materialParams.depthWrite = functions.depthMask !== undefined ? functions.depthMask[ 0 ] : true;
  873. materialParams.blending = enableBlend ? THREE.CustomBlending : THREE.NoBlending;
  874. materialParams.transparent = enableBlend;
  875. var blendEquationSeparate = functions.blendEquationSeparate;
  876. if ( blendEquationSeparate !== undefined ) {
  877. materialParams.blendEquation = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 0 ] ];
  878. materialParams.blendEquationAlpha = WEBGL_BLEND_EQUATIONS[ blendEquationSeparate[ 1 ] ];
  879. } else {
  880. materialParams.blendEquation = THREE.AddEquation;
  881. materialParams.blendEquationAlpha = THREE.AddEquation;
  882. }
  883. var blendFuncSeparate = functions.blendFuncSeparate;
  884. if ( blendFuncSeparate !== undefined ) {
  885. materialParams.blendSrc = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 0 ] ];
  886. materialParams.blendDst = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 1 ] ];
  887. materialParams.blendSrcAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 2 ] ];
  888. materialParams.blendDstAlpha = WEBGL_BLEND_FUNCS[ blendFuncSeparate[ 3 ] ];
  889. } else {
  890. materialParams.blendSrc = THREE.OneFactor;
  891. materialParams.blendDst = THREE.ZeroFactor;
  892. materialParams.blendSrcAlpha = THREE.OneFactor;
  893. materialParams.blendDstAlpha = THREE.ZeroFactor;
  894. }
  895. }
  896. }
  897. if ( Array.isArray( materialValues.diffuse ) ) {
  898. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  899. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  900. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  901. }
  902. delete materialParams.diffuse;
  903. if ( typeof( materialValues.reflective ) === 'string' ) {
  904. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  905. }
  906. if ( typeof( materialValues.bump ) === 'string' ) {
  907. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  908. }
  909. if ( Array.isArray( materialValues.emission ) ) {
  910. if ( materialType === THREE.MeshBasicMaterial ) {
  911. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  912. } else {
  913. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  914. }
  915. } else if ( typeof( materialValues.emission ) === 'string' ) {
  916. if ( materialType === THREE.MeshBasicMaterial ) {
  917. materialParams.map = dependencies.textures[ materialValues.emission ];
  918. } else {
  919. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  920. }
  921. }
  922. if ( Array.isArray( materialValues.specular ) ) {
  923. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  924. } else if ( typeof( materialValues.specular ) === 'string' ) {
  925. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  926. }
  927. if ( materialValues.shininess !== undefined ) {
  928. materialParams.shininess = materialValues.shininess;
  929. }
  930. var _material = new materialType( materialParams );
  931. if ( material.name !== undefined ) _material.name = material.name;
  932. return _material;
  933. } );
  934. } );
  935. };
  936. GLTFParser.prototype.loadMeshes = function () {
  937. var json = this.json;
  938. return this._withDependencies( [
  939. "accessors",
  940. "materials"
  941. ] ).then( function ( dependencies ) {
  942. return _each( json.meshes, function ( mesh ) {
  943. var group = new THREE.Group();
  944. if ( mesh.name !== undefined ) group.name = mesh.name;
  945. if ( mesh.extras ) group.userData = mesh.extras;
  946. var primitives = mesh.primitives || [];
  947. for ( var name in primitives ) {
  948. var primitive = primitives[ name ];
  949. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  950. var geometry = new THREE.BufferGeometry();
  951. var attributes = primitive.attributes;
  952. for ( var attributeId in attributes ) {
  953. var attributeEntry = attributes[ attributeId ];
  954. if ( ! attributeEntry ) return;
  955. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  956. switch ( attributeId ) {
  957. case 'POSITION':
  958. geometry.addAttribute( 'position', bufferAttribute );
  959. break;
  960. case 'NORMAL':
  961. geometry.addAttribute( 'normal', bufferAttribute );
  962. break;
  963. case 'TEXCOORD_0':
  964. case 'TEXCOORD0':
  965. case 'TEXCOORD':
  966. geometry.addAttribute( 'uv', bufferAttribute );
  967. break;
  968. case 'TEXCOORD_1':
  969. geometry.addAttribute( 'uv2', bufferAttribute );
  970. break;
  971. case 'COLOR_0':
  972. case 'COLOR0':
  973. case 'COLOR':
  974. geometry.addAttribute( 'color', bufferAttribute );
  975. break;
  976. case 'WEIGHT':
  977. geometry.addAttribute( 'skinWeight', bufferAttribute );
  978. break;
  979. case 'JOINT':
  980. geometry.addAttribute( 'skinIndex', bufferAttribute );
  981. break;
  982. default:
  983. if ( ! primitive.material ) break;
  984. var material = json.materials[ primitive.material ];
  985. if ( ! material.technique ) break;
  986. var parameters = json.techniques[ material.technique ].parameters || {};
  987. for( var attributeName in parameters ) {
  988. if ( parameters [ attributeName ][ 'semantic' ] === attributeId ) {
  989. geometry.addAttribute( attributeName, bufferAttribute );
  990. }
  991. }
  992. }
  993. }
  994. if ( primitive.indices ) {
  995. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  996. }
  997. var material = dependencies.materials !== undefined ? dependencies.materials[ primitive.material ] : createDefaultMaterial();
  998. var meshNode = new THREE.Mesh( geometry, material );
  999. meshNode.castShadow = true;
  1000. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1001. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1002. group.add( meshNode );
  1003. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1004. var geometry = new THREE.BufferGeometry();
  1005. var attributes = primitive.attributes;
  1006. for ( var attributeId in attributes ) {
  1007. var attributeEntry = attributes[ attributeId ];
  1008. if ( ! attributeEntry ) return;
  1009. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  1010. switch ( attributeId ) {
  1011. case 'POSITION':
  1012. geometry.addAttribute( 'position', bufferAttribute );
  1013. break;
  1014. case 'COLOR_0':
  1015. case 'COLOR0':
  1016. case 'COLOR':
  1017. geometry.addAttribute( 'color', bufferAttribute );
  1018. break;
  1019. }
  1020. }
  1021. var material = dependencies.materials[ primitive.material ];
  1022. var meshNode;
  1023. if ( primitive.indices ) {
  1024. geometry.setIndex( dependencies.accessors[ primitive.indices ] );
  1025. meshNode = new THREE.LineSegments( geometry, material );
  1026. } else {
  1027. meshNode = new THREE.Line( geometry, material );
  1028. }
  1029. meshNode.name = ( name === "0" ? group.name : group.name + name );
  1030. if ( primitive.extras ) meshNode.userData = primitive.extras;
  1031. group.add( meshNode );
  1032. } else {
  1033. console.warn( "Only triangular and line primitives are supported" );
  1034. }
  1035. }
  1036. return group;
  1037. } );
  1038. } );
  1039. };
  1040. GLTFParser.prototype.loadCameras = function () {
  1041. var json = this.json;
  1042. return _each( json.cameras, function ( camera ) {
  1043. if ( camera.type == "perspective" && camera.perspective ) {
  1044. var yfov = camera.perspective.yfov;
  1045. var aspectRatio = camera.perspective.aspectRatio !== undefined ? camera.perspective.aspectRatio : 1;
  1046. // According to COLLADA spec...
  1047. // aspectRatio = xfov / yfov
  1048. var xfov = yfov * aspectRatio;
  1049. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  1050. if ( camera.name !== undefined ) _camera.name = camera.name;
  1051. if ( camera.extras ) _camera.userData = camera.extras;
  1052. return _camera;
  1053. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  1054. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  1055. if ( camera.name !== undefined ) _camera.name = camera.name;
  1056. if ( camera.extras ) _camera.userData = camera.extras;
  1057. return _camera;
  1058. }
  1059. } );
  1060. };
  1061. GLTFParser.prototype.loadSkins = function () {
  1062. var json = this.json;
  1063. return this._withDependencies( [
  1064. "accessors"
  1065. ] ).then( function ( dependencies ) {
  1066. return _each( json.skins, function ( skin ) {
  1067. var bindShapeMatrix = new THREE.Matrix4();
  1068. if ( skin.bindShapeMatrix !== undefined ) bindShapeMatrix.fromArray( skin.bindShapeMatrix );
  1069. var _skin = {
  1070. bindShapeMatrix: bindShapeMatrix,
  1071. jointNames: skin.jointNames,
  1072. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  1073. };
  1074. return _skin;
  1075. } );
  1076. } );
  1077. };
  1078. GLTFParser.prototype.loadAnimations = function () {
  1079. var json = this.json;
  1080. return this._withDependencies( [
  1081. "accessors",
  1082. "nodes"
  1083. ] ).then( function ( dependencies ) {
  1084. return _each( json.animations, function ( animation, animationId ) {
  1085. var tracks = [];
  1086. for ( var channelId in animation.channels ) {
  1087. var channel = animation.channels[ channelId ];
  1088. var sampler = animation.samplers[ channel.sampler ];
  1089. if ( sampler ) {
  1090. var target = channel.target;
  1091. var name = target.id;
  1092. var input = animation.parameters !== undefined ? animation.parameters[ sampler.input ] : sampler.input;
  1093. var output = animation.parameters !== undefined ? animation.parameters[ sampler.output ] : sampler.output;
  1094. var inputAccessor = dependencies.accessors[ input ];
  1095. var outputAccessor = dependencies.accessors[ output ];
  1096. var node = dependencies.nodes[ name ];
  1097. if ( node ) {
  1098. node.updateMatrix();
  1099. node.matrixAutoUpdate = true;
  1100. var TypedKeyframeTrack = PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.rotation
  1101. ? THREE.QuaternionKeyframeTrack
  1102. : THREE.VectorKeyframeTrack;
  1103. var targetName = node.name ? node.name : node.uuid;
  1104. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  1105. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  1106. // buffers before creating a truncated copy to keep. Because buffers may
  1107. // be reused by other tracks, make copies here.
  1108. tracks.push( new TypedKeyframeTrack(
  1109. targetName + '.' + PATH_PROPERTIES[ target.path ],
  1110. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  1111. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  1112. interpolation
  1113. ) );
  1114. }
  1115. }
  1116. }
  1117. var name = animation.name !== undefined ? animation.name : "animation_" + animationId;
  1118. return new THREE.AnimationClip( name, undefined, tracks );
  1119. } );
  1120. } );
  1121. };
  1122. GLTFParser.prototype.loadNodes = function () {
  1123. var json = this.json;
  1124. var extensions = this.extensions;
  1125. var scope = this;
  1126. return _each( json.nodes, function ( node ) {
  1127. var matrix = new THREE.Matrix4();
  1128. var _node;
  1129. if ( node.jointName ) {
  1130. _node = new THREE.Bone();
  1131. _node.name = node.name !== undefined ? node.name : node.jointName;
  1132. _node.jointName = node.jointName;
  1133. } else {
  1134. _node = new THREE.Object3D();
  1135. if ( node.name !== undefined ) _node.name = node.name;
  1136. }
  1137. if ( node.extras ) _node.userData = node.extras;
  1138. if ( node.matrix !== undefined ) {
  1139. matrix.fromArray( node.matrix );
  1140. _node.applyMatrix( matrix );
  1141. } else {
  1142. if ( node.translation !== undefined ) {
  1143. _node.position.fromArray( node.translation );
  1144. }
  1145. if ( node.rotation !== undefined ) {
  1146. _node.quaternion.fromArray( node.rotation );
  1147. }
  1148. if ( node.scale !== undefined ) {
  1149. _node.scale.fromArray( node.scale );
  1150. }
  1151. }
  1152. return _node;
  1153. } ).then( function ( __nodes ) {
  1154. return scope._withDependencies( [
  1155. "meshes",
  1156. "skins",
  1157. "cameras"
  1158. ] ).then( function ( dependencies ) {
  1159. return _each( __nodes, function ( _node, nodeId ) {
  1160. var node = json.nodes[ nodeId ];
  1161. if ( node.meshes !== undefined ) {
  1162. for ( var meshId in node.meshes ) {
  1163. var mesh = node.meshes[ meshId ];
  1164. var group = dependencies.meshes[ mesh ];
  1165. if ( group === undefined ) {
  1166. console.warn( 'LegacyGLTFLoader: Couldn\'t find node "' + mesh + '".' );
  1167. continue;
  1168. }
  1169. for ( var childrenId in group.children ) {
  1170. var child = group.children[ childrenId ];
  1171. // clone Mesh to add to _node
  1172. var originalMaterial = child.material;
  1173. var originalGeometry = child.geometry;
  1174. var originalUserData = child.userData;
  1175. var originalName = child.name;
  1176. var material;
  1177. if ( originalMaterial.isDeferredShaderMaterial ) {
  1178. originalMaterial = material = originalMaterial.create();
  1179. } else {
  1180. material = originalMaterial;
  1181. }
  1182. switch ( child.type ) {
  1183. case 'LineSegments':
  1184. child = new THREE.LineSegments( originalGeometry, material );
  1185. break;
  1186. case 'LineLoop':
  1187. child = new THREE.LineLoop( originalGeometry, material );
  1188. break;
  1189. case 'Line':
  1190. child = new THREE.Line( originalGeometry, material );
  1191. break;
  1192. default:
  1193. child = new THREE.Mesh( originalGeometry, material );
  1194. }
  1195. child.castShadow = true;
  1196. child.userData = originalUserData;
  1197. child.name = originalName;
  1198. var skinEntry;
  1199. if ( node.skin ) {
  1200. skinEntry = dependencies.skins[ node.skin ];
  1201. }
  1202. // Replace Mesh with SkinnedMesh in library
  1203. if ( skinEntry ) {
  1204. var getJointNode = function ( jointId ) {
  1205. var keys = Object.keys( __nodes );
  1206. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1207. var n = __nodes[ keys[ i ] ];
  1208. if ( n.jointName === jointId ) return n;
  1209. }
  1210. return null;
  1211. };
  1212. var geometry = originalGeometry;
  1213. var material = originalMaterial;
  1214. material.skinning = true;
  1215. child = new THREE.SkinnedMesh( geometry, material );
  1216. child.castShadow = true;
  1217. child.userData = originalUserData;
  1218. child.name = originalName;
  1219. var bones = [];
  1220. var boneInverses = [];
  1221. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  1222. var jointId = skinEntry.jointNames[ i ];
  1223. var jointNode = getJointNode( jointId );
  1224. if ( jointNode ) {
  1225. bones.push( jointNode );
  1226. var m = skinEntry.inverseBindMatrices.array;
  1227. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  1228. boneInverses.push( mat );
  1229. } else {
  1230. console.warn( "WARNING: joint: '" + jointId + "' could not be found" );
  1231. }
  1232. }
  1233. child.bind( new THREE.Skeleton( bones, boneInverses ), skinEntry.bindShapeMatrix );
  1234. var buildBoneGraph = function ( parentJson, parentObject, property ) {
  1235. var children = parentJson[ property ];
  1236. if ( children === undefined ) return;
  1237. for ( var i = 0, il = children.length; i < il; i ++ ) {
  1238. var nodeId = children[ i ];
  1239. var bone = __nodes[ nodeId ];
  1240. var boneJson = json.nodes[ nodeId ];
  1241. if ( bone !== undefined && bone.isBone === true && boneJson !== undefined ) {
  1242. parentObject.add( bone );
  1243. buildBoneGraph( boneJson, bone, 'children' );
  1244. }
  1245. }
  1246. };
  1247. buildBoneGraph( node, child, 'skeletons' );
  1248. }
  1249. _node.add( child );
  1250. }
  1251. }
  1252. }
  1253. if ( node.camera !== undefined ) {
  1254. var camera = dependencies.cameras[ node.camera ];
  1255. _node.add( camera );
  1256. }
  1257. if ( node.extensions
  1258. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ]
  1259. && node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ) {
  1260. var extensionLights = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].lights;
  1261. var light = extensionLights[ node.extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ].light ];
  1262. _node.add( light );
  1263. }
  1264. return _node;
  1265. } );
  1266. } );
  1267. } );
  1268. };
  1269. GLTFParser.prototype.loadScenes = function () {
  1270. var json = this.json;
  1271. // scene node hierachy builder
  1272. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  1273. var _node = allNodes[ nodeId ];
  1274. parentObject.add( _node );
  1275. var node = json.nodes[ nodeId ];
  1276. if ( node.children ) {
  1277. var children = node.children;
  1278. for ( var i = 0, l = children.length; i < l; i ++ ) {
  1279. var child = children[ i ];
  1280. buildNodeHierachy( child, _node, allNodes );
  1281. }
  1282. }
  1283. }
  1284. return this._withDependencies( [
  1285. "nodes"
  1286. ] ).then( function ( dependencies ) {
  1287. return _each( json.scenes, function ( scene ) {
  1288. var _scene = new THREE.Scene();
  1289. if ( scene.name !== undefined ) _scene.name = scene.name;
  1290. if ( scene.extras ) _scene.userData = scene.extras;
  1291. var nodes = scene.nodes || [];
  1292. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  1293. var nodeId = nodes[ i ];
  1294. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  1295. }
  1296. _scene.traverse( function ( child ) {
  1297. // Register raw material meshes with LegacyGLTFLoader.Shaders
  1298. if ( child.material && child.material.isRawShaderMaterial ) {
  1299. child.gltfShader = new GLTFShader( child, dependencies.nodes );
  1300. child.onBeforeRender = function(renderer, scene, camera){
  1301. this.gltfShader.update(scene, camera);
  1302. };
  1303. }
  1304. } );
  1305. return _scene;
  1306. } );
  1307. } );
  1308. };
  1309. return LegacyGLTFLoader;
  1310. } )();