GLTF2Loader.js 67 KB

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