GLTFLoader.js 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280
  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. import {
  9. AddEquation,
  10. AlwaysDepth,
  11. AnimationClip,
  12. BackSide,
  13. Bone,
  14. BufferAttribute,
  15. BufferGeometry,
  16. Camera,
  17. ClampToEdgeWrapping,
  18. Color,
  19. DefaultLoadingManager,
  20. DirectionalLight,
  21. DoubleSide,
  22. DstAlphaFactor,
  23. DstColorFactor,
  24. EqualDepth,
  25. FileLoader,
  26. FrontSide,
  27. GreaterEqualDepth,
  28. Group,
  29. InterleavedBuffer,
  30. InterleavedBufferAttribute,
  31. Interpolant,
  32. InterpolateDiscrete,
  33. InterpolateLinear,
  34. LessDepth,
  35. LessEqualDepth,
  36. Line,
  37. LineBasicMaterial,
  38. LineLoop,
  39. LineSegments,
  40. LinearFilter,
  41. LinearMipMapLinearFilter,
  42. LinearMipMapNearestFilter,
  43. Loader,
  44. LoaderUtils,
  45. Material,
  46. Math as _Math,
  47. Matrix3,
  48. Matrix4,
  49. Mesh,
  50. MeshBasicMaterial,
  51. MeshStandardMaterial,
  52. MirroredRepeatWrapping,
  53. NearestFilter,
  54. NearestMipMapLinearFilter,
  55. NearestMipMapNearestFilter,
  56. NeverDepth,
  57. NotEqualDepth,
  58. NumberKeyframeTrack,
  59. Object3D,
  60. OneFactor,
  61. OneMinusDstAlphaFactor,
  62. OneMinusDstColorFactor,
  63. OneMinusSrcAlphaFactor,
  64. OneMinusSrcColorFactor,
  65. OrthographicCamera,
  66. PerspectiveCamera,
  67. PointLight,
  68. Points,
  69. PointsMaterial,
  70. PropertyBinding,
  71. QuaternionKeyframeTrack,
  72. RGBAFormat,
  73. RGBFormat,
  74. RepeatWrapping,
  75. ReverseSubtractEquation,
  76. Scene,
  77. ShaderLib,
  78. ShaderMaterial,
  79. Skeleton,
  80. SkinnedMesh,
  81. SpotLight,
  82. SrcAlphaFactor,
  83. SrcAlphaSaturateFactor,
  84. SrcColorFactor,
  85. SubtractEquation,
  86. Texture,
  87. TextureLoader,
  88. TriangleFanDrawMode,
  89. TriangleStripDrawMode,
  90. UniformsUtils,
  91. Vector2,
  92. Vector3,
  93. Vector4,
  94. VectorKeyframeTrack,
  95. VertexColors,
  96. ZeroFactor,
  97. sRGBEncoding
  98. } from "../../../build/three.module.js";
  99. var GLTFLoader = ( function () {
  100. function GLTFLoader( manager ) {
  101. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  102. this.dracoLoader = null;
  103. }
  104. GLTFLoader.prototype = {
  105. constructor: GLTFLoader,
  106. crossOrigin: 'anonymous',
  107. load: function ( url, onLoad, onProgress, onError ) {
  108. var scope = this;
  109. var resourcePath;
  110. if ( this.resourcePath !== undefined ) {
  111. resourcePath = this.resourcePath;
  112. } else if ( this.path !== undefined ) {
  113. resourcePath = this.path;
  114. } else {
  115. resourcePath = LoaderUtils.extractUrlBase( url );
  116. }
  117. // Tells the LoadingManager to track an extra item, which resolves after
  118. // the model is fully loaded. This means the count of items loaded will
  119. // be incorrect, but ensures manager.onLoad() does not fire early.
  120. scope.manager.itemStart( url );
  121. var _onError = function ( e ) {
  122. if ( onError ) {
  123. onError( e );
  124. } else {
  125. console.error( e );
  126. }
  127. scope.manager.itemError( url );
  128. scope.manager.itemEnd( url );
  129. };
  130. var loader = new FileLoader( scope.manager );
  131. loader.setPath( this.path );
  132. loader.setResponseType( 'arraybuffer' );
  133. loader.load( url, function ( data ) {
  134. try {
  135. scope.parse( data, resourcePath, function ( gltf ) {
  136. onLoad( gltf );
  137. scope.manager.itemEnd( url );
  138. }, _onError );
  139. } catch ( e ) {
  140. _onError( e );
  141. }
  142. }, onProgress, _onError );
  143. },
  144. setCrossOrigin: function ( value ) {
  145. this.crossOrigin = value;
  146. return this;
  147. },
  148. setPath: function ( value ) {
  149. this.path = value;
  150. return this;
  151. },
  152. setResourcePath: function ( value ) {
  153. this.resourcePath = value;
  154. return this;
  155. },
  156. setDRACOLoader: function ( dracoLoader ) {
  157. this.dracoLoader = dracoLoader;
  158. return this;
  159. },
  160. parse: function ( data, path, onLoad, onError ) {
  161. var content;
  162. var extensions = {};
  163. if ( typeof data === 'string' ) {
  164. content = data;
  165. } else {
  166. var magic = LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  167. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  168. try {
  169. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  170. } catch ( error ) {
  171. if ( onError ) onError( error );
  172. return;
  173. }
  174. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  175. } else {
  176. content = LoaderUtils.decodeText( new Uint8Array( data ) );
  177. }
  178. }
  179. var json = JSON.parse( content );
  180. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  181. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  182. return;
  183. }
  184. if ( json.extensionsUsed ) {
  185. for ( var i = 0; i < json.extensionsUsed.length; ++ i ) {
  186. var extensionName = json.extensionsUsed[ i ];
  187. var extensionsRequired = json.extensionsRequired || [];
  188. switch ( extensionName ) {
  189. case EXTENSIONS.KHR_LIGHTS_PUNCTUAL:
  190. extensions[ extensionName ] = new GLTFLightsExtension( json );
  191. break;
  192. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  193. extensions[ extensionName ] = new GLTFMaterialsUnlitExtension( json );
  194. break;
  195. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  196. extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension( json );
  197. break;
  198. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  199. extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader );
  200. break;
  201. case EXTENSIONS.MSFT_TEXTURE_DDS:
  202. extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension();
  203. break;
  204. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  205. extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension( json );
  206. break;
  207. default:
  208. if ( extensionsRequired.indexOf( extensionName ) >= 0 ) {
  209. console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' );
  210. }
  211. }
  212. }
  213. }
  214. var parser = new GLTFParser( json, extensions, {
  215. path: path || this.resourcePath || '',
  216. crossOrigin: this.crossOrigin,
  217. manager: this.manager
  218. } );
  219. parser.parse( onLoad, onError );
  220. }
  221. };
  222. /* GLTFREGISTRY */
  223. function GLTFRegistry() {
  224. var objects = {};
  225. return {
  226. get: function ( key ) {
  227. return objects[ key ];
  228. },
  229. add: function ( key, object ) {
  230. objects[ key ] = object;
  231. },
  232. remove: function ( key ) {
  233. delete objects[ key ];
  234. },
  235. removeAll: function () {
  236. objects = {};
  237. }
  238. };
  239. }
  240. /*********************************/
  241. /********** EXTENSIONS ***********/
  242. /*********************************/
  243. var EXTENSIONS = {
  244. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  245. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  246. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  247. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  248. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  249. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  250. MSFT_TEXTURE_DDS: 'MSFT_texture_dds'
  251. };
  252. /**
  253. * DDS Texture Extension
  254. *
  255. * Specification:
  256. * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds
  257. *
  258. */
  259. function GLTFTextureDDSExtension() {
  260. if ( ! THREE.DDSLoader ) {
  261. throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' );
  262. }
  263. this.name = EXTENSIONS.MSFT_TEXTURE_DDS;
  264. this.ddsLoader = new THREE.DDSLoader();
  265. }
  266. /**
  267. * Lights Extension
  268. *
  269. * Specification: PENDING
  270. */
  271. function GLTFLightsExtension( json ) {
  272. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  273. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {};
  274. this.lightDefs = extension.lights || [];
  275. }
  276. GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) {
  277. var lightDef = this.lightDefs[ lightIndex ];
  278. var lightNode;
  279. var color = new Color( 0xffffff );
  280. if ( lightDef.color !== undefined ) color.fromArray( lightDef.color );
  281. var range = lightDef.range !== undefined ? lightDef.range : 0;
  282. switch ( lightDef.type ) {
  283. case 'directional':
  284. lightNode = new DirectionalLight( color );
  285. lightNode.target.position.set( 0, 0, - 1 );
  286. lightNode.add( lightNode.target );
  287. break;
  288. case 'point':
  289. lightNode = new PointLight( color );
  290. lightNode.distance = range;
  291. break;
  292. case 'spot':
  293. lightNode = new SpotLight( color );
  294. lightNode.distance = range;
  295. // Handle spotlight properties.
  296. lightDef.spot = lightDef.spot || {};
  297. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  298. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  299. lightNode.angle = lightDef.spot.outerConeAngle;
  300. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  301. lightNode.target.position.set( 0, 0, - 1 );
  302. lightNode.add( lightNode.target );
  303. break;
  304. default:
  305. throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' );
  306. }
  307. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  308. // here, because node-level parsing will only override position if explicitly specified.
  309. lightNode.position.set( 0, 0, 0 );
  310. lightNode.decay = 2;
  311. if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity;
  312. lightNode.name = lightDef.name || ( 'light_' + lightIndex );
  313. return Promise.resolve( lightNode );
  314. };
  315. /**
  316. * Unlit Materials Extension (pending)
  317. *
  318. * PR: https://github.com/KhronosGroup/glTF/pull/1163
  319. */
  320. function GLTFMaterialsUnlitExtension() {
  321. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  322. }
  323. GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () {
  324. return MeshBasicMaterial;
  325. };
  326. GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) {
  327. var pending = [];
  328. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  329. materialParams.opacity = 1.0;
  330. var metallicRoughness = materialDef.pbrMetallicRoughness;
  331. if ( metallicRoughness ) {
  332. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  333. var array = metallicRoughness.baseColorFactor;
  334. materialParams.color.fromArray( array );
  335. materialParams.opacity = array[ 3 ];
  336. }
  337. if ( metallicRoughness.baseColorTexture !== undefined ) {
  338. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  339. }
  340. }
  341. return Promise.all( pending );
  342. };
  343. /* BINARY EXTENSION */
  344. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  345. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  346. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  347. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  348. function GLTFBinaryExtension( data ) {
  349. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  350. this.content = null;
  351. this.body = null;
  352. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  353. this.header = {
  354. magic: LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  355. version: headerView.getUint32( 4, true ),
  356. length: headerView.getUint32( 8, true )
  357. };
  358. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  359. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  360. } else if ( this.header.version < 2.0 ) {
  361. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  362. }
  363. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  364. var chunkIndex = 0;
  365. while ( chunkIndex < chunkView.byteLength ) {
  366. var chunkLength = chunkView.getUint32( chunkIndex, true );
  367. chunkIndex += 4;
  368. var chunkType = chunkView.getUint32( chunkIndex, true );
  369. chunkIndex += 4;
  370. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  371. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  372. this.content = LoaderUtils.decodeText( contentArray );
  373. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  374. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  375. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  376. }
  377. // Clients must ignore chunks with unknown types.
  378. chunkIndex += chunkLength;
  379. }
  380. if ( this.content === null ) {
  381. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  382. }
  383. }
  384. /**
  385. * DRACO Mesh Compression Extension
  386. *
  387. * Specification: https://github.com/KhronosGroup/glTF/pull/874
  388. */
  389. function GLTFDracoMeshCompressionExtension( json, dracoLoader ) {
  390. if ( ! dracoLoader ) {
  391. throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' );
  392. }
  393. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  394. this.json = json;
  395. this.dracoLoader = dracoLoader;
  396. }
  397. GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) {
  398. var json = this.json;
  399. var dracoLoader = this.dracoLoader;
  400. var bufferViewIndex = primitive.extensions[ this.name ].bufferView;
  401. var gltfAttributeMap = primitive.extensions[ this.name ].attributes;
  402. var threeAttributeMap = {};
  403. var attributeNormalizedMap = {};
  404. var attributeTypeMap = {};
  405. for ( var attributeName in gltfAttributeMap ) {
  406. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  407. threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ];
  408. }
  409. for ( attributeName in primitive.attributes ) {
  410. var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase();
  411. if ( gltfAttributeMap[ attributeName ] !== undefined ) {
  412. var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ];
  413. var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  414. attributeTypeMap[ threeAttributeName ] = componentType;
  415. attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true;
  416. }
  417. }
  418. return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) {
  419. return new Promise( function ( resolve ) {
  420. dracoLoader.decodeDracoFile( bufferView, function ( geometry ) {
  421. for ( var attributeName in geometry.attributes ) {
  422. var attribute = geometry.attributes[ attributeName ];
  423. var normalized = attributeNormalizedMap[ attributeName ];
  424. if ( normalized !== undefined ) attribute.normalized = normalized;
  425. }
  426. resolve( geometry );
  427. }, threeAttributeMap, attributeTypeMap );
  428. } );
  429. } );
  430. };
  431. /**
  432. * Texture Transform Extension
  433. *
  434. * Specification:
  435. */
  436. function GLTFTextureTransformExtension() {
  437. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  438. }
  439. GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) {
  440. texture = texture.clone();
  441. if ( transform.offset !== undefined ) {
  442. texture.offset.fromArray( transform.offset );
  443. }
  444. if ( transform.rotation !== undefined ) {
  445. texture.rotation = transform.rotation;
  446. }
  447. if ( transform.scale !== undefined ) {
  448. texture.repeat.fromArray( transform.scale );
  449. }
  450. if ( transform.texCoord !== undefined ) {
  451. console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' );
  452. }
  453. texture.needsUpdate = true;
  454. return texture;
  455. };
  456. /**
  457. * Specular-Glossiness Extension
  458. *
  459. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  460. */
  461. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  462. return {
  463. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  464. specularGlossinessParams: [
  465. 'color',
  466. 'map',
  467. 'lightMap',
  468. 'lightMapIntensity',
  469. 'aoMap',
  470. 'aoMapIntensity',
  471. 'emissive',
  472. 'emissiveIntensity',
  473. 'emissiveMap',
  474. 'bumpMap',
  475. 'bumpScale',
  476. 'normalMap',
  477. 'displacementMap',
  478. 'displacementScale',
  479. 'displacementBias',
  480. 'specularMap',
  481. 'specular',
  482. 'glossinessMap',
  483. 'glossiness',
  484. 'alphaMap',
  485. 'envMap',
  486. 'envMapIntensity',
  487. 'refractionRatio',
  488. ],
  489. getMaterialType: function () {
  490. return ShaderMaterial;
  491. },
  492. extendParams: function ( materialParams, materialDef, parser ) {
  493. var pbrSpecularGlossiness = materialDef.extensions[ this.name ];
  494. var shader = ShaderLib[ 'standard' ];
  495. var uniforms = UniformsUtils.clone( shader.uniforms );
  496. var specularMapParsFragmentChunk = [
  497. '#ifdef USE_SPECULARMAP',
  498. ' uniform sampler2D specularMap;',
  499. '#endif'
  500. ].join( '\n' );
  501. var glossinessMapParsFragmentChunk = [
  502. '#ifdef USE_GLOSSINESSMAP',
  503. ' uniform sampler2D glossinessMap;',
  504. '#endif'
  505. ].join( '\n' );
  506. var specularMapFragmentChunk = [
  507. 'vec3 specularFactor = specular;',
  508. '#ifdef USE_SPECULARMAP',
  509. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  510. ' texelSpecular = sRGBToLinear( texelSpecular );',
  511. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  512. ' specularFactor *= texelSpecular.rgb;',
  513. '#endif'
  514. ].join( '\n' );
  515. var glossinessMapFragmentChunk = [
  516. 'float glossinessFactor = glossiness;',
  517. '#ifdef USE_GLOSSINESSMAP',
  518. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  519. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  520. ' glossinessFactor *= texelGlossiness.a;',
  521. '#endif'
  522. ].join( '\n' );
  523. var lightPhysicalFragmentChunk = [
  524. 'PhysicalMaterial material;',
  525. 'material.diffuseColor = diffuseColor.rgb;',
  526. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  527. 'material.specularColor = specularFactor.rgb;',
  528. ].join( '\n' );
  529. var fragmentShader = shader.fragmentShader
  530. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  531. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  532. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  533. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  534. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  535. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  536. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  537. delete uniforms.roughness;
  538. delete uniforms.metalness;
  539. delete uniforms.roughnessMap;
  540. delete uniforms.metalnessMap;
  541. uniforms.specular = { value: new Color().setHex( 0x111111 ) };
  542. uniforms.glossiness = { value: 0.5 };
  543. uniforms.specularMap = { value: null };
  544. uniforms.glossinessMap = { value: null };
  545. materialParams.vertexShader = shader.vertexShader;
  546. materialParams.fragmentShader = fragmentShader;
  547. materialParams.uniforms = uniforms;
  548. materialParams.defines = { 'STANDARD': '' };
  549. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  550. materialParams.opacity = 1.0;
  551. var pending = [];
  552. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  553. var array = pbrSpecularGlossiness.diffuseFactor;
  554. materialParams.color.fromArray( array );
  555. materialParams.opacity = array[ 3 ];
  556. }
  557. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  558. pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) );
  559. }
  560. materialParams.emissive = new Color( 0.0, 0.0, 0.0 );
  561. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  562. materialParams.specular = new Color( 1.0, 1.0, 1.0 );
  563. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  564. materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  565. }
  566. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  567. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  568. pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) );
  569. pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) );
  570. }
  571. return Promise.all( pending );
  572. },
  573. createMaterial: function ( params ) {
  574. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  575. var material = new ShaderMaterial( {
  576. defines: params.defines,
  577. vertexShader: params.vertexShader,
  578. fragmentShader: params.fragmentShader,
  579. uniforms: params.uniforms,
  580. fog: true,
  581. lights: true,
  582. opacity: params.opacity,
  583. transparent: params.transparent
  584. } );
  585. material.isGLTFSpecularGlossinessMaterial = true;
  586. material.color = params.color;
  587. material.map = params.map === undefined ? null : params.map;
  588. material.lightMap = null;
  589. material.lightMapIntensity = 1.0;
  590. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  591. material.aoMapIntensity = 1.0;
  592. material.emissive = params.emissive;
  593. material.emissiveIntensity = 1.0;
  594. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  595. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  596. material.bumpScale = 1;
  597. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  598. if ( params.normalScale ) material.normalScale = params.normalScale;
  599. material.displacementMap = null;
  600. material.displacementScale = 1;
  601. material.displacementBias = 0;
  602. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  603. material.specular = params.specular;
  604. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  605. material.glossiness = params.glossiness;
  606. material.alphaMap = null;
  607. material.envMap = params.envMap === undefined ? null : params.envMap;
  608. material.envMapIntensity = 1.0;
  609. material.refractionRatio = 0.98;
  610. material.extensions.derivatives = true;
  611. return material;
  612. },
  613. /**
  614. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  615. * copy only properties it knows about or inherits, and misses many properties that would
  616. * normally be defined by MeshStandardMaterial.
  617. *
  618. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  619. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  620. * AND also updating `.onBeforeRender` on the parent mesh.
  621. *
  622. * @param {ShaderMaterial} source
  623. * @return {ShaderMaterial}
  624. */
  625. cloneMaterial: function ( source ) {
  626. var target = source.clone();
  627. target.isGLTFSpecularGlossinessMaterial = true;
  628. var params = this.specularGlossinessParams;
  629. for ( var i = 0, il = params.length; i < il; i ++ ) {
  630. var value = source[ params[ i ] ];
  631. target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value;
  632. }
  633. return target;
  634. },
  635. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  636. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  637. if ( material.isGLTFSpecularGlossinessMaterial !== true ) {
  638. return;
  639. }
  640. var uniforms = material.uniforms;
  641. var defines = material.defines;
  642. uniforms.opacity.value = material.opacity;
  643. uniforms.diffuse.value.copy( material.color );
  644. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  645. uniforms.map.value = material.map;
  646. uniforms.specularMap.value = material.specularMap;
  647. uniforms.alphaMap.value = material.alphaMap;
  648. uniforms.lightMap.value = material.lightMap;
  649. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  650. uniforms.aoMap.value = material.aoMap;
  651. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  652. // uv repeat and offset setting priorities
  653. // 1. color map
  654. // 2. specular map
  655. // 3. normal map
  656. // 4. bump map
  657. // 5. alpha map
  658. // 6. emissive map
  659. var uvScaleMap;
  660. if ( material.map ) {
  661. uvScaleMap = material.map;
  662. } else if ( material.specularMap ) {
  663. uvScaleMap = material.specularMap;
  664. } else if ( material.displacementMap ) {
  665. uvScaleMap = material.displacementMap;
  666. } else if ( material.normalMap ) {
  667. uvScaleMap = material.normalMap;
  668. } else if ( material.bumpMap ) {
  669. uvScaleMap = material.bumpMap;
  670. } else if ( material.glossinessMap ) {
  671. uvScaleMap = material.glossinessMap;
  672. } else if ( material.alphaMap ) {
  673. uvScaleMap = material.alphaMap;
  674. } else if ( material.emissiveMap ) {
  675. uvScaleMap = material.emissiveMap;
  676. }
  677. if ( uvScaleMap !== undefined ) {
  678. // backwards compatibility
  679. if ( uvScaleMap.isWebGLRenderTarget ) {
  680. uvScaleMap = uvScaleMap.texture;
  681. }
  682. if ( uvScaleMap.matrixAutoUpdate === true ) {
  683. uvScaleMap.updateMatrix();
  684. }
  685. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  686. }
  687. if ( material.envMap ) {
  688. uniforms.envMap.value = material.envMap;
  689. uniforms.envMapIntensity.value = material.envMapIntensity;
  690. // don't flip CubeTexture envMaps, flip everything else:
  691. // WebGLRenderTargetCube will be flipped for backwards compatibility
  692. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  693. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  694. uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1;
  695. uniforms.reflectivity.value = material.reflectivity;
  696. uniforms.refractionRatio.value = material.refractionRatio;
  697. uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel;
  698. }
  699. uniforms.specular.value.copy( material.specular );
  700. uniforms.glossiness.value = material.glossiness;
  701. uniforms.glossinessMap.value = material.glossinessMap;
  702. uniforms.emissiveMap.value = material.emissiveMap;
  703. uniforms.bumpMap.value = material.bumpMap;
  704. uniforms.normalMap.value = material.normalMap;
  705. uniforms.displacementMap.value = material.displacementMap;
  706. uniforms.displacementScale.value = material.displacementScale;
  707. uniforms.displacementBias.value = material.displacementBias;
  708. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  709. defines.USE_GLOSSINESSMAP = '';
  710. // set USE_ROUGHNESSMAP to enable vUv
  711. defines.USE_ROUGHNESSMAP = '';
  712. }
  713. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  714. delete defines.USE_GLOSSINESSMAP;
  715. delete defines.USE_ROUGHNESSMAP;
  716. }
  717. }
  718. };
  719. }
  720. /*********************************/
  721. /********** INTERPOLATION ********/
  722. /*********************************/
  723. // Spline Interpolation
  724. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  725. function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  726. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  727. }
  728. GLTFCubicSplineInterpolant.prototype = Object.create( Interpolant.prototype );
  729. GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant;
  730. GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) {
  731. // Copies a sample value to the result buffer. See description of glTF
  732. // CUBICSPLINE values layout in interpolate_() function below.
  733. var result = this.resultBuffer,
  734. values = this.sampleValues,
  735. valueSize = this.valueSize,
  736. offset = index * valueSize * 3 + valueSize;
  737. for ( var i = 0; i !== valueSize; i ++ ) {
  738. result[ i ] = values[ offset + i ];
  739. }
  740. return result;
  741. };
  742. GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  743. GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_;
  744. GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) {
  745. var result = this.resultBuffer;
  746. var values = this.sampleValues;
  747. var stride = this.valueSize;
  748. var stride2 = stride * 2;
  749. var stride3 = stride * 3;
  750. var td = t1 - t0;
  751. var p = ( t - t0 ) / td;
  752. var pp = p * p;
  753. var ppp = pp * p;
  754. var offset1 = i1 * stride3;
  755. var offset0 = offset1 - stride3;
  756. var s2 = - 2 * ppp + 3 * pp;
  757. var s3 = ppp - pp;
  758. var s0 = 1 - s2;
  759. var s1 = s3 - pp + p;
  760. // Layout of keyframe output values for CUBICSPLINE animations:
  761. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  762. for ( var i = 0; i !== stride; i ++ ) {
  763. var p0 = values[ offset0 + i + stride ]; // splineVertex_k
  764. var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k)
  765. var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1
  766. var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k)
  767. result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  768. }
  769. return result;
  770. };
  771. /*********************************/
  772. /********** INTERNALS ************/
  773. /*********************************/
  774. /* CONSTANTS */
  775. var WEBGL_CONSTANTS = {
  776. FLOAT: 5126,
  777. //FLOAT_MAT2: 35674,
  778. FLOAT_MAT3: 35675,
  779. FLOAT_MAT4: 35676,
  780. FLOAT_VEC2: 35664,
  781. FLOAT_VEC3: 35665,
  782. FLOAT_VEC4: 35666,
  783. LINEAR: 9729,
  784. REPEAT: 10497,
  785. SAMPLER_2D: 35678,
  786. POINTS: 0,
  787. LINES: 1,
  788. LINE_LOOP: 2,
  789. LINE_STRIP: 3,
  790. TRIANGLES: 4,
  791. TRIANGLE_STRIP: 5,
  792. TRIANGLE_FAN: 6,
  793. UNSIGNED_BYTE: 5121,
  794. UNSIGNED_SHORT: 5123
  795. };
  796. var WEBGL_TYPE = {
  797. 5126: Number,
  798. //35674: THREE.Matrix2,
  799. 35675: Matrix3,
  800. 35676: Matrix4,
  801. 35664: Vector2,
  802. 35665: Vector3,
  803. 35666: Vector4,
  804. 35678: Texture
  805. };
  806. var WEBGL_COMPONENT_TYPES = {
  807. 5120: Int8Array,
  808. 5121: Uint8Array,
  809. 5122: Int16Array,
  810. 5123: Uint16Array,
  811. 5125: Uint32Array,
  812. 5126: Float32Array
  813. };
  814. var WEBGL_FILTERS = {
  815. 9728: NearestFilter,
  816. 9729: LinearFilter,
  817. 9984: NearestMipMapNearestFilter,
  818. 9985: LinearMipMapNearestFilter,
  819. 9986: NearestMipMapLinearFilter,
  820. 9987: LinearMipMapLinearFilter
  821. };
  822. var WEBGL_WRAPPINGS = {
  823. 33071: ClampToEdgeWrapping,
  824. 33648: MirroredRepeatWrapping,
  825. 10497: RepeatWrapping
  826. };
  827. var WEBGL_SIDES = {
  828. 1028: BackSide, // Culling front
  829. 1029: FrontSide // Culling back
  830. //1032: THREE.NoSide // Culling front and back, what to do?
  831. };
  832. var WEBGL_DEPTH_FUNCS = {
  833. 512: NeverDepth,
  834. 513: LessDepth,
  835. 514: EqualDepth,
  836. 515: LessEqualDepth,
  837. 516: GreaterEqualDepth,
  838. 517: NotEqualDepth,
  839. 518: GreaterEqualDepth,
  840. 519: AlwaysDepth
  841. };
  842. var WEBGL_BLEND_EQUATIONS = {
  843. 32774: AddEquation,
  844. 32778: SubtractEquation,
  845. 32779: ReverseSubtractEquation
  846. };
  847. var WEBGL_BLEND_FUNCS = {
  848. 0: ZeroFactor,
  849. 1: OneFactor,
  850. 768: SrcColorFactor,
  851. 769: OneMinusSrcColorFactor,
  852. 770: SrcAlphaFactor,
  853. 771: OneMinusSrcAlphaFactor,
  854. 772: DstAlphaFactor,
  855. 773: OneMinusDstAlphaFactor,
  856. 774: DstColorFactor,
  857. 775: OneMinusDstColorFactor,
  858. 776: SrcAlphaSaturateFactor
  859. // The followings are not supported by Three.js yet
  860. //32769: CONSTANT_COLOR,
  861. //32770: ONE_MINUS_CONSTANT_COLOR,
  862. //32771: CONSTANT_ALPHA,
  863. //32772: ONE_MINUS_CONSTANT_COLOR
  864. };
  865. var WEBGL_TYPE_SIZES = {
  866. 'SCALAR': 1,
  867. 'VEC2': 2,
  868. 'VEC3': 3,
  869. 'VEC4': 4,
  870. 'MAT2': 4,
  871. 'MAT3': 9,
  872. 'MAT4': 16
  873. };
  874. var ATTRIBUTES = {
  875. POSITION: 'position',
  876. NORMAL: 'normal',
  877. TANGENT: 'tangent',
  878. TEXCOORD_0: 'uv',
  879. TEXCOORD_1: 'uv2',
  880. COLOR_0: 'color',
  881. WEIGHTS_0: 'skinWeight',
  882. JOINTS_0: 'skinIndex',
  883. };
  884. var PATH_PROPERTIES = {
  885. scale: 'scale',
  886. translation: 'position',
  887. rotation: 'quaternion',
  888. weights: 'morphTargetInfluences'
  889. };
  890. var INTERPOLATION = {
  891. CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  892. // keyframe track will be initialized with a default interpolation type, then modified.
  893. LINEAR: InterpolateLinear,
  894. STEP: InterpolateDiscrete
  895. };
  896. var STATES_ENABLES = {
  897. 2884: 'CULL_FACE',
  898. 2929: 'DEPTH_TEST',
  899. 3042: 'BLEND',
  900. 3089: 'SCISSOR_TEST',
  901. 32823: 'POLYGON_OFFSET_FILL',
  902. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  903. };
  904. var ALPHA_MODES = {
  905. OPAQUE: 'OPAQUE',
  906. MASK: 'MASK',
  907. BLEND: 'BLEND'
  908. };
  909. var MIME_TYPE_FORMATS = {
  910. 'image/png': RGBAFormat,
  911. 'image/jpeg': RGBFormat
  912. };
  913. /* UTILITY FUNCTIONS */
  914. function resolveURL( url, path ) {
  915. // Invalid URL
  916. if ( typeof url !== 'string' || url === '' ) return '';
  917. // Absolute URL http://,https://,//
  918. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  919. // Data URI
  920. if ( /^data:.*,.*$/i.test( url ) ) return url;
  921. // Blob URL
  922. if ( /^blob:.*$/i.test( url ) ) return url;
  923. // Relative URL
  924. return path + url;
  925. }
  926. var defaultMaterial;
  927. /**
  928. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  929. */
  930. function createDefaultMaterial() {
  931. defaultMaterial = defaultMaterial || new MeshStandardMaterial( {
  932. color: 0xFFFFFF,
  933. emissive: 0x000000,
  934. metalness: 1,
  935. roughness: 1,
  936. transparent: false,
  937. depthTest: true,
  938. side: FrontSide
  939. } );
  940. return defaultMaterial;
  941. }
  942. function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) {
  943. // Add unknown glTF extensions to an object's userData.
  944. for ( var name in objectDef.extensions ) {
  945. if ( knownExtensions[ name ] === undefined ) {
  946. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  947. object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ];
  948. }
  949. }
  950. }
  951. /**
  952. * @param {Object3D|Material|BufferGeometry} object
  953. * @param {GLTF.definition} gltfDef
  954. */
  955. function assignExtrasToUserData( object, gltfDef ) {
  956. if ( gltfDef.extras !== undefined ) {
  957. if ( typeof gltfDef.extras === 'object' ) {
  958. Object.assign( object.userData, gltfDef.extras );
  959. } else {
  960. console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras );
  961. }
  962. }
  963. }
  964. /**
  965. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  966. *
  967. * @param {BufferGeometry} geometry
  968. * @param {Array<GLTF.Target>} targets
  969. * @param {GLTFParser} parser
  970. * @return {Promise<BufferGeometry>}
  971. */
  972. function addMorphTargets( geometry, targets, parser ) {
  973. var hasMorphPosition = false;
  974. var hasMorphNormal = false;
  975. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  976. var target = targets[ i ];
  977. if ( target.POSITION !== undefined ) hasMorphPosition = true;
  978. if ( target.NORMAL !== undefined ) hasMorphNormal = true;
  979. if ( hasMorphPosition && hasMorphNormal ) break;
  980. }
  981. if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry );
  982. var pendingPositionAccessors = [];
  983. var pendingNormalAccessors = [];
  984. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  985. var target = targets[ i ];
  986. if ( hasMorphPosition ) {
  987. var pendingAccessor = target.POSITION !== undefined
  988. ? parser.getDependency( 'accessor', target.POSITION )
  989. : geometry.attributes.position;
  990. pendingPositionAccessors.push( pendingAccessor );
  991. }
  992. if ( hasMorphNormal ) {
  993. var pendingAccessor = target.NORMAL !== undefined
  994. ? parser.getDependency( 'accessor', target.NORMAL )
  995. : geometry.attributes.normal;
  996. pendingNormalAccessors.push( pendingAccessor );
  997. }
  998. }
  999. return Promise.all( [
  1000. Promise.all( pendingPositionAccessors ),
  1001. Promise.all( pendingNormalAccessors )
  1002. ] ).then( function ( accessors ) {
  1003. var morphPositions = accessors[ 0 ];
  1004. var morphNormals = accessors[ 1 ];
  1005. // Clone morph target accessors before modifying them.
  1006. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) {
  1007. if ( geometry.attributes.position === morphPositions[ i ] ) continue;
  1008. morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] );
  1009. }
  1010. for ( var i = 0, il = morphNormals.length; i < il; i ++ ) {
  1011. if ( geometry.attributes.normal === morphNormals[ i ] ) continue;
  1012. morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] );
  1013. }
  1014. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  1015. var target = targets[ i ];
  1016. var attributeName = 'morphTarget' + i;
  1017. if ( hasMorphPosition ) {
  1018. // Three.js morph position is absolute value. The formula is
  1019. // basePosition
  1020. // + weight0 * ( morphPosition0 - basePosition )
  1021. // + weight1 * ( morphPosition1 - basePosition )
  1022. // ...
  1023. // while the glTF one is relative
  1024. // basePosition
  1025. // + weight0 * glTFmorphPosition0
  1026. // + weight1 * glTFmorphPosition1
  1027. // ...
  1028. // then we need to convert from relative to absolute here.
  1029. if ( target.POSITION !== undefined ) {
  1030. var positionAttribute = morphPositions[ i ];
  1031. positionAttribute.name = attributeName;
  1032. var position = geometry.attributes.position;
  1033. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  1034. positionAttribute.setXYZ(
  1035. j,
  1036. positionAttribute.getX( j ) + position.getX( j ),
  1037. positionAttribute.getY( j ) + position.getY( j ),
  1038. positionAttribute.getZ( j ) + position.getZ( j )
  1039. );
  1040. }
  1041. }
  1042. }
  1043. if ( hasMorphNormal ) {
  1044. // see target.POSITION's comment
  1045. if ( target.NORMAL !== undefined ) {
  1046. var normalAttribute = morphNormals[ i ];
  1047. normalAttribute.name = attributeName;
  1048. var normal = geometry.attributes.normal;
  1049. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  1050. normalAttribute.setXYZ(
  1051. j,
  1052. normalAttribute.getX( j ) + normal.getX( j ),
  1053. normalAttribute.getY( j ) + normal.getY( j ),
  1054. normalAttribute.getZ( j ) + normal.getZ( j )
  1055. );
  1056. }
  1057. }
  1058. }
  1059. }
  1060. if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions;
  1061. if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals;
  1062. return geometry;
  1063. } );
  1064. }
  1065. /**
  1066. * @param {Mesh} mesh
  1067. * @param {GLTF.Mesh} meshDef
  1068. */
  1069. function updateMorphTargets( mesh, meshDef ) {
  1070. mesh.updateMorphTargets();
  1071. if ( meshDef.weights !== undefined ) {
  1072. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  1073. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  1074. }
  1075. }
  1076. // .extras has user-defined data, so check that .extras.targetNames is an array.
  1077. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) {
  1078. var targetNames = meshDef.extras.targetNames;
  1079. if ( mesh.morphTargetInfluences.length === targetNames.length ) {
  1080. mesh.morphTargetDictionary = {};
  1081. for ( var i = 0, il = targetNames.length; i < il; i ++ ) {
  1082. mesh.morphTargetDictionary[ targetNames[ i ] ] = i;
  1083. }
  1084. } else {
  1085. console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' );
  1086. }
  1087. }
  1088. }
  1089. function isObjectEqual( a, b ) {
  1090. if ( Object.keys( a ).length !== Object.keys( b ).length ) return false;
  1091. for ( var key in a ) {
  1092. if ( a[ key ] !== b[ key ] ) return false;
  1093. }
  1094. return true;
  1095. }
  1096. function createPrimitiveKey( primitiveDef ) {
  1097. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ];
  1098. var geometryKey;
  1099. if ( dracoExtension ) {
  1100. geometryKey = 'draco:' + dracoExtension.bufferView
  1101. + ':' + dracoExtension.indices
  1102. + ':' + createAttributesKey( dracoExtension.attributes );
  1103. } else {
  1104. geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode;
  1105. }
  1106. return geometryKey;
  1107. }
  1108. function createAttributesKey( attributes ) {
  1109. var attributesKey = '';
  1110. var keys = Object.keys( attributes ).sort();
  1111. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  1112. attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';';
  1113. }
  1114. return attributesKey;
  1115. }
  1116. function cloneBufferAttribute( attribute ) {
  1117. if ( attribute.isInterleavedBufferAttribute ) {
  1118. var count = attribute.count;
  1119. var itemSize = attribute.itemSize;
  1120. var array = attribute.array.slice( 0, count * itemSize );
  1121. for ( var i = 0, j = 0; i < count; ++ i ) {
  1122. array[ j ++ ] = attribute.getX( i );
  1123. if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i );
  1124. if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i );
  1125. if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i );
  1126. }
  1127. return new BufferAttribute( array, itemSize, attribute.normalized );
  1128. }
  1129. return attribute.clone();
  1130. }
  1131. /* GLTF PARSER */
  1132. function GLTFParser( json, extensions, options ) {
  1133. this.json = json || {};
  1134. this.extensions = extensions || {};
  1135. this.options = options || {};
  1136. // loader object cache
  1137. this.cache = new GLTFRegistry();
  1138. // BufferGeometry caching
  1139. this.primitiveCache = {};
  1140. this.textureLoader = new TextureLoader( this.options.manager );
  1141. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  1142. this.fileLoader = new FileLoader( this.options.manager );
  1143. this.fileLoader.setResponseType( 'arraybuffer' );
  1144. }
  1145. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  1146. var parser = this;
  1147. var json = this.json;
  1148. var extensions = this.extensions;
  1149. // Clear the loader cache
  1150. this.cache.removeAll();
  1151. // Mark the special nodes/meshes in json for efficient parse
  1152. this.markDefs();
  1153. Promise.all( [
  1154. this.getDependencies( 'scene' ),
  1155. this.getDependencies( 'animation' ),
  1156. this.getDependencies( 'camera' ),
  1157. ] ).then( function ( dependencies ) {
  1158. var result = {
  1159. scene: dependencies[ 0 ][ json.scene || 0 ],
  1160. scenes: dependencies[ 0 ],
  1161. animations: dependencies[ 1 ],
  1162. cameras: dependencies[ 2 ],
  1163. asset: json.asset,
  1164. parser: parser,
  1165. userData: {}
  1166. };
  1167. addUnknownExtensionsToUserData( extensions, result, json );
  1168. onLoad( result );
  1169. } ).catch( onError );
  1170. };
  1171. /**
  1172. * Marks the special nodes/meshes in json for efficient parse.
  1173. */
  1174. GLTFParser.prototype.markDefs = function () {
  1175. var nodeDefs = this.json.nodes || [];
  1176. var skinDefs = this.json.skins || [];
  1177. var meshDefs = this.json.meshes || [];
  1178. var meshReferences = {};
  1179. var meshUses = {};
  1180. // Nothing in the node definition indicates whether it is a Bone or an
  1181. // Object3D. Use the skins' joint references to mark bones.
  1182. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  1183. var joints = skinDefs[ skinIndex ].joints;
  1184. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  1185. nodeDefs[ joints[ i ] ].isBone = true;
  1186. }
  1187. }
  1188. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  1189. // avoid having more than one Mesh with the same name, count
  1190. // references and rename instances below.
  1191. //
  1192. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1193. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  1194. var nodeDef = nodeDefs[ nodeIndex ];
  1195. if ( nodeDef.mesh !== undefined ) {
  1196. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  1197. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  1198. }
  1199. meshReferences[ nodeDef.mesh ] ++;
  1200. // Nothing in the mesh definition indicates whether it is
  1201. // a SkinnedMesh or Mesh. Use the node's mesh reference
  1202. // to mark SkinnedMesh if node has skin.
  1203. if ( nodeDef.skin !== undefined ) {
  1204. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  1205. }
  1206. }
  1207. }
  1208. this.json.meshReferences = meshReferences;
  1209. this.json.meshUses = meshUses;
  1210. };
  1211. /**
  1212. * Requests the specified dependency asynchronously, with caching.
  1213. * @param {string} type
  1214. * @param {number} index
  1215. * @return {Promise<Object3D|Material|Texture|AnimationClip|ArrayBuffer|Object>}
  1216. */
  1217. GLTFParser.prototype.getDependency = function ( type, index ) {
  1218. var cacheKey = type + ':' + index;
  1219. var dependency = this.cache.get( cacheKey );
  1220. if ( ! dependency ) {
  1221. switch ( type ) {
  1222. case 'scene':
  1223. dependency = this.loadScene( index );
  1224. break;
  1225. case 'node':
  1226. dependency = this.loadNode( index );
  1227. break;
  1228. case 'mesh':
  1229. dependency = this.loadMesh( index );
  1230. break;
  1231. case 'accessor':
  1232. dependency = this.loadAccessor( index );
  1233. break;
  1234. case 'bufferView':
  1235. dependency = this.loadBufferView( index );
  1236. break;
  1237. case 'buffer':
  1238. dependency = this.loadBuffer( index );
  1239. break;
  1240. case 'material':
  1241. dependency = this.loadMaterial( index );
  1242. break;
  1243. case 'texture':
  1244. dependency = this.loadTexture( index );
  1245. break;
  1246. case 'skin':
  1247. dependency = this.loadSkin( index );
  1248. break;
  1249. case 'animation':
  1250. dependency = this.loadAnimation( index );
  1251. break;
  1252. case 'camera':
  1253. dependency = this.loadCamera( index );
  1254. break;
  1255. case 'light':
  1256. dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index );
  1257. break;
  1258. default:
  1259. throw new Error( 'Unknown type: ' + type );
  1260. }
  1261. this.cache.add( cacheKey, dependency );
  1262. }
  1263. return dependency;
  1264. };
  1265. /**
  1266. * Requests all dependencies of the specified type asynchronously, with caching.
  1267. * @param {string} type
  1268. * @return {Promise<Array<Object>>}
  1269. */
  1270. GLTFParser.prototype.getDependencies = function ( type ) {
  1271. var dependencies = this.cache.get( type );
  1272. if ( ! dependencies ) {
  1273. var parser = this;
  1274. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  1275. dependencies = Promise.all( defs.map( function ( def, index ) {
  1276. return parser.getDependency( type, index );
  1277. } ) );
  1278. this.cache.add( type, dependencies );
  1279. }
  1280. return dependencies;
  1281. };
  1282. /**
  1283. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1284. * @param {number} bufferIndex
  1285. * @return {Promise<ArrayBuffer>}
  1286. */
  1287. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  1288. var bufferDef = this.json.buffers[ bufferIndex ];
  1289. var loader = this.fileLoader;
  1290. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  1291. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  1292. }
  1293. // If present, GLB container is required to be the first buffer.
  1294. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  1295. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  1296. }
  1297. var options = this.options;
  1298. return new Promise( function ( resolve, reject ) {
  1299. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  1300. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  1301. } );
  1302. } );
  1303. };
  1304. /**
  1305. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1306. * @param {number} bufferViewIndex
  1307. * @return {Promise<ArrayBuffer>}
  1308. */
  1309. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  1310. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  1311. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  1312. var byteLength = bufferViewDef.byteLength || 0;
  1313. var byteOffset = bufferViewDef.byteOffset || 0;
  1314. return buffer.slice( byteOffset, byteOffset + byteLength );
  1315. } );
  1316. };
  1317. /**
  1318. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1319. * @param {number} accessorIndex
  1320. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  1321. */
  1322. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  1323. var parser = this;
  1324. var json = this.json;
  1325. var accessorDef = this.json.accessors[ accessorIndex ];
  1326. if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) {
  1327. // Ignore empty accessors, which may be used to declare runtime
  1328. // information about attributes coming from another source (e.g. Draco
  1329. // compression extension).
  1330. return Promise.resolve( null );
  1331. }
  1332. var pendingBufferViews = [];
  1333. if ( accessorDef.bufferView !== undefined ) {
  1334. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  1335. } else {
  1336. pendingBufferViews.push( null );
  1337. }
  1338. if ( accessorDef.sparse !== undefined ) {
  1339. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  1340. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  1341. }
  1342. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  1343. var bufferView = bufferViews[ 0 ];
  1344. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  1345. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  1346. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1347. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  1348. var itemBytes = elementBytes * itemSize;
  1349. var byteOffset = accessorDef.byteOffset || 0;
  1350. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined;
  1351. var normalized = accessorDef.normalized === true;
  1352. var array, bufferAttribute;
  1353. // The buffer is not interleaved if the stride is the item size in bytes.
  1354. if ( byteStride && byteStride !== itemBytes ) {
  1355. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType;
  1356. var ib = parser.cache.get( ibCacheKey );
  1357. if ( ! ib ) {
  1358. // Use the full buffer if it's interleaved.
  1359. array = new TypedArray( bufferView );
  1360. // Integer parameters to IB/IBA are in array elements, not bytes.
  1361. ib = new InterleavedBuffer( array, byteStride / elementBytes );
  1362. parser.cache.add( ibCacheKey, ib );
  1363. }
  1364. bufferAttribute = new InterleavedBufferAttribute( ib, itemSize, byteOffset / elementBytes, normalized );
  1365. } else {
  1366. if ( bufferView === null ) {
  1367. array = new TypedArray( accessorDef.count * itemSize );
  1368. } else {
  1369. array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize );
  1370. }
  1371. bufferAttribute = new BufferAttribute( array, itemSize, normalized );
  1372. }
  1373. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1374. if ( accessorDef.sparse !== undefined ) {
  1375. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  1376. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  1377. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  1378. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  1379. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  1380. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  1381. if ( bufferView !== null ) {
  1382. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1383. bufferAttribute.setArray( bufferAttribute.array.slice() );
  1384. }
  1385. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  1386. var index = sparseIndices[ i ];
  1387. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  1388. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  1389. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  1390. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  1391. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  1392. }
  1393. }
  1394. return bufferAttribute;
  1395. } );
  1396. };
  1397. /**
  1398. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1399. * @param {number} textureIndex
  1400. * @return {Promise<Texture>}
  1401. */
  1402. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  1403. var parser = this;
  1404. var json = this.json;
  1405. var options = this.options;
  1406. var textureLoader = this.textureLoader;
  1407. var URL = window.URL || window.webkitURL;
  1408. var textureDef = json.textures[ textureIndex ];
  1409. var textureExtensions = textureDef.extensions || {};
  1410. var source;
  1411. if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) {
  1412. source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ];
  1413. } else {
  1414. source = json.images[ textureDef.source ];
  1415. }
  1416. var sourceURI = source.uri;
  1417. var isObjectURL = false;
  1418. if ( source.bufferView !== undefined ) {
  1419. // Load binary image data from bufferView, if provided.
  1420. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  1421. isObjectURL = true;
  1422. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  1423. sourceURI = URL.createObjectURL( blob );
  1424. return sourceURI;
  1425. } );
  1426. }
  1427. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  1428. // Load Texture resource.
  1429. var loader = Loader.Handlers.get( sourceURI );
  1430. if ( ! loader ) {
  1431. loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ]
  1432. ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader
  1433. : textureLoader;
  1434. }
  1435. return new Promise( function ( resolve, reject ) {
  1436. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  1437. } );
  1438. } ).then( function ( texture ) {
  1439. // Clean up resources and configure Texture.
  1440. if ( isObjectURL === true ) {
  1441. URL.revokeObjectURL( sourceURI );
  1442. }
  1443. texture.flipY = false;
  1444. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  1445. // Ignore unknown mime types, like DDS files.
  1446. if ( source.mimeType in MIME_TYPE_FORMATS ) {
  1447. texture.format = MIME_TYPE_FORMATS[ source.mimeType ];
  1448. }
  1449. var samplers = json.samplers || {};
  1450. var sampler = samplers[ textureDef.sampler ] || {};
  1451. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  1452. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipMapLinearFilter;
  1453. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  1454. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  1455. return texture;
  1456. } );
  1457. };
  1458. /**
  1459. * Asynchronously assigns a texture to the given material parameters.
  1460. * @param {Object} materialParams
  1461. * @param {string} mapName
  1462. * @param {Object} mapDef
  1463. * @return {Promise}
  1464. */
  1465. GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) {
  1466. var parser = this;
  1467. return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) {
  1468. if ( ! texture.isCompressedTexture ) {
  1469. switch ( mapName ) {
  1470. case 'aoMap':
  1471. case 'emissiveMap':
  1472. case 'metalnessMap':
  1473. case 'normalMap':
  1474. case 'roughnessMap':
  1475. texture.format = RGBFormat;
  1476. break;
  1477. }
  1478. }
  1479. if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) {
  1480. var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined;
  1481. if ( transform ) {
  1482. texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform );
  1483. }
  1484. }
  1485. materialParams[ mapName ] = texture;
  1486. } );
  1487. };
  1488. /**
  1489. * Assigns final material to a Mesh, Line, or Points instance. The instance
  1490. * already has a material (generated from the glTF material options alone)
  1491. * but reuse of the same glTF material may require multiple threejs materials
  1492. * to accomodate different primitive types, defines, etc. New materials will
  1493. * be created if necessary, and reused from a cache.
  1494. * @param {Object3D} mesh Mesh, Line, or Points instance.
  1495. */
  1496. GLTFParser.prototype.assignFinalMaterial = function ( mesh ) {
  1497. var geometry = mesh.geometry;
  1498. var material = mesh.material;
  1499. var extensions = this.extensions;
  1500. var useVertexTangents = geometry.attributes.tangent !== undefined;
  1501. var useVertexColors = geometry.attributes.color !== undefined;
  1502. var useFlatShading = geometry.attributes.normal === undefined;
  1503. var useSkinning = mesh.isSkinnedMesh === true;
  1504. var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0;
  1505. var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined;
  1506. if ( mesh.isPoints ) {
  1507. var cacheKey = 'PointsMaterial:' + material.uuid;
  1508. var pointsMaterial = this.cache.get( cacheKey );
  1509. if ( ! pointsMaterial ) {
  1510. pointsMaterial = new PointsMaterial();
  1511. Material.prototype.copy.call( pointsMaterial, material );
  1512. pointsMaterial.color.copy( material.color );
  1513. pointsMaterial.map = material.map;
  1514. pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet
  1515. this.cache.add( cacheKey, pointsMaterial );
  1516. }
  1517. material = pointsMaterial;
  1518. } else if ( mesh.isLine ) {
  1519. var cacheKey = 'LineBasicMaterial:' + material.uuid;
  1520. var lineMaterial = this.cache.get( cacheKey );
  1521. if ( ! lineMaterial ) {
  1522. lineMaterial = new LineBasicMaterial();
  1523. Material.prototype.copy.call( lineMaterial, material );
  1524. lineMaterial.color.copy( material.color );
  1525. lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet
  1526. this.cache.add( cacheKey, lineMaterial );
  1527. }
  1528. material = lineMaterial;
  1529. }
  1530. // Clone the material if it will be modified
  1531. if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  1532. var cacheKey = 'ClonedMaterial:' + material.uuid + ':';
  1533. if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:';
  1534. if ( useSkinning ) cacheKey += 'skinning:';
  1535. if ( useVertexTangents ) cacheKey += 'vertex-tangents:';
  1536. if ( useVertexColors ) cacheKey += 'vertex-colors:';
  1537. if ( useFlatShading ) cacheKey += 'flat-shading:';
  1538. if ( useMorphTargets ) cacheKey += 'morph-targets:';
  1539. if ( useMorphNormals ) cacheKey += 'morph-normals:';
  1540. var cachedMaterial = this.cache.get( cacheKey );
  1541. if ( ! cachedMaterial ) {
  1542. cachedMaterial = material.isGLTFSpecularGlossinessMaterial
  1543. ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material )
  1544. : material.clone();
  1545. if ( useSkinning ) cachedMaterial.skinning = true;
  1546. if ( useVertexTangents ) cachedMaterial.vertexTangents = true;
  1547. if ( useVertexColors ) cachedMaterial.vertexColors = VertexColors;
  1548. if ( useFlatShading ) cachedMaterial.flatShading = true;
  1549. if ( useMorphTargets ) cachedMaterial.morphTargets = true;
  1550. if ( useMorphNormals ) cachedMaterial.morphNormals = true;
  1551. this.cache.add( cacheKey, cachedMaterial );
  1552. }
  1553. material = cachedMaterial;
  1554. }
  1555. // workarounds for mesh and geometry
  1556. if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) {
  1557. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  1558. geometry.addAttribute( 'uv2', new BufferAttribute( geometry.attributes.uv.array, 2 ) );
  1559. }
  1560. if ( material.isGLTFSpecularGlossinessMaterial ) {
  1561. // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update
  1562. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  1563. }
  1564. mesh.material = material;
  1565. };
  1566. /**
  1567. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1568. * @param {number} materialIndex
  1569. * @return {Promise<Material>}
  1570. */
  1571. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  1572. var parser = this;
  1573. var json = this.json;
  1574. var extensions = this.extensions;
  1575. var materialDef = json.materials[ materialIndex ];
  1576. var materialType;
  1577. var materialParams = {};
  1578. var materialExtensions = materialDef.extensions || {};
  1579. var pending = [];
  1580. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  1581. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  1582. materialType = sgExtension.getMaterialType();
  1583. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  1584. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) {
  1585. var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ];
  1586. materialType = kmuExtension.getMaterialType();
  1587. pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) );
  1588. } else {
  1589. // Specification:
  1590. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  1591. materialType = MeshStandardMaterial;
  1592. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  1593. materialParams.color = new Color( 1.0, 1.0, 1.0 );
  1594. materialParams.opacity = 1.0;
  1595. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  1596. var array = metallicRoughness.baseColorFactor;
  1597. materialParams.color.fromArray( array );
  1598. materialParams.opacity = array[ 3 ];
  1599. }
  1600. if ( metallicRoughness.baseColorTexture !== undefined ) {
  1601. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) );
  1602. }
  1603. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  1604. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  1605. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  1606. pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1607. pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) );
  1608. }
  1609. }
  1610. if ( materialDef.doubleSided === true ) {
  1611. materialParams.side = DoubleSide;
  1612. }
  1613. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  1614. if ( alphaMode === ALPHA_MODES.BLEND ) {
  1615. materialParams.transparent = true;
  1616. } else {
  1617. materialParams.transparent = false;
  1618. if ( alphaMode === ALPHA_MODES.MASK ) {
  1619. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  1620. }
  1621. }
  1622. if ( materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial ) {
  1623. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) );
  1624. materialParams.normalScale = new Vector2( 1, 1 );
  1625. if ( materialDef.normalTexture.scale !== undefined ) {
  1626. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  1627. }
  1628. }
  1629. if ( materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial ) {
  1630. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) );
  1631. if ( materialDef.occlusionTexture.strength !== undefined ) {
  1632. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  1633. }
  1634. }
  1635. if ( materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial ) {
  1636. materialParams.emissive = new Color().fromArray( materialDef.emissiveFactor );
  1637. }
  1638. if ( materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial ) {
  1639. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) );
  1640. }
  1641. return Promise.all( pending ).then( function () {
  1642. var material;
  1643. if ( materialType === ShaderMaterial ) {
  1644. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  1645. } else {
  1646. material = new materialType( materialParams );
  1647. }
  1648. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  1649. // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding.
  1650. if ( material.map ) material.map.encoding = sRGBEncoding;
  1651. if ( material.emissiveMap ) material.emissiveMap.encoding = sRGBEncoding;
  1652. if ( material.specularMap ) material.specularMap.encoding = sRGBEncoding;
  1653. assignExtrasToUserData( material, materialDef );
  1654. if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef );
  1655. return material;
  1656. } );
  1657. };
  1658. /**
  1659. * @param {BufferGeometry} geometry
  1660. * @param {GLTF.Primitive} primitiveDef
  1661. * @param {GLTFParser} parser
  1662. * @return {Promise<BufferGeometry>}
  1663. */
  1664. function addPrimitiveAttributes( geometry, primitiveDef, parser ) {
  1665. var attributes = primitiveDef.attributes;
  1666. var pending = [];
  1667. function assignAttributeAccessor( accessorIndex, attributeName ) {
  1668. return parser.getDependency( 'accessor', accessorIndex )
  1669. .then( function ( accessor ) {
  1670. geometry.addAttribute( attributeName, accessor );
  1671. } );
  1672. }
  1673. for ( var gltfAttributeName in attributes ) {
  1674. var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase();
  1675. // Skip attributes already provided by e.g. Draco extension.
  1676. if ( threeAttributeName in geometry.attributes ) continue;
  1677. pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) );
  1678. }
  1679. if ( primitiveDef.indices !== undefined && ! geometry.index ) {
  1680. var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) {
  1681. geometry.setIndex( accessor );
  1682. } );
  1683. pending.push( accessor );
  1684. }
  1685. assignExtrasToUserData( geometry, primitiveDef );
  1686. return Promise.all( pending ).then( function () {
  1687. return primitiveDef.targets !== undefined
  1688. ? addMorphTargets( geometry, primitiveDef.targets, parser )
  1689. : geometry;
  1690. } );
  1691. }
  1692. /**
  1693. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  1694. *
  1695. * Creates BufferGeometries from primitives.
  1696. *
  1697. * @param {Array<GLTF.Primitive>} primitives
  1698. * @return {Promise<Array<BufferGeometry>>}
  1699. */
  1700. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  1701. var parser = this;
  1702. var extensions = this.extensions;
  1703. var cache = this.primitiveCache;
  1704. function createDracoPrimitive( primitive ) {
  1705. return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]
  1706. .decodePrimitive( primitive, parser )
  1707. .then( function ( geometry ) {
  1708. return addPrimitiveAttributes( geometry, primitive, parser );
  1709. } );
  1710. }
  1711. var pending = [];
  1712. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1713. var primitive = primitives[ i ];
  1714. var cacheKey = createPrimitiveKey( primitive );
  1715. // See if we've already created this geometry
  1716. var cached = cache[ cacheKey ];
  1717. if ( cached ) {
  1718. // Use the cached geometry if it exists
  1719. pending.push( cached.promise );
  1720. } else {
  1721. var geometryPromise;
  1722. if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) {
  1723. // Use DRACO geometry if available
  1724. geometryPromise = createDracoPrimitive( primitive );
  1725. } else {
  1726. // Otherwise create a new geometry
  1727. geometryPromise = addPrimitiveAttributes( new BufferGeometry(), primitive, parser );
  1728. }
  1729. // Cache this geometry
  1730. cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise };
  1731. pending.push( geometryPromise );
  1732. }
  1733. }
  1734. return Promise.all( pending );
  1735. };
  1736. /**
  1737. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  1738. * @param {number} meshIndex
  1739. * @return {Promise<Group|Mesh|SkinnedMesh>}
  1740. */
  1741. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  1742. var parser = this;
  1743. var json = this.json;
  1744. var extensions = this.extensions;
  1745. var meshDef = json.meshes[ meshIndex ];
  1746. var primitives = meshDef.primitives;
  1747. var pending = [];
  1748. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  1749. var material = primitives[ i ].material === undefined
  1750. ? createDefaultMaterial()
  1751. : this.getDependency( 'material', primitives[ i ].material );
  1752. pending.push( material );
  1753. }
  1754. return Promise.all( pending ).then( function ( originalMaterials ) {
  1755. return parser.loadGeometries( primitives ).then( function ( geometries ) {
  1756. var meshes = [];
  1757. for ( var i = 0, il = geometries.length; i < il; i ++ ) {
  1758. var geometry = geometries[ i ];
  1759. var primitive = primitives[ i ];
  1760. // 1. create Mesh
  1761. var mesh;
  1762. var material = originalMaterials[ i ];
  1763. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  1764. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  1765. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  1766. primitive.mode === undefined ) {
  1767. // .isSkinnedMesh isn't in glTF spec. See .markDefs()
  1768. mesh = meshDef.isSkinnedMesh === true
  1769. ? new SkinnedMesh( geometry, material )
  1770. : new Mesh( geometry, material );
  1771. if ( mesh.isSkinnedMesh === true ) mesh.normalizeSkinWeights(); // #15319
  1772. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  1773. mesh.drawMode = TriangleStripDrawMode;
  1774. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  1775. mesh.drawMode = TriangleFanDrawMode;
  1776. }
  1777. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  1778. mesh = new LineSegments( geometry, material );
  1779. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  1780. mesh = new Line( geometry, material );
  1781. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  1782. mesh = new LineLoop( geometry, material );
  1783. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  1784. mesh = new Points( geometry, material );
  1785. } else {
  1786. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  1787. }
  1788. if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) {
  1789. updateMorphTargets( mesh, meshDef );
  1790. }
  1791. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  1792. if ( geometries.length > 1 ) mesh.name += '_' + i;
  1793. assignExtrasToUserData( mesh, meshDef );
  1794. parser.assignFinalMaterial( mesh );
  1795. meshes.push( mesh );
  1796. }
  1797. if ( meshes.length === 1 ) {
  1798. return meshes[ 0 ];
  1799. }
  1800. var group = new Group();
  1801. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  1802. group.add( meshes[ i ] );
  1803. }
  1804. return group;
  1805. } );
  1806. } );
  1807. };
  1808. /**
  1809. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  1810. * @param {number} cameraIndex
  1811. * @return {Promise<Camera>}
  1812. */
  1813. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  1814. var camera;
  1815. var cameraDef = this.json.cameras[ cameraIndex ];
  1816. var params = cameraDef[ cameraDef.type ];
  1817. if ( ! params ) {
  1818. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  1819. return;
  1820. }
  1821. if ( cameraDef.type === 'perspective' ) {
  1822. camera = new PerspectiveCamera( _Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 );
  1823. } else if ( cameraDef.type === 'orthographic' ) {
  1824. camera = new OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  1825. }
  1826. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  1827. assignExtrasToUserData( camera, cameraDef );
  1828. return Promise.resolve( camera );
  1829. };
  1830. /**
  1831. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  1832. * @param {number} skinIndex
  1833. * @return {Promise<Object>}
  1834. */
  1835. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  1836. var skinDef = this.json.skins[ skinIndex ];
  1837. var skinEntry = { joints: skinDef.joints };
  1838. if ( skinDef.inverseBindMatrices === undefined ) {
  1839. return Promise.resolve( skinEntry );
  1840. }
  1841. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  1842. skinEntry.inverseBindMatrices = accessor;
  1843. return skinEntry;
  1844. } );
  1845. };
  1846. /**
  1847. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  1848. * @param {number} animationIndex
  1849. * @return {Promise<AnimationClip>}
  1850. */
  1851. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  1852. var json = this.json;
  1853. var animationDef = json.animations[ animationIndex ];
  1854. var pendingNodes = [];
  1855. var pendingInputAccessors = [];
  1856. var pendingOutputAccessors = [];
  1857. var pendingSamplers = [];
  1858. var pendingTargets = [];
  1859. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  1860. var channel = animationDef.channels[ i ];
  1861. var sampler = animationDef.samplers[ channel.sampler ];
  1862. var target = channel.target;
  1863. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  1864. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  1865. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  1866. pendingNodes.push( this.getDependency( 'node', name ) );
  1867. pendingInputAccessors.push( this.getDependency( 'accessor', input ) );
  1868. pendingOutputAccessors.push( this.getDependency( 'accessor', output ) );
  1869. pendingSamplers.push( sampler );
  1870. pendingTargets.push( target );
  1871. }
  1872. return Promise.all( [
  1873. Promise.all( pendingNodes ),
  1874. Promise.all( pendingInputAccessors ),
  1875. Promise.all( pendingOutputAccessors ),
  1876. Promise.all( pendingSamplers ),
  1877. Promise.all( pendingTargets )
  1878. ] ).then( function ( dependencies ) {
  1879. var nodes = dependencies[ 0 ];
  1880. var inputAccessors = dependencies[ 1 ];
  1881. var outputAccessors = dependencies[ 2 ];
  1882. var samplers = dependencies[ 3 ];
  1883. var targets = dependencies[ 4 ];
  1884. var tracks = [];
  1885. for ( var i = 0, il = nodes.length; i < il; i ++ ) {
  1886. var node = nodes[ i ];
  1887. var inputAccessor = inputAccessors[ i ];
  1888. var outputAccessor = outputAccessors[ i ];
  1889. var sampler = samplers[ i ];
  1890. var target = targets[ i ];
  1891. if ( node === undefined ) continue;
  1892. node.updateMatrix();
  1893. node.matrixAutoUpdate = true;
  1894. var TypedKeyframeTrack;
  1895. switch ( PATH_PROPERTIES[ target.path ] ) {
  1896. case PATH_PROPERTIES.weights:
  1897. TypedKeyframeTrack = NumberKeyframeTrack;
  1898. break;
  1899. case PATH_PROPERTIES.rotation:
  1900. TypedKeyframeTrack = QuaternionKeyframeTrack;
  1901. break;
  1902. case PATH_PROPERTIES.position:
  1903. case PATH_PROPERTIES.scale:
  1904. default:
  1905. TypedKeyframeTrack = VectorKeyframeTrack;
  1906. break;
  1907. }
  1908. var targetName = node.name ? node.name : node.uuid;
  1909. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : InterpolateLinear;
  1910. var targetNames = [];
  1911. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  1912. // Node may be a Group (glTF mesh with several primitives) or a Mesh.
  1913. node.traverse( function ( object ) {
  1914. if ( object.isMesh === true && object.morphTargetInfluences ) {
  1915. targetNames.push( object.name ? object.name : object.uuid );
  1916. }
  1917. } );
  1918. } else {
  1919. targetNames.push( targetName );
  1920. }
  1921. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  1922. var track = new TypedKeyframeTrack(
  1923. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  1924. inputAccessor.array,
  1925. outputAccessor.array,
  1926. interpolation
  1927. );
  1928. // Override interpolation with custom factory method.
  1929. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  1930. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) {
  1931. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  1932. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  1933. // must be divided by three to get the interpolant's sampleSize argument.
  1934. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result );
  1935. };
  1936. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  1937. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  1938. }
  1939. tracks.push( track );
  1940. }
  1941. }
  1942. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  1943. return new AnimationClip( name, undefined, tracks );
  1944. } );
  1945. };
  1946. /**
  1947. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  1948. * @param {number} nodeIndex
  1949. * @return {Promise<Object3D>}
  1950. */
  1951. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  1952. var json = this.json;
  1953. var extensions = this.extensions;
  1954. var parser = this;
  1955. var meshReferences = json.meshReferences;
  1956. var meshUses = json.meshUses;
  1957. var nodeDef = json.nodes[ nodeIndex ];
  1958. return ( function () {
  1959. // .isBone isn't in glTF spec. See .markDefs
  1960. if ( nodeDef.isBone === true ) {
  1961. return Promise.resolve( new Bone() );
  1962. } else if ( nodeDef.mesh !== undefined ) {
  1963. return parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) {
  1964. var node;
  1965. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  1966. var instanceNum = meshUses[ nodeDef.mesh ] ++;
  1967. node = mesh.clone();
  1968. node.name += '_instance_' + instanceNum;
  1969. // onBeforeRender copy for Specular-Glossiness
  1970. node.onBeforeRender = mesh.onBeforeRender;
  1971. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  1972. node.children[ i ].name += '_instance_' + instanceNum;
  1973. node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender;
  1974. }
  1975. } else {
  1976. node = mesh;
  1977. }
  1978. // if weights are provided on the node, override weights on the mesh.
  1979. if ( nodeDef.weights !== undefined ) {
  1980. node.traverse( function ( o ) {
  1981. if ( ! o.isMesh ) return;
  1982. for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) {
  1983. o.morphTargetInfluences[ i ] = nodeDef.weights[ i ];
  1984. }
  1985. } );
  1986. }
  1987. return node;
  1988. } );
  1989. } else if ( nodeDef.camera !== undefined ) {
  1990. return parser.getDependency( 'camera', nodeDef.camera );
  1991. } else if ( nodeDef.extensions
  1992. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ]
  1993. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) {
  1994. return parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light );
  1995. } else {
  1996. return Promise.resolve( new Object3D() );
  1997. }
  1998. }() ).then( function ( node ) {
  1999. if ( nodeDef.name !== undefined ) {
  2000. node.userData.name = nodeDef.name;
  2001. node.name = PropertyBinding.sanitizeNodeName( nodeDef.name );
  2002. }
  2003. assignExtrasToUserData( node, nodeDef );
  2004. if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef );
  2005. if ( nodeDef.matrix !== undefined ) {
  2006. var matrix = new Matrix4();
  2007. matrix.fromArray( nodeDef.matrix );
  2008. node.applyMatrix( matrix );
  2009. } else {
  2010. if ( nodeDef.translation !== undefined ) {
  2011. node.position.fromArray( nodeDef.translation );
  2012. }
  2013. if ( nodeDef.rotation !== undefined ) {
  2014. node.quaternion.fromArray( nodeDef.rotation );
  2015. }
  2016. if ( nodeDef.scale !== undefined ) {
  2017. node.scale.fromArray( nodeDef.scale );
  2018. }
  2019. }
  2020. return node;
  2021. } );
  2022. };
  2023. /**
  2024. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2025. * @param {number} sceneIndex
  2026. * @return {Promise<Scene>}
  2027. */
  2028. GLTFParser.prototype.loadScene = function () {
  2029. // scene node hierachy builder
  2030. function buildNodeHierachy( nodeId, parentObject, json, parser ) {
  2031. var nodeDef = json.nodes[ nodeId ];
  2032. return parser.getDependency( 'node', nodeId ).then( function ( node ) {
  2033. if ( nodeDef.skin === undefined ) return node;
  2034. // build skeleton here as well
  2035. var skinEntry;
  2036. return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) {
  2037. skinEntry = skin;
  2038. var pendingJoints = [];
  2039. for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) {
  2040. pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) );
  2041. }
  2042. return Promise.all( pendingJoints );
  2043. } ).then( function ( jointNodes ) {
  2044. var meshes = node.isGroup === true ? node.children : [ node ];
  2045. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  2046. var mesh = meshes[ i ];
  2047. var bones = [];
  2048. var boneInverses = [];
  2049. for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) {
  2050. var jointNode = jointNodes[ j ];
  2051. if ( jointNode ) {
  2052. bones.push( jointNode );
  2053. var mat = new Matrix4();
  2054. if ( skinEntry.inverseBindMatrices !== undefined ) {
  2055. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  2056. }
  2057. boneInverses.push( mat );
  2058. } else {
  2059. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] );
  2060. }
  2061. }
  2062. mesh.bind( new Skeleton( bones, boneInverses ), mesh.matrixWorld );
  2063. }
  2064. return node;
  2065. } );
  2066. } ).then( function ( node ) {
  2067. // build node hierachy
  2068. parentObject.add( node );
  2069. var pending = [];
  2070. if ( nodeDef.children ) {
  2071. var children = nodeDef.children;
  2072. for ( var i = 0, il = children.length; i < il; i ++ ) {
  2073. var child = children[ i ];
  2074. pending.push( buildNodeHierachy( child, node, json, parser ) );
  2075. }
  2076. }
  2077. return Promise.all( pending );
  2078. } );
  2079. }
  2080. return function loadScene( sceneIndex ) {
  2081. var json = this.json;
  2082. var extensions = this.extensions;
  2083. var sceneDef = this.json.scenes[ sceneIndex ];
  2084. var parser = this;
  2085. var scene = new Scene();
  2086. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  2087. assignExtrasToUserData( scene, sceneDef );
  2088. if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef );
  2089. var nodeIds = sceneDef.nodes || [];
  2090. var pending = [];
  2091. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  2092. pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) );
  2093. }
  2094. return Promise.all( pending ).then( function () {
  2095. return scene;
  2096. } );
  2097. };
  2098. }();
  2099. return GLTFLoader;
  2100. } )();
  2101. export { GLTFLoader };