GLTFLoader.js 86 KB

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