GLTFLoader.js 86 KB

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