gltf-loader.js 88 KB

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