GLTFLoader.js 133 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191
  1. ;(function () {
  2. class GLTFLoader extends THREE.Loader {
  3. constructor(manager) {
  4. super(manager)
  5. this.dracoLoader = null
  6. this.ktx2Loader = null
  7. this.meshoptDecoder = null
  8. this.pluginCallbacks = []
  9. this.register(function (parser) {
  10. return new GLTFMaterialsClearcoatExtension(parser)
  11. })
  12. this.register(function (parser) {
  13. return new GLTFTextureBasisUExtension(parser)
  14. })
  15. this.register(function (parser) {
  16. return new GLTFTextureWebPExtension(parser)
  17. })
  18. this.register(function (parser) {
  19. return new GLTFMaterialsSheenExtension(parser)
  20. })
  21. this.register(function (parser) {
  22. return new GLTFMaterialsTransmissionExtension(parser)
  23. })
  24. this.register(function (parser) {
  25. return new GLTFMaterialsVolumeExtension(parser)
  26. })
  27. this.register(function (parser) {
  28. return new GLTFMaterialsIorExtension(parser)
  29. })
  30. this.register(function (parser) {
  31. return new GLTFMaterialsEmissiveStrengthExtension(parser)
  32. })
  33. this.register(function (parser) {
  34. return new GLTFMaterialsSpecularExtension(parser)
  35. })
  36. this.register(function (parser) {
  37. return new GLTFMaterialsIridescenceExtension(parser)
  38. })
  39. this.register(function (parser) {
  40. return new GLTFLightsExtension(parser)
  41. })
  42. this.register(function (parser) {
  43. return new GLTFMeshoptCompression(parser)
  44. })
  45. }
  46. load(url, onLoad, onProgress, onError) {
  47. const scope = this
  48. let resourcePath
  49. if (this.resourcePath !== '') {
  50. resourcePath = this.resourcePath
  51. } else if (this.path !== '') {
  52. resourcePath = this.path
  53. } else {
  54. resourcePath = THREE.LoaderUtils.extractUrlBase(url)
  55. } // Tells the LoadingManager to track an extra item, which resolves after
  56. // the model is fully loaded. This means the count of items loaded will
  57. // be incorrect, but ensures manager.onLoad() does not fire early.
  58. this.manager.itemStart(url)
  59. const _onError = function (e) {
  60. if (onError) {
  61. onError(e)
  62. } else {
  63. console.error(e)
  64. }
  65. scope.manager.itemError(url)
  66. scope.manager.itemEnd(url)
  67. }
  68. const loader = new THREE.FileLoader(this.manager)
  69. loader.setPath(this.path)
  70. loader.setResponseType('arraybuffer')
  71. loader.setRequestHeader(this.requestHeader)
  72. loader.setWithCredentials(this.withCredentials)
  73. loader.load(
  74. url,
  75. function (data) {
  76. try {
  77. scope.parse(
  78. data,
  79. resourcePath,
  80. function (gltf) {
  81. onLoad(gltf)
  82. scope.manager.itemEnd(url)
  83. },
  84. _onError
  85. )
  86. } catch (e) {
  87. _onError(e)
  88. }
  89. },
  90. onProgress,
  91. _onError
  92. )
  93. }
  94. setDRACOLoader(dracoLoader) {
  95. this.dracoLoader = dracoLoader
  96. return this
  97. }
  98. setDDSLoader() {
  99. throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".')
  100. }
  101. setKTX2Loader(ktx2Loader) {
  102. this.ktx2Loader = ktx2Loader
  103. return this
  104. }
  105. setMeshoptDecoder(meshoptDecoder) {
  106. this.meshoptDecoder = meshoptDecoder
  107. return this
  108. }
  109. register(callback) {
  110. if (this.pluginCallbacks.indexOf(callback) === -1) {
  111. this.pluginCallbacks.push(callback)
  112. }
  113. return this
  114. }
  115. unregister(callback) {
  116. if (this.pluginCallbacks.indexOf(callback) !== -1) {
  117. this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1)
  118. }
  119. return this
  120. }
  121. parse(data, path, onLoad, onError) {
  122. let content
  123. const extensions = {}
  124. const plugins = {}
  125. if (typeof data === 'string') {
  126. content = data
  127. } else {
  128. const magic = THREE.LoaderUtils.decodeText(new Uint8Array(data, 0, 4))
  129. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  130. try {
  131. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data)
  132. } catch (error) {
  133. if (onError) onError(error)
  134. return
  135. }
  136. content = extensions[EXTENSIONS.KHR_BINARY_GLTF].content
  137. } else {
  138. content = THREE.LoaderUtils.decodeText(new Uint8Array(data))
  139. }
  140. }
  141. const json = JSON.parse(content)
  142. if (json.asset === undefined || json.asset.version[0] < 2) {
  143. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'))
  144. return
  145. }
  146. const parser = new GLTFParser(json, {
  147. path: path || this.resourcePath || '',
  148. crossOrigin: this.crossOrigin,
  149. requestHeader: this.requestHeader,
  150. manager: this.manager,
  151. ktx2Loader: this.ktx2Loader,
  152. meshoptDecoder: this.meshoptDecoder,
  153. })
  154. parser.fileLoader.setRequestHeader(this.requestHeader)
  155. for (let i = 0; i < this.pluginCallbacks.length; i++) {
  156. const plugin = this.pluginCallbacks[i](parser)
  157. plugins[plugin.name] = plugin // Workaround to avoid determining as unknown extension
  158. // in addUnknownExtensionsToUserData().
  159. // Remove this workaround if we move all the existing
  160. // extension handlers to plugin system
  161. extensions[plugin.name] = true
  162. }
  163. if (json.extensionsUsed) {
  164. for (let i = 0; i < json.extensionsUsed.length; ++i) {
  165. const extensionName = json.extensionsUsed[i]
  166. const extensionsRequired = json.extensionsRequired || []
  167. switch (extensionName) {
  168. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  169. extensions[extensionName] = new GLTFMaterialsUnlitExtension()
  170. break
  171. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  172. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension()
  173. break
  174. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  175. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader)
  176. break
  177. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  178. extensions[extensionName] = new GLTFTextureTransformExtension()
  179. break
  180. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  181. extensions[extensionName] = new GLTFMeshQuantizationExtension()
  182. break
  183. default:
  184. if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
  185. console.warn('THREE.GLTFLoader: Unknown extension "' + extensionName + '".')
  186. }
  187. }
  188. }
  189. }
  190. parser.setExtensions(extensions)
  191. parser.setPlugins(plugins)
  192. parser.parse(onLoad, onError)
  193. }
  194. parseAsync(data, path) {
  195. const scope = this
  196. return new Promise(function (resolve, reject) {
  197. scope.parse(data, path, resolve, reject)
  198. })
  199. }
  200. }
  201. /* GLTFREGISTRY */
  202. function GLTFRegistry() {
  203. let objects = {}
  204. return {
  205. get: function (key) {
  206. return objects[key]
  207. },
  208. add: function (key, object) {
  209. objects[key] = object
  210. },
  211. remove: function (key) {
  212. delete objects[key]
  213. },
  214. removeAll: function () {
  215. objects = {}
  216. },
  217. }
  218. }
  219. /*********************************/
  220. /********** EXTENSIONS ***********/
  221. /*********************************/
  222. const EXTENSIONS = {
  223. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  224. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  225. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  226. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  227. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  228. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  229. KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
  230. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  231. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  232. KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
  233. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  234. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  235. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  236. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  237. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  238. KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
  239. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  240. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  241. }
  242. /**
  243. * Punctual Lights Extension
  244. *
  245. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  246. */
  247. class GLTFLightsExtension {
  248. constructor(parser) {
  249. this.parser = parser
  250. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL // THREE.Object3D instance caches
  251. this.cache = {
  252. refs: {},
  253. uses: {},
  254. }
  255. }
  256. _markDefs() {
  257. const parser = this.parser
  258. const nodeDefs = this.parser.json.nodes || []
  259. for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  260. const nodeDef = nodeDefs[nodeIndex]
  261. if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) {
  262. parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light)
  263. }
  264. }
  265. }
  266. _loadLight(lightIndex) {
  267. const parser = this.parser
  268. const cacheKey = 'light:' + lightIndex
  269. let dependency = parser.cache.get(cacheKey)
  270. if (dependency) return dependency
  271. const json = parser.json
  272. const extensions = (json.extensions && json.extensions[this.name]) || {}
  273. const lightDefs = extensions.lights || []
  274. const lightDef = lightDefs[lightIndex]
  275. let lightNode
  276. const color = new THREE.Color(0xffffff)
  277. if (lightDef.color !== undefined) color.fromArray(lightDef.color)
  278. const range = lightDef.range !== undefined ? lightDef.range : 0
  279. switch (lightDef.type) {
  280. case 'directional':
  281. lightNode = new THREE.DirectionalLight(color)
  282. lightNode.target.position.set(0, 0, -1)
  283. lightNode.add(lightNode.target)
  284. break
  285. case 'point':
  286. lightNode = new THREE.PointLight(color)
  287. lightNode.distance = range
  288. break
  289. case 'spot':
  290. lightNode = new THREE.SpotLight(color)
  291. lightNode.distance = range // Handle spotlight properties.
  292. lightDef.spot = lightDef.spot || {}
  293. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0
  294. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0
  295. lightNode.angle = lightDef.spot.outerConeAngle
  296. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle
  297. lightNode.target.position.set(0, 0, -1)
  298. lightNode.add(lightNode.target)
  299. break
  300. default:
  301. throw new Error('THREE.GLTFLoader: Unexpected light type: ' + lightDef.type)
  302. } // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  303. // here, because node-level parsing will only override position if explicitly specified.
  304. lightNode.position.set(0, 0, 0)
  305. lightNode.decay = 2
  306. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity
  307. lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex)
  308. dependency = Promise.resolve(lightNode)
  309. parser.cache.add(cacheKey, dependency)
  310. return dependency
  311. }
  312. createNodeAttachment(nodeIndex) {
  313. const self = this
  314. const parser = this.parser
  315. const json = parser.json
  316. const nodeDef = json.nodes[nodeIndex]
  317. const lightDef = (nodeDef.extensions && nodeDef.extensions[this.name]) || {}
  318. const lightIndex = lightDef.light
  319. if (lightIndex === undefined) return null
  320. return this._loadLight(lightIndex).then(function (light) {
  321. return parser._getNodeRef(self.cache, lightIndex, light)
  322. })
  323. }
  324. }
  325. /**
  326. * Unlit Materials Extension
  327. *
  328. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  329. */
  330. class GLTFMaterialsUnlitExtension {
  331. constructor() {
  332. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT
  333. }
  334. getMaterialType() {
  335. return THREE.MeshBasicMaterial
  336. }
  337. extendParams(materialParams, materialDef, parser) {
  338. const pending = []
  339. materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
  340. materialParams.opacity = 1.0
  341. const metallicRoughness = materialDef.pbrMetallicRoughness
  342. if (metallicRoughness) {
  343. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  344. const array = metallicRoughness.baseColorFactor
  345. materialParams.color.fromArray(array)
  346. materialParams.opacity = array[3]
  347. }
  348. if (metallicRoughness.baseColorTexture !== undefined) {
  349. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, THREE.sRGBEncoding))
  350. }
  351. }
  352. return Promise.all(pending)
  353. }
  354. }
  355. /**
  356. * Materials Emissive Strength Extension
  357. *
  358. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  359. */
  360. class GLTFMaterialsEmissiveStrengthExtension {
  361. constructor(parser) {
  362. this.parser = parser
  363. this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH
  364. }
  365. extendMaterialParams(materialIndex, materialParams) {
  366. const parser = this.parser
  367. const materialDef = parser.json.materials[materialIndex]
  368. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  369. return Promise.resolve()
  370. }
  371. const emissiveStrength = materialDef.extensions[this.name].emissiveStrength
  372. if (emissiveStrength !== undefined) {
  373. materialParams.emissiveIntensity = emissiveStrength
  374. }
  375. return Promise.resolve()
  376. }
  377. }
  378. /**
  379. * Clearcoat Materials Extension
  380. *
  381. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  382. */
  383. class GLTFMaterialsClearcoatExtension {
  384. constructor(parser) {
  385. this.parser = parser
  386. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT
  387. }
  388. getMaterialType(materialIndex) {
  389. const parser = this.parser
  390. const materialDef = parser.json.materials[materialIndex]
  391. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  392. return THREE.MeshPhysicalMaterial
  393. }
  394. extendMaterialParams(materialIndex, materialParams) {
  395. const parser = this.parser
  396. const materialDef = parser.json.materials[materialIndex]
  397. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  398. return Promise.resolve()
  399. }
  400. const pending = []
  401. const extension = materialDef.extensions[this.name]
  402. if (extension.clearcoatFactor !== undefined) {
  403. materialParams.clearcoat = extension.clearcoatFactor
  404. }
  405. if (extension.clearcoatTexture !== undefined) {
  406. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture))
  407. }
  408. if (extension.clearcoatRoughnessFactor !== undefined) {
  409. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor
  410. }
  411. if (extension.clearcoatRoughnessTexture !== undefined) {
  412. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture))
  413. }
  414. if (extension.clearcoatNormalTexture !== undefined) {
  415. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture))
  416. if (extension.clearcoatNormalTexture.scale !== undefined) {
  417. const scale = extension.clearcoatNormalTexture.scale
  418. materialParams.clearcoatNormalScale = new THREE.Vector2(scale, scale)
  419. }
  420. }
  421. return Promise.all(pending)
  422. }
  423. }
  424. /**
  425. * Iridescence Materials Extension
  426. *
  427. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  428. */
  429. class GLTFMaterialsIridescenceExtension {
  430. constructor(parser) {
  431. this.parser = parser
  432. this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE
  433. }
  434. getMaterialType(materialIndex) {
  435. const parser = this.parser
  436. const materialDef = parser.json.materials[materialIndex]
  437. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  438. return THREE.MeshPhysicalMaterial
  439. }
  440. extendMaterialParams(materialIndex, materialParams) {
  441. const parser = this.parser
  442. const materialDef = parser.json.materials[materialIndex]
  443. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  444. return Promise.resolve()
  445. }
  446. const pending = []
  447. const extension = materialDef.extensions[this.name]
  448. if (extension.iridescenceFactor !== undefined) {
  449. materialParams.iridescence = extension.iridescenceFactor
  450. }
  451. if (extension.iridescenceTexture !== undefined) {
  452. pending.push(parser.assignTexture(materialParams, 'iridescenceMap', extension.iridescenceTexture))
  453. }
  454. if (extension.iridescenceIor !== undefined) {
  455. materialParams.iridescenceIOR = extension.iridescenceIor
  456. }
  457. if (materialParams.iridescenceThicknessRange === undefined) {
  458. materialParams.iridescenceThicknessRange = [100, 400]
  459. }
  460. if (extension.iridescenceThicknessMinimum !== undefined) {
  461. materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum
  462. }
  463. if (extension.iridescenceThicknessMaximum !== undefined) {
  464. materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum
  465. }
  466. if (extension.iridescenceThicknessTexture !== undefined) {
  467. pending.push(parser.assignTexture(materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture))
  468. }
  469. return Promise.all(pending)
  470. }
  471. }
  472. /**
  473. * Sheen Materials Extension
  474. *
  475. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  476. */
  477. class GLTFMaterialsSheenExtension {
  478. constructor(parser) {
  479. this.parser = parser
  480. this.name = EXTENSIONS.KHR_MATERIALS_SHEEN
  481. }
  482. getMaterialType(materialIndex) {
  483. const parser = this.parser
  484. const materialDef = parser.json.materials[materialIndex]
  485. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  486. return THREE.MeshPhysicalMaterial
  487. }
  488. extendMaterialParams(materialIndex, materialParams) {
  489. const parser = this.parser
  490. const materialDef = parser.json.materials[materialIndex]
  491. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  492. return Promise.resolve()
  493. }
  494. const pending = []
  495. materialParams.sheenColor = new THREE.Color(0, 0, 0)
  496. materialParams.sheenRoughness = 0
  497. materialParams.sheen = 1
  498. const extension = materialDef.extensions[this.name]
  499. if (extension.sheenColorFactor !== undefined) {
  500. materialParams.sheenColor.fromArray(extension.sheenColorFactor)
  501. }
  502. if (extension.sheenRoughnessFactor !== undefined) {
  503. materialParams.sheenRoughness = extension.sheenRoughnessFactor
  504. }
  505. if (extension.sheenColorTexture !== undefined) {
  506. pending.push(parser.assignTexture(materialParams, 'sheenColorMap', extension.sheenColorTexture, THREE.sRGBEncoding))
  507. }
  508. if (extension.sheenRoughnessTexture !== undefined) {
  509. pending.push(parser.assignTexture(materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture))
  510. }
  511. return Promise.all(pending)
  512. }
  513. }
  514. /**
  515. * Transmission Materials Extension
  516. *
  517. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  518. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  519. */
  520. class GLTFMaterialsTransmissionExtension {
  521. constructor(parser) {
  522. this.parser = parser
  523. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION
  524. }
  525. getMaterialType(materialIndex) {
  526. const parser = this.parser
  527. const materialDef = parser.json.materials[materialIndex]
  528. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  529. return THREE.MeshPhysicalMaterial
  530. }
  531. extendMaterialParams(materialIndex, materialParams) {
  532. const parser = this.parser
  533. const materialDef = parser.json.materials[materialIndex]
  534. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  535. return Promise.resolve()
  536. }
  537. const pending = []
  538. const extension = materialDef.extensions[this.name]
  539. if (extension.transmissionFactor !== undefined) {
  540. materialParams.transmission = extension.transmissionFactor
  541. }
  542. if (extension.transmissionTexture !== undefined) {
  543. pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture))
  544. }
  545. return Promise.all(pending)
  546. }
  547. }
  548. /**
  549. * Materials Volume Extension
  550. *
  551. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  552. */
  553. class GLTFMaterialsVolumeExtension {
  554. constructor(parser) {
  555. this.parser = parser
  556. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME
  557. }
  558. getMaterialType(materialIndex) {
  559. const parser = this.parser
  560. const materialDef = parser.json.materials[materialIndex]
  561. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  562. return THREE.MeshPhysicalMaterial
  563. }
  564. extendMaterialParams(materialIndex, materialParams) {
  565. const parser = this.parser
  566. const materialDef = parser.json.materials[materialIndex]
  567. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  568. return Promise.resolve()
  569. }
  570. const pending = []
  571. const extension = materialDef.extensions[this.name]
  572. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0
  573. if (extension.thicknessTexture !== undefined) {
  574. pending.push(parser.assignTexture(materialParams, 'thicknessMap', extension.thicknessTexture))
  575. }
  576. materialParams.attenuationDistance = extension.attenuationDistance || 0
  577. const colorArray = extension.attenuationColor || [1, 1, 1]
  578. materialParams.attenuationColor = new THREE.Color(colorArray[0], colorArray[1], colorArray[2])
  579. return Promise.all(pending)
  580. }
  581. }
  582. /**
  583. * Materials ior Extension
  584. *
  585. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  586. */
  587. class GLTFMaterialsIorExtension {
  588. constructor(parser) {
  589. this.parser = parser
  590. this.name = EXTENSIONS.KHR_MATERIALS_IOR
  591. }
  592. getMaterialType(materialIndex) {
  593. const parser = this.parser
  594. const materialDef = parser.json.materials[materialIndex]
  595. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  596. return THREE.MeshPhysicalMaterial
  597. }
  598. extendMaterialParams(materialIndex, materialParams) {
  599. const parser = this.parser
  600. const materialDef = parser.json.materials[materialIndex]
  601. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  602. return Promise.resolve()
  603. }
  604. const extension = materialDef.extensions[this.name]
  605. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5
  606. return Promise.resolve()
  607. }
  608. }
  609. /**
  610. * Materials specular Extension
  611. *
  612. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  613. */
  614. class GLTFMaterialsSpecularExtension {
  615. constructor(parser) {
  616. this.parser = parser
  617. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR
  618. }
  619. getMaterialType(materialIndex) {
  620. const parser = this.parser
  621. const materialDef = parser.json.materials[materialIndex]
  622. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null
  623. return THREE.MeshPhysicalMaterial
  624. }
  625. extendMaterialParams(materialIndex, materialParams) {
  626. const parser = this.parser
  627. const materialDef = parser.json.materials[materialIndex]
  628. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  629. return Promise.resolve()
  630. }
  631. const pending = []
  632. const extension = materialDef.extensions[this.name]
  633. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0
  634. if (extension.specularTexture !== undefined) {
  635. pending.push(parser.assignTexture(materialParams, 'specularIntensityMap', extension.specularTexture))
  636. }
  637. const colorArray = extension.specularColorFactor || [1, 1, 1]
  638. materialParams.specularColor = new THREE.Color(colorArray[0], colorArray[1], colorArray[2])
  639. if (extension.specularColorTexture !== undefined) {
  640. pending.push(parser.assignTexture(materialParams, 'specularColorMap', extension.specularColorTexture, THREE.sRGBEncoding))
  641. }
  642. return Promise.all(pending)
  643. }
  644. }
  645. /**
  646. * BasisU THREE.Texture Extension
  647. *
  648. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  649. */
  650. class GLTFTextureBasisUExtension {
  651. constructor(parser) {
  652. this.parser = parser
  653. this.name = EXTENSIONS.KHR_TEXTURE_BASISU
  654. }
  655. loadTexture(textureIndex) {
  656. const parser = this.parser
  657. const json = parser.json
  658. const textureDef = json.textures[textureIndex]
  659. if (!textureDef.extensions || !textureDef.extensions[this.name]) {
  660. return null
  661. }
  662. const extension = textureDef.extensions[this.name]
  663. const loader = parser.options.ktx2Loader
  664. if (!loader) {
  665. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  666. throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures')
  667. } else {
  668. // Assumes that the extension is optional and that a fallback texture is present
  669. return null
  670. }
  671. }
  672. return parser.loadTextureImage(textureIndex, extension.source, loader)
  673. }
  674. }
  675. /**
  676. * WebP THREE.Texture Extension
  677. *
  678. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  679. */
  680. class GLTFTextureWebPExtension {
  681. constructor(parser) {
  682. this.parser = parser
  683. this.name = EXTENSIONS.EXT_TEXTURE_WEBP
  684. this.isSupported = null
  685. }
  686. loadTexture(textureIndex) {
  687. const name = this.name
  688. const parser = this.parser
  689. const json = parser.json
  690. const textureDef = json.textures[textureIndex]
  691. if (!textureDef.extensions || !textureDef.extensions[name]) {
  692. return null
  693. }
  694. const extension = textureDef.extensions[name]
  695. const source = json.images[extension.source]
  696. let loader = parser.textureLoader
  697. if (source.uri) {
  698. const handler = parser.options.manager.getHandler(source.uri)
  699. if (handler !== null) loader = handler
  700. }
  701. return this.detectSupport().then(function (isSupported) {
  702. if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader)
  703. if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
  704. throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.')
  705. } // Fall back to PNG or JPEG.
  706. return parser.loadTexture(textureIndex)
  707. })
  708. }
  709. detectSupport() {
  710. if (!this.isSupported) {
  711. this.isSupported = new Promise(function (resolve) {
  712. const image = new Image() // Lossy test image. Support for lossy images doesn't guarantee support for all
  713. // WebP images, unfortunately.
  714. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA'
  715. image.onload = image.onerror = function () {
  716. resolve(image.height === 1)
  717. }
  718. })
  719. }
  720. return this.isSupported
  721. }
  722. }
  723. /**
  724. * meshopt BufferView Compression Extension
  725. *
  726. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  727. */
  728. class GLTFMeshoptCompression {
  729. constructor(parser) {
  730. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION
  731. this.parser = parser
  732. }
  733. loadBufferView(index) {
  734. const json = this.parser.json
  735. const bufferView = json.bufferViews[index]
  736. if (bufferView.extensions && bufferView.extensions[this.name]) {
  737. const extensionDef = bufferView.extensions[this.name]
  738. const buffer = this.parser.getDependency('buffer', extensionDef.buffer)
  739. const decoder = this.parser.options.meshoptDecoder
  740. if (!decoder || !decoder.supported) {
  741. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  742. throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files')
  743. } else {
  744. // Assumes that the extension is optional and that fallback buffer data is present
  745. return null
  746. }
  747. }
  748. return buffer.then(function (res) {
  749. const byteOffset = extensionDef.byteOffset || 0
  750. const byteLength = extensionDef.byteLength || 0
  751. const count = extensionDef.count
  752. const stride = extensionDef.byteStride
  753. const source = new Uint8Array(res, byteOffset, byteLength)
  754. if (decoder.decodeGltfBufferAsync) {
  755. return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function (res) {
  756. return res.buffer
  757. })
  758. } else {
  759. // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
  760. return decoder.ready.then(function () {
  761. const result = new ArrayBuffer(count * stride)
  762. decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter)
  763. return result
  764. })
  765. }
  766. })
  767. } else {
  768. return null
  769. }
  770. }
  771. }
  772. /* BINARY EXTENSION */
  773. const BINARY_EXTENSION_HEADER_MAGIC = 'glTF'
  774. const BINARY_EXTENSION_HEADER_LENGTH = 12
  775. const BINARY_EXTENSION_CHUNK_TYPES = {
  776. JSON: 0x4e4f534a,
  777. BIN: 0x004e4942,
  778. }
  779. class GLTFBinaryExtension {
  780. constructor(data) {
  781. this.name = EXTENSIONS.KHR_BINARY_GLTF
  782. this.content = null
  783. this.body = null
  784. const headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH)
  785. this.header = {
  786. magic: THREE.LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  787. version: headerView.getUint32(4, true),
  788. length: headerView.getUint32(8, true),
  789. }
  790. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  791. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.')
  792. } else if (this.header.version < 2.0) {
  793. throw new Error('THREE.GLTFLoader: Legacy binary file detected.')
  794. }
  795. const chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH
  796. const chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH)
  797. let chunkIndex = 0
  798. while (chunkIndex < chunkContentsLength) {
  799. const chunkLength = chunkView.getUint32(chunkIndex, true)
  800. chunkIndex += 4
  801. const chunkType = chunkView.getUint32(chunkIndex, true)
  802. chunkIndex += 4
  803. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  804. const contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength)
  805. this.content = THREE.LoaderUtils.decodeText(contentArray)
  806. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  807. const byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex
  808. this.body = data.slice(byteOffset, byteOffset + chunkLength)
  809. } // Clients must ignore chunks with unknown types.
  810. chunkIndex += chunkLength
  811. }
  812. if (this.content === null) {
  813. throw new Error('THREE.GLTFLoader: JSON content not found.')
  814. }
  815. }
  816. }
  817. /**
  818. * DRACO THREE.Mesh Compression Extension
  819. *
  820. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  821. */
  822. class GLTFDracoMeshCompressionExtension {
  823. constructor(json, dracoLoader) {
  824. if (!dracoLoader) {
  825. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.')
  826. }
  827. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION
  828. this.json = json
  829. this.dracoLoader = dracoLoader
  830. this.dracoLoader.preload()
  831. }
  832. decodePrimitive(primitive, parser) {
  833. const json = this.json
  834. const dracoLoader = this.dracoLoader
  835. const bufferViewIndex = primitive.extensions[this.name].bufferView
  836. const gltfAttributeMap = primitive.extensions[this.name].attributes
  837. const threeAttributeMap = {}
  838. const attributeNormalizedMap = {}
  839. const attributeTypeMap = {}
  840. for (const attributeName in gltfAttributeMap) {
  841. const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase()
  842. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName]
  843. }
  844. for (const attributeName in primitive.attributes) {
  845. const threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase()
  846. if (gltfAttributeMap[attributeName] !== undefined) {
  847. const accessorDef = json.accessors[primitive.attributes[attributeName]]
  848. const componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType]
  849. attributeTypeMap[threeAttributeName] = componentType.name
  850. attributeNormalizedMap[threeAttributeName] = accessorDef.normalized === true
  851. }
  852. }
  853. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  854. return new Promise(function (resolve) {
  855. dracoLoader.decodeDracoFile(
  856. bufferView,
  857. function (geometry) {
  858. for (const attributeName in geometry.attributes) {
  859. const attribute = geometry.attributes[attributeName]
  860. const normalized = attributeNormalizedMap[attributeName]
  861. if (normalized !== undefined) attribute.normalized = normalized
  862. }
  863. resolve(geometry)
  864. },
  865. threeAttributeMap,
  866. attributeTypeMap
  867. )
  868. })
  869. })
  870. }
  871. }
  872. /**
  873. * THREE.Texture Transform Extension
  874. *
  875. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  876. */
  877. class GLTFTextureTransformExtension {
  878. constructor() {
  879. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM
  880. }
  881. extendTexture(texture, transform) {
  882. if (transform.texCoord !== undefined) {
  883. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.')
  884. }
  885. if (transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined) {
  886. // See https://github.com/mrdoob/three.js/issues/21819.
  887. return texture
  888. }
  889. texture = texture.clone()
  890. if (transform.offset !== undefined) {
  891. texture.offset.fromArray(transform.offset)
  892. }
  893. if (transform.rotation !== undefined) {
  894. texture.rotation = transform.rotation
  895. }
  896. if (transform.scale !== undefined) {
  897. texture.repeat.fromArray(transform.scale)
  898. }
  899. texture.needsUpdate = true
  900. return texture
  901. }
  902. }
  903. /**
  904. * Specular-Glossiness Extension
  905. *
  906. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness
  907. */
  908. /**
  909. * A sub class of StandardMaterial with some of the functionality
  910. * changed via the `onBeforeCompile` callback
  911. * @pailhead
  912. */
  913. class GLTFMeshStandardSGMaterial extends THREE.MeshStandardMaterial {
  914. constructor(params) {
  915. super()
  916. this.isGLTFSpecularGlossinessMaterial = true //various chunks that need replacing
  917. const specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n')
  918. const glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n')
  919. const specularMapFragmentChunk = [
  920. 'vec3 specularFactor = specular;',
  921. '#ifdef USE_SPECULARMAP',
  922. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  923. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  924. ' specularFactor *= texelSpecular.rgb;',
  925. '#endif',
  926. ].join('\n')
  927. const glossinessMapFragmentChunk = [
  928. 'float glossinessFactor = glossiness;',
  929. '#ifdef USE_GLOSSINESSMAP',
  930. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  931. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  932. ' glossinessFactor *= texelGlossiness.a;',
  933. '#endif',
  934. ].join('\n')
  935. const lightPhysicalFragmentChunk = [
  936. 'PhysicalMaterial material;',
  937. 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );',
  938. 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );',
  939. 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );',
  940. 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.',
  941. 'material.roughness += geometryRoughness;',
  942. 'material.roughness = min( material.roughness, 1.0 );',
  943. 'material.specularColor = specularFactor;',
  944. ].join('\n')
  945. const uniforms = {
  946. specular: {
  947. value: new THREE.Color().setHex(0xffffff),
  948. },
  949. glossiness: {
  950. value: 1,
  951. },
  952. specularMap: {
  953. value: null,
  954. },
  955. glossinessMap: {
  956. value: null,
  957. },
  958. }
  959. this._extraUniforms = uniforms
  960. this.onBeforeCompile = function (shader) {
  961. for (const uniformName in uniforms) {
  962. shader.uniforms[uniformName] = uniforms[uniformName]
  963. }
  964. shader.fragmentShader = shader.fragmentShader
  965. .replace('uniform float roughness;', 'uniform vec3 specular;')
  966. .replace('uniform float metalness;', 'uniform float glossiness;')
  967. .replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk)
  968. .replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk)
  969. .replace('#include <roughnessmap_fragment>', specularMapFragmentChunk)
  970. .replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk)
  971. .replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk)
  972. }
  973. Object.defineProperties(this, {
  974. specular: {
  975. get: function () {
  976. return uniforms.specular.value
  977. },
  978. set: function (v) {
  979. uniforms.specular.value = v
  980. },
  981. },
  982. specularMap: {
  983. get: function () {
  984. return uniforms.specularMap.value
  985. },
  986. set: function (v) {
  987. uniforms.specularMap.value = v
  988. if (v) {
  989. this.defines.USE_SPECULARMAP = '' // USE_UV is set by the renderer for specular maps
  990. } else {
  991. delete this.defines.USE_SPECULARMAP
  992. }
  993. },
  994. },
  995. glossiness: {
  996. get: function () {
  997. return uniforms.glossiness.value
  998. },
  999. set: function (v) {
  1000. uniforms.glossiness.value = v
  1001. },
  1002. },
  1003. glossinessMap: {
  1004. get: function () {
  1005. return uniforms.glossinessMap.value
  1006. },
  1007. set: function (v) {
  1008. uniforms.glossinessMap.value = v
  1009. if (v) {
  1010. this.defines.USE_GLOSSINESSMAP = ''
  1011. this.defines.USE_UV = ''
  1012. } else {
  1013. delete this.defines.USE_GLOSSINESSMAP
  1014. delete this.defines.USE_UV
  1015. }
  1016. },
  1017. },
  1018. })
  1019. delete this.metalness
  1020. delete this.roughness
  1021. delete this.metalnessMap
  1022. delete this.roughnessMap
  1023. this.setValues(params)
  1024. }
  1025. copy(source) {
  1026. super.copy(source)
  1027. this.specularMap = source.specularMap
  1028. this.specular.copy(source.specular)
  1029. this.glossinessMap = source.glossinessMap
  1030. this.glossiness = source.glossiness
  1031. delete this.metalness
  1032. delete this.roughness
  1033. delete this.metalnessMap
  1034. delete this.roughnessMap
  1035. return this
  1036. }
  1037. }
  1038. class GLTFMaterialsPbrSpecularGlossinessExtension {
  1039. constructor() {
  1040. this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS
  1041. this.specularGlossinessParams = [
  1042. 'color',
  1043. 'map',
  1044. 'lightMap',
  1045. 'lightMapIntensity',
  1046. 'aoMap',
  1047. 'aoMapIntensity',
  1048. 'emissive',
  1049. 'emissiveIntensity',
  1050. 'emissiveMap',
  1051. 'bumpMap',
  1052. 'bumpScale',
  1053. 'normalMap',
  1054. 'normalMapType',
  1055. 'displacementMap',
  1056. 'displacementScale',
  1057. 'displacementBias',
  1058. 'specularMap',
  1059. 'specular',
  1060. 'glossinessMap',
  1061. 'glossiness',
  1062. 'alphaMap',
  1063. 'envMap',
  1064. 'envMapIntensity',
  1065. ]
  1066. }
  1067. getMaterialType() {
  1068. return GLTFMeshStandardSGMaterial
  1069. }
  1070. extendParams(materialParams, materialDef, parser) {
  1071. const pbrSpecularGlossiness = materialDef.extensions[this.name]
  1072. materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
  1073. materialParams.opacity = 1.0
  1074. const pending = []
  1075. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  1076. const array = pbrSpecularGlossiness.diffuseFactor
  1077. materialParams.color.fromArray(array)
  1078. materialParams.opacity = array[3]
  1079. }
  1080. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  1081. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, THREE.sRGBEncoding))
  1082. }
  1083. materialParams.emissive = new THREE.Color(0.0, 0.0, 0.0)
  1084. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0
  1085. materialParams.specular = new THREE.Color(1.0, 1.0, 1.0)
  1086. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  1087. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor)
  1088. }
  1089. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  1090. const specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture
  1091. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef))
  1092. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef, THREE.sRGBEncoding))
  1093. }
  1094. return Promise.all(pending)
  1095. }
  1096. createMaterial(materialParams) {
  1097. const material = new GLTFMeshStandardSGMaterial(materialParams)
  1098. material.fog = true
  1099. material.color = materialParams.color
  1100. material.map = materialParams.map === undefined ? null : materialParams.map
  1101. material.lightMap = null
  1102. material.lightMapIntensity = 1.0
  1103. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap
  1104. material.aoMapIntensity = 1.0
  1105. material.emissive = materialParams.emissive
  1106. material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity
  1107. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap
  1108. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap
  1109. material.bumpScale = 1
  1110. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap
  1111. material.normalMapType = THREE.TangentSpaceNormalMap
  1112. if (materialParams.normalScale) material.normalScale = materialParams.normalScale
  1113. material.displacementMap = null
  1114. material.displacementScale = 1
  1115. material.displacementBias = 0
  1116. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap
  1117. material.specular = materialParams.specular
  1118. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap
  1119. material.glossiness = materialParams.glossiness
  1120. material.alphaMap = null
  1121. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap
  1122. material.envMapIntensity = 1.0
  1123. return material
  1124. }
  1125. }
  1126. /**
  1127. * THREE.Mesh Quantization Extension
  1128. *
  1129. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  1130. */
  1131. class GLTFMeshQuantizationExtension {
  1132. constructor() {
  1133. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION
  1134. }
  1135. }
  1136. /*********************************/
  1137. /********** INTERPOLATION ********/
  1138. /*********************************/
  1139. // Spline Interpolation
  1140. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  1141. class GLTFCubicSplineInterpolant extends THREE.Interpolant {
  1142. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  1143. super(parameterPositions, sampleValues, sampleSize, resultBuffer)
  1144. }
  1145. copySampleValue_(index) {
  1146. // Copies a sample value to the result buffer. See description of glTF
  1147. // CUBICSPLINE values layout in interpolate_() function below.
  1148. const result = this.resultBuffer,
  1149. values = this.sampleValues,
  1150. valueSize = this.valueSize,
  1151. offset = index * valueSize * 3 + valueSize
  1152. for (let i = 0; i !== valueSize; i++) {
  1153. result[i] = values[offset + i]
  1154. }
  1155. return result
  1156. }
  1157. interpolate_(i1, t0, t, t1) {
  1158. const result = this.resultBuffer
  1159. const values = this.sampleValues
  1160. const stride = this.valueSize
  1161. const stride2 = stride * 2
  1162. const stride3 = stride * 3
  1163. const td = t1 - t0
  1164. const p = (t - t0) / td
  1165. const pp = p * p
  1166. const ppp = pp * p
  1167. const offset1 = i1 * stride3
  1168. const offset0 = offset1 - stride3
  1169. const s2 = -2 * ppp + 3 * pp
  1170. const s3 = ppp - pp
  1171. const s0 = 1 - s2
  1172. const s1 = s3 - pp + p // Layout of keyframe output values for CUBICSPLINE animations:
  1173. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  1174. for (let i = 0; i !== stride; i++) {
  1175. const p0 = values[offset0 + i + stride] // splineVertex_k
  1176. const m0 = values[offset0 + i + stride2] * td // outTangent_k * (t_k+1 - t_k)
  1177. const p1 = values[offset1 + i + stride] // splineVertex_k+1
  1178. const m1 = values[offset1 + i] * td // inTangent_k+1 * (t_k+1 - t_k)
  1179. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1
  1180. }
  1181. return result
  1182. }
  1183. }
  1184. const _q = new THREE.Quaternion()
  1185. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  1186. interpolate_(i1, t0, t, t1) {
  1187. const result = super.interpolate_(i1, t0, t, t1)
  1188. _q.fromArray(result).normalize().toArray(result)
  1189. return result
  1190. }
  1191. }
  1192. /*********************************/
  1193. /********** INTERNALS ************/
  1194. /*********************************/
  1195. /* CONSTANTS */
  1196. const WEBGL_CONSTANTS = {
  1197. FLOAT: 5126,
  1198. //FLOAT_MAT2: 35674,
  1199. FLOAT_MAT3: 35675,
  1200. FLOAT_MAT4: 35676,
  1201. FLOAT_VEC2: 35664,
  1202. FLOAT_VEC3: 35665,
  1203. FLOAT_VEC4: 35666,
  1204. LINEAR: 9729,
  1205. REPEAT: 10497,
  1206. SAMPLER_2D: 35678,
  1207. POINTS: 0,
  1208. LINES: 1,
  1209. LINE_LOOP: 2,
  1210. LINE_STRIP: 3,
  1211. TRIANGLES: 4,
  1212. TRIANGLE_STRIP: 5,
  1213. TRIANGLE_FAN: 6,
  1214. UNSIGNED_BYTE: 5121,
  1215. UNSIGNED_SHORT: 5123,
  1216. }
  1217. const WEBGL_COMPONENT_TYPES = {
  1218. 5120: Int8Array,
  1219. 5121: Uint8Array,
  1220. 5122: Int16Array,
  1221. 5123: Uint16Array,
  1222. 5125: Uint32Array,
  1223. 5126: Float32Array,
  1224. }
  1225. const WEBGL_FILTERS = {
  1226. 9728: THREE.NearestFilter,
  1227. 9729: THREE.LinearFilter,
  1228. 9984: THREE.NearestMipmapNearestFilter,
  1229. 9985: THREE.LinearMipmapNearestFilter,
  1230. 9986: THREE.NearestMipmapLinearFilter,
  1231. 9987: THREE.LinearMipmapLinearFilter,
  1232. }
  1233. const WEBGL_WRAPPINGS = {
  1234. 33071: THREE.ClampToEdgeWrapping,
  1235. 33648: THREE.MirroredRepeatWrapping,
  1236. 10497: THREE.RepeatWrapping,
  1237. }
  1238. const WEBGL_TYPE_SIZES = {
  1239. SCALAR: 1,
  1240. VEC2: 2,
  1241. VEC3: 3,
  1242. VEC4: 4,
  1243. MAT2: 4,
  1244. MAT3: 9,
  1245. MAT4: 16,
  1246. }
  1247. const ATTRIBUTES = {
  1248. POSITION: 'position',
  1249. NORMAL: 'normal',
  1250. TANGENT: 'tangent',
  1251. TEXCOORD_0: 'uv',
  1252. TEXCOORD_1: 'uv2',
  1253. COLOR_0: 'color',
  1254. WEIGHTS_0: 'skinWeight',
  1255. JOINTS_0: 'skinIndex',
  1256. }
  1257. const PATH_PROPERTIES = {
  1258. scale: 'scale',
  1259. translation: 'position',
  1260. rotation: 'quaternion',
  1261. weights: 'morphTargetInfluences',
  1262. }
  1263. const INTERPOLATION = {
  1264. CUBICSPLINE: undefined,
  1265. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  1266. // keyframe track will be initialized with a default interpolation type, then modified.
  1267. LINEAR: THREE.InterpolateLinear,
  1268. STEP: THREE.InterpolateDiscrete,
  1269. }
  1270. const ALPHA_MODES = {
  1271. OPAQUE: 'OPAQUE',
  1272. MASK: 'MASK',
  1273. BLEND: 'BLEND',
  1274. }
  1275. /**
  1276. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  1277. */
  1278. function createDefaultMaterial(cache) {
  1279. if (cache['DefaultMaterial'] === undefined) {
  1280. cache['DefaultMaterial'] = new THREE.MeshStandardMaterial({
  1281. color: 0xffffff,
  1282. emissive: 0x000000,
  1283. metalness: 1,
  1284. roughness: 1,
  1285. transparent: false,
  1286. depthTest: true,
  1287. side: THREE.FrontSide,
  1288. })
  1289. }
  1290. return cache['DefaultMaterial']
  1291. }
  1292. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  1293. // Add unknown glTF extensions to an object's userData.
  1294. for (const name in objectDef.extensions) {
  1295. if (knownExtensions[name] === undefined) {
  1296. object.userData.gltfExtensions = object.userData.gltfExtensions || {}
  1297. object.userData.gltfExtensions[name] = objectDef.extensions[name]
  1298. }
  1299. }
  1300. }
  1301. /**
  1302. * @param {Object3D|Material|BufferGeometry} object
  1303. * @param {GLTF.definition} gltfDef
  1304. */
  1305. function assignExtrasToUserData(object, gltfDef) {
  1306. if (gltfDef.extras !== undefined) {
  1307. if (typeof gltfDef.extras === 'object') {
  1308. Object.assign(object.userData, gltfDef.extras)
  1309. } else {
  1310. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras)
  1311. }
  1312. }
  1313. }
  1314. /**
  1315. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  1316. *
  1317. * @param {BufferGeometry} geometry
  1318. * @param {Array<GLTF.Target>} targets
  1319. * @param {GLTFParser} parser
  1320. * @return {Promise<BufferGeometry>}
  1321. */
  1322. function addMorphTargets(geometry, targets, parser) {
  1323. let hasMorphPosition = false
  1324. let hasMorphNormal = false
  1325. let hasMorphColor = false
  1326. for (let i = 0, il = targets.length; i < il; i++) {
  1327. const target = targets[i]
  1328. if (target.POSITION !== undefined) hasMorphPosition = true
  1329. if (target.NORMAL !== undefined) hasMorphNormal = true
  1330. if (target.COLOR_0 !== undefined) hasMorphColor = true
  1331. if (hasMorphPosition && hasMorphNormal && hasMorphColor) break
  1332. }
  1333. if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry)
  1334. const pendingPositionAccessors = []
  1335. const pendingNormalAccessors = []
  1336. const pendingColorAccessors = []
  1337. for (let i = 0, il = targets.length; i < il; i++) {
  1338. const target = targets[i]
  1339. if (hasMorphPosition) {
  1340. const pendingAccessor = target.POSITION !== undefined ? parser.getDependency('accessor', target.POSITION) : geometry.attributes.position
  1341. pendingPositionAccessors.push(pendingAccessor)
  1342. }
  1343. if (hasMorphNormal) {
  1344. const pendingAccessor = target.NORMAL !== undefined ? parser.getDependency('accessor', target.NORMAL) : geometry.attributes.normal
  1345. pendingNormalAccessors.push(pendingAccessor)
  1346. }
  1347. if (hasMorphColor) {
  1348. const pendingAccessor = target.COLOR_0 !== undefined ? parser.getDependency('accessor', target.COLOR_0) : geometry.attributes.color
  1349. pendingColorAccessors.push(pendingAccessor)
  1350. }
  1351. }
  1352. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors), Promise.all(pendingColorAccessors)]).then(function (accessors) {
  1353. const morphPositions = accessors[0]
  1354. const morphNormals = accessors[1]
  1355. const morphColors = accessors[2]
  1356. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions
  1357. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals
  1358. if (hasMorphColor) geometry.morphAttributes.color = morphColors
  1359. geometry.morphTargetsRelative = true
  1360. return geometry
  1361. })
  1362. }
  1363. /**
  1364. * @param {Mesh} mesh
  1365. * @param {GLTF.Mesh} meshDef
  1366. */
  1367. function updateMorphTargets(mesh, meshDef) {
  1368. mesh.updateMorphTargets()
  1369. if (meshDef.weights !== undefined) {
  1370. for (let i = 0, il = meshDef.weights.length; i < il; i++) {
  1371. mesh.morphTargetInfluences[i] = meshDef.weights[i]
  1372. }
  1373. } // .extras has user-defined data, so check that .extras.targetNames is an array.
  1374. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  1375. const targetNames = meshDef.extras.targetNames
  1376. if (mesh.morphTargetInfluences.length === targetNames.length) {
  1377. mesh.morphTargetDictionary = {}
  1378. for (let i = 0, il = targetNames.length; i < il; i++) {
  1379. mesh.morphTargetDictionary[targetNames[i]] = i
  1380. }
  1381. } else {
  1382. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.')
  1383. }
  1384. }
  1385. }
  1386. function createPrimitiveKey(primitiveDef) {
  1387. const dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]
  1388. let geometryKey
  1389. if (dracoExtension) {
  1390. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes)
  1391. } else {
  1392. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode
  1393. }
  1394. return geometryKey
  1395. }
  1396. function createAttributesKey(attributes) {
  1397. let attributesKey = ''
  1398. const keys = Object.keys(attributes).sort()
  1399. for (let i = 0, il = keys.length; i < il; i++) {
  1400. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';'
  1401. }
  1402. return attributesKey
  1403. }
  1404. function getNormalizedComponentScale(constructor) {
  1405. // Reference:
  1406. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  1407. switch (constructor) {
  1408. case Int8Array:
  1409. return 1 / 127
  1410. case Uint8Array:
  1411. return 1 / 255
  1412. case Int16Array:
  1413. return 1 / 32767
  1414. case Uint16Array:
  1415. return 1 / 65535
  1416. default:
  1417. throw new Error('THREE.GLTFLoader: Unsupported normalized accessor component type.')
  1418. }
  1419. }
  1420. function getImageURIMimeType(uri) {
  1421. if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return 'image/jpeg'
  1422. if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return 'image/webp'
  1423. return 'image/png'
  1424. }
  1425. /* GLTF PARSER */
  1426. class GLTFParser {
  1427. constructor(json = {}, options = {}) {
  1428. this.json = json
  1429. this.extensions = {}
  1430. this.plugins = {}
  1431. this.options = options // loader object cache
  1432. this.cache = new GLTFRegistry() // associations between Three.js objects and glTF elements
  1433. this.associations = new Map() // THREE.BufferGeometry caching
  1434. this.primitiveCache = {} // THREE.Object3D instance caches
  1435. this.meshCache = {
  1436. refs: {},
  1437. uses: {},
  1438. }
  1439. this.cameraCache = {
  1440. refs: {},
  1441. uses: {},
  1442. }
  1443. this.lightCache = {
  1444. refs: {},
  1445. uses: {},
  1446. }
  1447. this.sourceCache = {}
  1448. this.textureCache = {} // Track node names, to ensure no duplicates
  1449. this.nodeNamesUsed = {} // Use an THREE.ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  1450. // expensive work of uploading a texture to the GPU off the main thread.
  1451. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true
  1452. const isFirefox = navigator.userAgent.indexOf('Firefox') > -1
  1453. const firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1
  1454. if (typeof createImageBitmap === 'undefined' || isSafari || (isFirefox && firefoxVersion < 98)) {
  1455. this.textureLoader = new THREE.TextureLoader(this.options.manager)
  1456. } else {
  1457. this.textureLoader = new THREE.ImageBitmapLoader(this.options.manager)
  1458. }
  1459. this.textureLoader.setCrossOrigin(this.options.crossOrigin)
  1460. this.textureLoader.setRequestHeader(this.options.requestHeader)
  1461. this.fileLoader = new THREE.FileLoader(this.options.manager)
  1462. this.fileLoader.setResponseType('arraybuffer')
  1463. if (this.options.crossOrigin === 'use-credentials') {
  1464. this.fileLoader.setWithCredentials(true)
  1465. }
  1466. }
  1467. setExtensions(extensions) {
  1468. this.extensions = extensions
  1469. }
  1470. setPlugins(plugins) {
  1471. this.plugins = plugins
  1472. }
  1473. parse(onLoad, onError) {
  1474. const parser = this
  1475. const json = this.json
  1476. const extensions = this.extensions // Clear the loader cache
  1477. this.cache.removeAll() // Mark the special nodes/meshes in json for efficient parse
  1478. this._invokeAll(function (ext) {
  1479. return ext._markDefs && ext._markDefs()
  1480. })
  1481. Promise.all(
  1482. this._invokeAll(function (ext) {
  1483. return ext.beforeRoot && ext.beforeRoot()
  1484. })
  1485. )
  1486. .then(function () {
  1487. return Promise.all([parser.getDependencies('scene'), parser.getDependencies('animation'), parser.getDependencies('camera')])
  1488. })
  1489. .then(function (dependencies) {
  1490. const result = {
  1491. scene: dependencies[0][json.scene || 0],
  1492. scenes: dependencies[0],
  1493. animations: dependencies[1],
  1494. cameras: dependencies[2],
  1495. asset: json.asset,
  1496. parser: parser,
  1497. userData: {},
  1498. }
  1499. addUnknownExtensionsToUserData(extensions, result, json)
  1500. assignExtrasToUserData(result, json)
  1501. Promise.all(
  1502. parser._invokeAll(function (ext) {
  1503. return ext.afterRoot && ext.afterRoot(result)
  1504. })
  1505. ).then(function () {
  1506. onLoad(result)
  1507. })
  1508. })
  1509. .catch(onError)
  1510. }
  1511. /**
  1512. * Marks the special nodes/meshes in json for efficient parse.
  1513. */
  1514. _markDefs() {
  1515. const nodeDefs = this.json.nodes || []
  1516. const skinDefs = this.json.skins || []
  1517. const meshDefs = this.json.meshes || [] // Nothing in the node definition indicates whether it is a THREE.Bone or an
  1518. // THREE.Object3D. Use the skins' joint references to mark bones.
  1519. for (let skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  1520. const joints = skinDefs[skinIndex].joints
  1521. for (let i = 0, il = joints.length; i < il; i++) {
  1522. nodeDefs[joints[i]].isBone = true
  1523. }
  1524. } // Iterate over all nodes, marking references to shared resources,
  1525. // as well as skeleton joints.
  1526. for (let nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  1527. const nodeDef = nodeDefs[nodeIndex]
  1528. if (nodeDef.mesh !== undefined) {
  1529. this._addNodeRef(this.meshCache, nodeDef.mesh) // Nothing in the mesh definition indicates whether it is
  1530. // a THREE.SkinnedMesh or THREE.Mesh. Use the node's mesh reference
  1531. // to mark THREE.SkinnedMesh if node has skin.
  1532. if (nodeDef.skin !== undefined) {
  1533. meshDefs[nodeDef.mesh].isSkinnedMesh = true
  1534. }
  1535. }
  1536. if (nodeDef.camera !== undefined) {
  1537. this._addNodeRef(this.cameraCache, nodeDef.camera)
  1538. }
  1539. }
  1540. }
  1541. /**
  1542. * Counts references to shared node / THREE.Object3D resources. These resources
  1543. * can be reused, or "instantiated", at multiple nodes in the scene
  1544. * hierarchy. THREE.Mesh, Camera, and Light instances are instantiated and must
  1545. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  1546. * Textures) can be reused directly and are not marked here.
  1547. *
  1548. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  1549. */
  1550. _addNodeRef(cache, index) {
  1551. if (index === undefined) return
  1552. if (cache.refs[index] === undefined) {
  1553. cache.refs[index] = cache.uses[index] = 0
  1554. }
  1555. cache.refs[index]++
  1556. }
  1557. /** Returns a reference to a shared resource, cloning it if necessary. */
  1558. _getNodeRef(cache, index, object) {
  1559. if (cache.refs[index] <= 1) return object
  1560. const ref = object.clone() // Propagates mappings to the cloned object, prevents mappings on the
  1561. // original object from being lost.
  1562. const updateMappings = (original, clone) => {
  1563. const mappings = this.associations.get(original)
  1564. if (mappings != null) {
  1565. this.associations.set(clone, mappings)
  1566. }
  1567. for (const [i, child] of original.children.entries()) {
  1568. updateMappings(child, clone.children[i])
  1569. }
  1570. }
  1571. updateMappings(object, ref)
  1572. ref.name += '_instance_' + cache.uses[index]++
  1573. return ref
  1574. }
  1575. _invokeOne(func) {
  1576. const extensions = Object.values(this.plugins)
  1577. extensions.push(this)
  1578. for (let i = 0; i < extensions.length; i++) {
  1579. const result = func(extensions[i])
  1580. if (result) return result
  1581. }
  1582. return null
  1583. }
  1584. _invokeAll(func) {
  1585. const extensions = Object.values(this.plugins)
  1586. extensions.unshift(this)
  1587. const pending = []
  1588. for (let i = 0; i < extensions.length; i++) {
  1589. const result = func(extensions[i])
  1590. if (result) pending.push(result)
  1591. }
  1592. return pending
  1593. }
  1594. /**
  1595. * Requests the specified dependency asynchronously, with caching.
  1596. * @param {string} type
  1597. * @param {number} index
  1598. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  1599. */
  1600. getDependency(type, index) {
  1601. const cacheKey = type + ':' + index
  1602. let dependency = this.cache.get(cacheKey)
  1603. if (!dependency) {
  1604. switch (type) {
  1605. case 'scene':
  1606. dependency = this.loadScene(index)
  1607. break
  1608. case 'node':
  1609. dependency = this.loadNode(index)
  1610. break
  1611. case 'mesh':
  1612. dependency = this._invokeOne(function (ext) {
  1613. return ext.loadMesh && ext.loadMesh(index)
  1614. })
  1615. break
  1616. case 'accessor':
  1617. dependency = this.loadAccessor(index)
  1618. break
  1619. case 'bufferView':
  1620. dependency = this._invokeOne(function (ext) {
  1621. return ext.loadBufferView && ext.loadBufferView(index)
  1622. })
  1623. break
  1624. case 'buffer':
  1625. dependency = this.loadBuffer(index)
  1626. break
  1627. case 'material':
  1628. dependency = this._invokeOne(function (ext) {
  1629. return ext.loadMaterial && ext.loadMaterial(index)
  1630. })
  1631. break
  1632. case 'texture':
  1633. dependency = this._invokeOne(function (ext) {
  1634. return ext.loadTexture && ext.loadTexture(index)
  1635. })
  1636. break
  1637. case 'skin':
  1638. dependency = this.loadSkin(index)
  1639. break
  1640. case 'animation':
  1641. dependency = this._invokeOne(function (ext) {
  1642. return ext.loadAnimation && ext.loadAnimation(index)
  1643. })
  1644. break
  1645. case 'camera':
  1646. dependency = this.loadCamera(index)
  1647. break
  1648. default:
  1649. throw new Error('Unknown type: ' + type)
  1650. }
  1651. this.cache.add(cacheKey, dependency)
  1652. }
  1653. return dependency
  1654. }
  1655. /**
  1656. * Requests all dependencies of the specified type asynchronously, with caching.
  1657. * @param {string} type
  1658. * @return {Promise<Array<Object>>}
  1659. */
  1660. getDependencies(type) {
  1661. let dependencies = this.cache.get(type)
  1662. if (!dependencies) {
  1663. const parser = this
  1664. const defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || []
  1665. dependencies = Promise.all(
  1666. defs.map(function (def, index) {
  1667. return parser.getDependency(type, index)
  1668. })
  1669. )
  1670. this.cache.add(type, dependencies)
  1671. }
  1672. return dependencies
  1673. }
  1674. /**
  1675. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1676. * @param {number} bufferIndex
  1677. * @return {Promise<ArrayBuffer>}
  1678. */
  1679. loadBuffer(bufferIndex) {
  1680. const bufferDef = this.json.buffers[bufferIndex]
  1681. const loader = this.fileLoader
  1682. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  1683. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.')
  1684. } // If present, GLB container is required to be the first buffer.
  1685. if (bufferDef.uri === undefined && bufferIndex === 0) {
  1686. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body)
  1687. }
  1688. const options = this.options
  1689. return new Promise(function (resolve, reject) {
  1690. loader.load(THREE.LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  1691. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'))
  1692. })
  1693. })
  1694. }
  1695. /**
  1696. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  1697. * @param {number} bufferViewIndex
  1698. * @return {Promise<ArrayBuffer>}
  1699. */
  1700. loadBufferView(bufferViewIndex) {
  1701. const bufferViewDef = this.json.bufferViews[bufferViewIndex]
  1702. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  1703. const byteLength = bufferViewDef.byteLength || 0
  1704. const byteOffset = bufferViewDef.byteOffset || 0
  1705. return buffer.slice(byteOffset, byteOffset + byteLength)
  1706. })
  1707. }
  1708. /**
  1709. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  1710. * @param {number} accessorIndex
  1711. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  1712. */
  1713. loadAccessor(accessorIndex) {
  1714. const parser = this
  1715. const json = this.json
  1716. const accessorDef = this.json.accessors[accessorIndex]
  1717. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  1718. // Ignore empty accessors, which may be used to declare runtime
  1719. // information about attributes coming from another source (e.g. Draco
  1720. // compression extension).
  1721. return Promise.resolve(null)
  1722. }
  1723. const pendingBufferViews = []
  1724. if (accessorDef.bufferView !== undefined) {
  1725. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView))
  1726. } else {
  1727. pendingBufferViews.push(null)
  1728. }
  1729. if (accessorDef.sparse !== undefined) {
  1730. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView))
  1731. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView))
  1732. }
  1733. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  1734. const bufferView = bufferViews[0]
  1735. const itemSize = WEBGL_TYPE_SIZES[accessorDef.type]
  1736. const TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType] // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  1737. const elementBytes = TypedArray.BYTES_PER_ELEMENT
  1738. const itemBytes = elementBytes * itemSize
  1739. const byteOffset = accessorDef.byteOffset || 0
  1740. const byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined
  1741. const normalized = accessorDef.normalized === true
  1742. let array, bufferAttribute // The buffer is not interleaved if the stride is the item size in bytes.
  1743. if (byteStride && byteStride !== itemBytes) {
  1744. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own THREE.InterleavedBuffer
  1745. // This makes sure that IBA.count reflects accessor.count properly
  1746. const ibSlice = Math.floor(byteOffset / byteStride)
  1747. const ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count
  1748. let ib = parser.cache.get(ibCacheKey)
  1749. if (!ib) {
  1750. array = new TypedArray(bufferView, ibSlice * byteStride, (accessorDef.count * byteStride) / elementBytes) // Integer parameters to IB/IBA are in array elements, not bytes.
  1751. ib = new THREE.InterleavedBuffer(array, byteStride / elementBytes)
  1752. parser.cache.add(ibCacheKey, ib)
  1753. }
  1754. bufferAttribute = new THREE.InterleavedBufferAttribute(ib, itemSize, (byteOffset % byteStride) / elementBytes, normalized)
  1755. } else {
  1756. if (bufferView === null) {
  1757. array = new TypedArray(accessorDef.count * itemSize)
  1758. } else {
  1759. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize)
  1760. }
  1761. bufferAttribute = new THREE.BufferAttribute(array, itemSize, normalized)
  1762. } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  1763. if (accessorDef.sparse !== undefined) {
  1764. const itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR
  1765. const TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType]
  1766. const byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0
  1767. const byteOffsetValues = accessorDef.sparse.values.byteOffset || 0
  1768. const sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices)
  1769. const sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize)
  1770. if (bufferView !== null) {
  1771. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  1772. bufferAttribute = new THREE.BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized)
  1773. }
  1774. for (let i = 0, il = sparseIndices.length; i < il; i++) {
  1775. const index = sparseIndices[i]
  1776. bufferAttribute.setX(index, sparseValues[i * itemSize])
  1777. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1])
  1778. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2])
  1779. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3])
  1780. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse THREE.BufferAttribute.')
  1781. }
  1782. }
  1783. return bufferAttribute
  1784. })
  1785. }
  1786. /**
  1787. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  1788. * @param {number} textureIndex
  1789. * @return {Promise<THREE.Texture>}
  1790. */
  1791. loadTexture(textureIndex) {
  1792. const json = this.json
  1793. const options = this.options
  1794. const textureDef = json.textures[textureIndex]
  1795. const sourceIndex = textureDef.source
  1796. const sourceDef = json.images[sourceIndex]
  1797. let loader = this.textureLoader
  1798. if (sourceDef.uri) {
  1799. const handler = options.manager.getHandler(sourceDef.uri)
  1800. if (handler !== null) loader = handler
  1801. }
  1802. return this.loadTextureImage(textureIndex, sourceIndex, loader)
  1803. }
  1804. loadTextureImage(textureIndex, sourceIndex, loader) {
  1805. const parser = this
  1806. const json = this.json
  1807. const textureDef = json.textures[textureIndex]
  1808. const sourceDef = json.images[sourceIndex]
  1809. const cacheKey = (sourceDef.uri || sourceDef.bufferView) + ':' + textureDef.sampler
  1810. if (this.textureCache[cacheKey]) {
  1811. // See https://github.com/mrdoob/three.js/issues/21559.
  1812. return this.textureCache[cacheKey]
  1813. }
  1814. const promise = this.loadImageSource(sourceIndex, loader)
  1815. .then(function (texture) {
  1816. texture.flipY = false
  1817. if (textureDef.name) texture.name = textureDef.name
  1818. const samplers = json.samplers || {}
  1819. const sampler = samplers[textureDef.sampler] || {}
  1820. texture.magFilter = WEBGL_FILTERS[sampler.magFilter] || THREE.LinearFilter
  1821. texture.minFilter = WEBGL_FILTERS[sampler.minFilter] || THREE.LinearMipmapLinearFilter
  1822. texture.wrapS = WEBGL_WRAPPINGS[sampler.wrapS] || THREE.RepeatWrapping
  1823. texture.wrapT = WEBGL_WRAPPINGS[sampler.wrapT] || THREE.RepeatWrapping
  1824. parser.associations.set(texture, {
  1825. textures: textureIndex,
  1826. })
  1827. return texture
  1828. })
  1829. .catch(function () {
  1830. return null
  1831. })
  1832. this.textureCache[cacheKey] = promise
  1833. return promise
  1834. }
  1835. loadImageSource(sourceIndex, loader) {
  1836. const parser = this
  1837. const json = this.json
  1838. const options = this.options
  1839. if (this.sourceCache[sourceIndex] !== undefined) {
  1840. return this.sourceCache[sourceIndex].then(texture => texture.clone())
  1841. }
  1842. const sourceDef = json.images[sourceIndex]
  1843. const URL = self.URL || self.webkitURL
  1844. let sourceURI = sourceDef.uri || ''
  1845. let isObjectURL = false
  1846. if (sourceDef.bufferView !== undefined) {
  1847. // Load binary image data from bufferView, if provided.
  1848. sourceURI = parser.getDependency('bufferView', sourceDef.bufferView).then(function (bufferView) {
  1849. isObjectURL = true
  1850. const blob = new Blob([bufferView], {
  1851. type: sourceDef.mimeType,
  1852. })
  1853. sourceURI = URL.createObjectURL(blob)
  1854. return sourceURI
  1855. })
  1856. } else if (sourceDef.uri === undefined) {
  1857. throw new Error('THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView')
  1858. }
  1859. const promise = Promise.resolve(sourceURI)
  1860. .then(function (sourceURI) {
  1861. return new Promise(function (resolve, reject) {
  1862. let onLoad = resolve
  1863. if (loader.isImageBitmapLoader === true) {
  1864. onLoad = function (imageBitmap) {
  1865. const texture = new THREE.Texture(imageBitmap)
  1866. texture.needsUpdate = true
  1867. resolve(texture)
  1868. }
  1869. }
  1870. loader.load(THREE.LoaderUtils.resolveURL(sourceURI, options.path), onLoad, undefined, reject)
  1871. })
  1872. })
  1873. .then(function (texture) {
  1874. // Clean up resources and configure THREE.Texture.
  1875. if (isObjectURL === true) {
  1876. URL.revokeObjectURL(sourceURI)
  1877. }
  1878. texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri)
  1879. return texture
  1880. })
  1881. .catch(function (error) {
  1882. console.error("THREE.GLTFLoader: Couldn't load texture", sourceURI)
  1883. throw error
  1884. })
  1885. this.sourceCache[sourceIndex] = promise
  1886. return promise
  1887. }
  1888. /**
  1889. * Asynchronously assigns a texture to the given material parameters.
  1890. * @param {Object} materialParams
  1891. * @param {string} mapName
  1892. * @param {Object} mapDef
  1893. * @return {Promise<Texture>}
  1894. */
  1895. assignTexture(materialParams, mapName, mapDef, encoding) {
  1896. const parser = this
  1897. return this.getDependency('texture', mapDef.index).then(function (texture) {
  1898. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  1899. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  1900. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  1901. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.')
  1902. }
  1903. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  1904. const transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined
  1905. if (transform) {
  1906. const gltfReference = parser.associations.get(texture)
  1907. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform)
  1908. parser.associations.set(texture, gltfReference)
  1909. }
  1910. }
  1911. if (encoding !== undefined) {
  1912. texture.encoding = encoding
  1913. }
  1914. materialParams[mapName] = texture
  1915. return texture
  1916. })
  1917. }
  1918. /**
  1919. * Assigns final material to a THREE.Mesh, THREE.Line, or THREE.Points instance. The instance
  1920. * already has a material (generated from the glTF material options alone)
  1921. * but reuse of the same glTF material may require multiple threejs materials
  1922. * to accommodate different primitive types, defines, etc. New materials will
  1923. * be created if necessary, and reused from a cache.
  1924. * @param {Object3D} mesh THREE.Mesh, THREE.Line, or THREE.Points instance.
  1925. */
  1926. assignFinalMaterial(mesh) {
  1927. const geometry = mesh.geometry
  1928. let material = mesh.material
  1929. const useDerivativeTangents = geometry.attributes.tangent === undefined
  1930. const useVertexColors = geometry.attributes.color !== undefined
  1931. const useFlatShading = geometry.attributes.normal === undefined
  1932. if (mesh.isPoints) {
  1933. const cacheKey = 'PointsMaterial:' + material.uuid
  1934. let pointsMaterial = this.cache.get(cacheKey)
  1935. if (!pointsMaterial) {
  1936. pointsMaterial = new THREE.PointsMaterial()
  1937. THREE.Material.prototype.copy.call(pointsMaterial, material)
  1938. pointsMaterial.color.copy(material.color)
  1939. pointsMaterial.map = material.map
  1940. pointsMaterial.sizeAttenuation = false // glTF spec says points should be 1px
  1941. this.cache.add(cacheKey, pointsMaterial)
  1942. }
  1943. material = pointsMaterial
  1944. } else if (mesh.isLine) {
  1945. const cacheKey = 'LineBasicMaterial:' + material.uuid
  1946. let lineMaterial = this.cache.get(cacheKey)
  1947. if (!lineMaterial) {
  1948. lineMaterial = new THREE.LineBasicMaterial()
  1949. THREE.Material.prototype.copy.call(lineMaterial, material)
  1950. lineMaterial.color.copy(material.color)
  1951. this.cache.add(cacheKey, lineMaterial)
  1952. }
  1953. material = lineMaterial
  1954. } // Clone the material if it will be modified
  1955. if (useDerivativeTangents || useVertexColors || useFlatShading) {
  1956. let cacheKey = 'ClonedMaterial:' + material.uuid + ':'
  1957. if (material.isGLTFSpecularGlossinessMaterial) cacheKey += 'specular-glossiness:'
  1958. if (useDerivativeTangents) cacheKey += 'derivative-tangents:'
  1959. if (useVertexColors) cacheKey += 'vertex-colors:'
  1960. if (useFlatShading) cacheKey += 'flat-shading:'
  1961. let cachedMaterial = this.cache.get(cacheKey)
  1962. if (!cachedMaterial) {
  1963. cachedMaterial = material.clone()
  1964. if (useVertexColors) cachedMaterial.vertexColors = true
  1965. if (useFlatShading) cachedMaterial.flatShading = true
  1966. if (useDerivativeTangents) {
  1967. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  1968. if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1
  1969. if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1
  1970. }
  1971. this.cache.add(cacheKey, cachedMaterial)
  1972. this.associations.set(cachedMaterial, this.associations.get(material))
  1973. }
  1974. material = cachedMaterial
  1975. } // workarounds for mesh and geometry
  1976. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  1977. geometry.setAttribute('uv2', geometry.attributes.uv)
  1978. }
  1979. mesh.material = material
  1980. }
  1981. getMaterialType() {
  1982. return THREE.MeshStandardMaterial
  1983. }
  1984. /**
  1985. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  1986. * @param {number} materialIndex
  1987. * @return {Promise<Material>}
  1988. */
  1989. loadMaterial(materialIndex) {
  1990. const parser = this
  1991. const json = this.json
  1992. const extensions = this.extensions
  1993. const materialDef = json.materials[materialIndex]
  1994. let materialType
  1995. const materialParams = {}
  1996. const materialExtensions = materialDef.extensions || {}
  1997. const pending = []
  1998. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  1999. const sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]
  2000. materialType = sgExtension.getMaterialType()
  2001. pending.push(sgExtension.extendParams(materialParams, materialDef, parser))
  2002. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  2003. const kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT]
  2004. materialType = kmuExtension.getMaterialType()
  2005. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser))
  2006. } else {
  2007. // Specification:
  2008. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  2009. const metallicRoughness = materialDef.pbrMetallicRoughness || {}
  2010. materialParams.color = new THREE.Color(1.0, 1.0, 1.0)
  2011. materialParams.opacity = 1.0
  2012. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  2013. const array = metallicRoughness.baseColorFactor
  2014. materialParams.color.fromArray(array)
  2015. materialParams.opacity = array[3]
  2016. }
  2017. if (metallicRoughness.baseColorTexture !== undefined) {
  2018. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, THREE.sRGBEncoding))
  2019. }
  2020. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0
  2021. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0
  2022. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  2023. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture))
  2024. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture))
  2025. }
  2026. materialType = this._invokeOne(function (ext) {
  2027. return ext.getMaterialType && ext.getMaterialType(materialIndex)
  2028. })
  2029. pending.push(
  2030. Promise.all(
  2031. this._invokeAll(function (ext) {
  2032. return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams)
  2033. })
  2034. )
  2035. )
  2036. }
  2037. if (materialDef.doubleSided === true) {
  2038. materialParams.side = THREE.DoubleSide
  2039. }
  2040. const alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE
  2041. if (alphaMode === ALPHA_MODES.BLEND) {
  2042. materialParams.transparent = true // See: https://github.com/mrdoob/three.js/issues/17706
  2043. materialParams.depthWrite = false
  2044. } else {
  2045. materialParams.transparent = false
  2046. if (alphaMode === ALPHA_MODES.MASK) {
  2047. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5
  2048. }
  2049. }
  2050. if (materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  2051. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture))
  2052. materialParams.normalScale = new THREE.Vector2(1, 1)
  2053. if (materialDef.normalTexture.scale !== undefined) {
  2054. const scale = materialDef.normalTexture.scale
  2055. materialParams.normalScale.set(scale, scale)
  2056. }
  2057. }
  2058. if (materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  2059. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture))
  2060. if (materialDef.occlusionTexture.strength !== undefined) {
  2061. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength
  2062. }
  2063. }
  2064. if (materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial) {
  2065. materialParams.emissive = new THREE.Color().fromArray(materialDef.emissiveFactor)
  2066. }
  2067. if (materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial) {
  2068. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture, THREE.sRGBEncoding))
  2069. }
  2070. return Promise.all(pending).then(function () {
  2071. let material
  2072. if (materialType === GLTFMeshStandardSGMaterial) {
  2073. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams)
  2074. } else {
  2075. material = new materialType(materialParams)
  2076. }
  2077. if (materialDef.name) material.name = materialDef.name
  2078. assignExtrasToUserData(material, materialDef)
  2079. parser.associations.set(material, {
  2080. materials: materialIndex,
  2081. })
  2082. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef)
  2083. return material
  2084. })
  2085. }
  2086. /** When THREE.Object3D instances are targeted by animation, they need unique names. */
  2087. createUniqueName(originalName) {
  2088. const sanitizedName = THREE.PropertyBinding.sanitizeNodeName(originalName || '')
  2089. let name = sanitizedName
  2090. for (let i = 1; this.nodeNamesUsed[name]; ++i) {
  2091. name = sanitizedName + '_' + i
  2092. }
  2093. this.nodeNamesUsed[name] = true
  2094. return name
  2095. }
  2096. /**
  2097. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  2098. *
  2099. * Creates BufferGeometries from primitives.
  2100. *
  2101. * @param {Array<GLTF.Primitive>} primitives
  2102. * @return {Promise<Array<BufferGeometry>>}
  2103. */
  2104. loadGeometries(primitives) {
  2105. const parser = this
  2106. const extensions = this.extensions
  2107. const cache = this.primitiveCache
  2108. function createDracoPrimitive(primitive) {
  2109. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  2110. return addPrimitiveAttributes(geometry, primitive, parser)
  2111. })
  2112. }
  2113. const pending = []
  2114. for (let i = 0, il = primitives.length; i < il; i++) {
  2115. const primitive = primitives[i]
  2116. const cacheKey = createPrimitiveKey(primitive) // See if we've already created this geometry
  2117. const cached = cache[cacheKey]
  2118. if (cached) {
  2119. // Use the cached geometry if it exists
  2120. pending.push(cached.promise)
  2121. } else {
  2122. let geometryPromise
  2123. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  2124. // Use DRACO geometry if available
  2125. geometryPromise = createDracoPrimitive(primitive)
  2126. } else {
  2127. // Otherwise create a new geometry
  2128. geometryPromise = addPrimitiveAttributes(new THREE.BufferGeometry(), primitive, parser)
  2129. } // Cache this geometry
  2130. cache[cacheKey] = {
  2131. primitive: primitive,
  2132. promise: geometryPromise,
  2133. }
  2134. pending.push(geometryPromise)
  2135. }
  2136. }
  2137. return Promise.all(pending)
  2138. }
  2139. /**
  2140. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  2141. * @param {number} meshIndex
  2142. * @return {Promise<Group|Mesh|SkinnedMesh>}
  2143. */
  2144. loadMesh(meshIndex) {
  2145. const parser = this
  2146. const json = this.json
  2147. const extensions = this.extensions
  2148. const meshDef = json.meshes[meshIndex]
  2149. const primitives = meshDef.primitives
  2150. const pending = []
  2151. for (let i = 0, il = primitives.length; i < il; i++) {
  2152. const material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material)
  2153. pending.push(material)
  2154. }
  2155. pending.push(parser.loadGeometries(primitives))
  2156. return Promise.all(pending).then(function (results) {
  2157. const materials = results.slice(0, results.length - 1)
  2158. const geometries = results[results.length - 1]
  2159. const meshes = []
  2160. for (let i = 0, il = geometries.length; i < il; i++) {
  2161. const geometry = geometries[i]
  2162. const primitive = primitives[i] // 1. create THREE.Mesh
  2163. let mesh
  2164. const material = materials[i]
  2165. if (
  2166. primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  2167. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  2168. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  2169. primitive.mode === undefined
  2170. ) {
  2171. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  2172. mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh(geometry, material) : new THREE.Mesh(geometry, material)
  2173. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  2174. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  2175. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  2176. mesh.normalizeSkinWeights()
  2177. }
  2178. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  2179. mesh.geometry = toTrianglesDrawMode(mesh.geometry, THREE.TriangleStripDrawMode)
  2180. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  2181. mesh.geometry = toTrianglesDrawMode(mesh.geometry, THREE.TriangleFanDrawMode)
  2182. }
  2183. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  2184. mesh = new THREE.LineSegments(geometry, material)
  2185. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  2186. mesh = new THREE.Line(geometry, material)
  2187. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  2188. mesh = new THREE.LineLoop(geometry, material)
  2189. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  2190. mesh = new THREE.Points(geometry, material)
  2191. } else {
  2192. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode)
  2193. }
  2194. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  2195. updateMorphTargets(mesh, meshDef)
  2196. }
  2197. mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex)
  2198. assignExtrasToUserData(mesh, meshDef)
  2199. if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive)
  2200. parser.assignFinalMaterial(mesh)
  2201. meshes.push(mesh)
  2202. }
  2203. for (let i = 0, il = meshes.length; i < il; i++) {
  2204. parser.associations.set(meshes[i], {
  2205. meshes: meshIndex,
  2206. primitives: i,
  2207. })
  2208. }
  2209. if (meshes.length === 1) {
  2210. return meshes[0]
  2211. }
  2212. const group = new THREE.Group()
  2213. parser.associations.set(group, {
  2214. meshes: meshIndex,
  2215. })
  2216. for (let i = 0, il = meshes.length; i < il; i++) {
  2217. group.add(meshes[i])
  2218. }
  2219. return group
  2220. })
  2221. }
  2222. /**
  2223. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  2224. * @param {number} cameraIndex
  2225. * @return {Promise<THREE.Camera>}
  2226. */
  2227. loadCamera(cameraIndex) {
  2228. let camera
  2229. const cameraDef = this.json.cameras[cameraIndex]
  2230. const params = cameraDef[cameraDef.type]
  2231. if (!params) {
  2232. console.warn('THREE.GLTFLoader: Missing camera parameters.')
  2233. return
  2234. }
  2235. if (cameraDef.type === 'perspective') {
  2236. camera = new THREE.PerspectiveCamera(THREE.MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6)
  2237. } else if (cameraDef.type === 'orthographic') {
  2238. camera = new THREE.OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar)
  2239. }
  2240. if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name)
  2241. assignExtrasToUserData(camera, cameraDef)
  2242. return Promise.resolve(camera)
  2243. }
  2244. /**
  2245. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  2246. * @param {number} skinIndex
  2247. * @return {Promise<Object>}
  2248. */
  2249. loadSkin(skinIndex) {
  2250. const skinDef = this.json.skins[skinIndex]
  2251. const skinEntry = {
  2252. joints: skinDef.joints,
  2253. }
  2254. if (skinDef.inverseBindMatrices === undefined) {
  2255. return Promise.resolve(skinEntry)
  2256. }
  2257. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  2258. skinEntry.inverseBindMatrices = accessor
  2259. return skinEntry
  2260. })
  2261. }
  2262. /**
  2263. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  2264. * @param {number} animationIndex
  2265. * @return {Promise<AnimationClip>}
  2266. */
  2267. loadAnimation(animationIndex) {
  2268. const json = this.json
  2269. const animationDef = json.animations[animationIndex]
  2270. const pendingNodes = []
  2271. const pendingInputAccessors = []
  2272. const pendingOutputAccessors = []
  2273. const pendingSamplers = []
  2274. const pendingTargets = []
  2275. for (let i = 0, il = animationDef.channels.length; i < il; i++) {
  2276. const channel = animationDef.channels[i]
  2277. const sampler = animationDef.samplers[channel.sampler]
  2278. const target = channel.target
  2279. const name = target.node
  2280. const input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input
  2281. const output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output
  2282. pendingNodes.push(this.getDependency('node', name))
  2283. pendingInputAccessors.push(this.getDependency('accessor', input))
  2284. pendingOutputAccessors.push(this.getDependency('accessor', output))
  2285. pendingSamplers.push(sampler)
  2286. pendingTargets.push(target)
  2287. }
  2288. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(
  2289. function (dependencies) {
  2290. const nodes = dependencies[0]
  2291. const inputAccessors = dependencies[1]
  2292. const outputAccessors = dependencies[2]
  2293. const samplers = dependencies[3]
  2294. const targets = dependencies[4]
  2295. const tracks = []
  2296. for (let i = 0, il = nodes.length; i < il; i++) {
  2297. const node = nodes[i]
  2298. const inputAccessor = inputAccessors[i]
  2299. const outputAccessor = outputAccessors[i]
  2300. const sampler = samplers[i]
  2301. const target = targets[i]
  2302. if (node === undefined) continue
  2303. node.updateMatrix()
  2304. let TypedKeyframeTrack
  2305. switch (PATH_PROPERTIES[target.path]) {
  2306. case PATH_PROPERTIES.weights:
  2307. TypedKeyframeTrack = THREE.NumberKeyframeTrack
  2308. break
  2309. case PATH_PROPERTIES.rotation:
  2310. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack
  2311. break
  2312. case PATH_PROPERTIES.position:
  2313. case PATH_PROPERTIES.scale:
  2314. default:
  2315. TypedKeyframeTrack = THREE.VectorKeyframeTrack
  2316. break
  2317. }
  2318. const targetName = node.name ? node.name : node.uuid
  2319. const interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : THREE.InterpolateLinear
  2320. const targetNames = []
  2321. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  2322. node.traverse(function (object) {
  2323. if (object.morphTargetInfluences) {
  2324. targetNames.push(object.name ? object.name : object.uuid)
  2325. }
  2326. })
  2327. } else {
  2328. targetNames.push(targetName)
  2329. }
  2330. let outputArray = outputAccessor.array
  2331. if (outputAccessor.normalized) {
  2332. const scale = getNormalizedComponentScale(outputArray.constructor)
  2333. const scaled = new Float32Array(outputArray.length)
  2334. for (let j = 0, jl = outputArray.length; j < jl; j++) {
  2335. scaled[j] = outputArray[j] * scale
  2336. }
  2337. outputArray = scaled
  2338. }
  2339. for (let j = 0, jl = targetNames.length; j < jl; j++) {
  2340. const track = new TypedKeyframeTrack(targetNames[j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation) // Override interpolation with custom factory method.
  2341. if (sampler.interpolation === 'CUBICSPLINE') {
  2342. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  2343. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  2344. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  2345. // must be divided by three to get the interpolant's sampleSize argument.
  2346. const interpolantType = this instanceof THREE.QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant
  2347. return new interpolantType(this.times, this.values, this.getValueSize() / 3, result)
  2348. } // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  2349. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true
  2350. }
  2351. tracks.push(track)
  2352. }
  2353. }
  2354. const name = animationDef.name ? animationDef.name : 'animation_' + animationIndex
  2355. return new THREE.AnimationClip(name, undefined, tracks)
  2356. }
  2357. )
  2358. }
  2359. createNodeMesh(nodeIndex) {
  2360. const json = this.json
  2361. const parser = this
  2362. const nodeDef = json.nodes[nodeIndex]
  2363. if (nodeDef.mesh === undefined) return null
  2364. return parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  2365. const node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh) // if weights are provided on the node, override weights on the mesh.
  2366. if (nodeDef.weights !== undefined) {
  2367. node.traverse(function (o) {
  2368. if (!o.isMesh) return
  2369. for (let i = 0, il = nodeDef.weights.length; i < il; i++) {
  2370. o.morphTargetInfluences[i] = nodeDef.weights[i]
  2371. }
  2372. })
  2373. }
  2374. return node
  2375. })
  2376. }
  2377. /**
  2378. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  2379. * @param {number} nodeIndex
  2380. * @return {Promise<Object3D>}
  2381. */
  2382. loadNode(nodeIndex) {
  2383. const json = this.json
  2384. const extensions = this.extensions
  2385. const parser = this
  2386. const nodeDef = json.nodes[nodeIndex] // reserve node's name before its dependencies, so the root has the intended name.
  2387. const nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : ''
  2388. return (function () {
  2389. const pending = []
  2390. const meshPromise = parser._invokeOne(function (ext) {
  2391. return ext.createNodeMesh && ext.createNodeMesh(nodeIndex)
  2392. })
  2393. if (meshPromise) {
  2394. pending.push(meshPromise)
  2395. }
  2396. if (nodeDef.camera !== undefined) {
  2397. pending.push(
  2398. parser.getDependency('camera', nodeDef.camera).then(function (camera) {
  2399. return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera)
  2400. })
  2401. )
  2402. }
  2403. parser
  2404. ._invokeAll(function (ext) {
  2405. return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex)
  2406. })
  2407. .forEach(function (promise) {
  2408. pending.push(promise)
  2409. })
  2410. return Promise.all(pending)
  2411. })().then(function (objects) {
  2412. let node // .isBone isn't in glTF spec. See ._markDefs
  2413. if (nodeDef.isBone === true) {
  2414. node = new THREE.Bone()
  2415. } else if (objects.length > 1) {
  2416. node = new THREE.Group()
  2417. } else if (objects.length === 1) {
  2418. node = objects[0]
  2419. } else {
  2420. node = new THREE.Object3D()
  2421. }
  2422. if (node !== objects[0]) {
  2423. for (let i = 0, il = objects.length; i < il; i++) {
  2424. node.add(objects[i])
  2425. }
  2426. }
  2427. if (nodeDef.name) {
  2428. node.userData.name = nodeDef.name
  2429. node.name = nodeName
  2430. }
  2431. assignExtrasToUserData(node, nodeDef)
  2432. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef)
  2433. if (nodeDef.matrix !== undefined) {
  2434. const matrix = new THREE.Matrix4()
  2435. matrix.fromArray(nodeDef.matrix)
  2436. node.applyMatrix4(matrix)
  2437. } else {
  2438. if (nodeDef.translation !== undefined) {
  2439. node.position.fromArray(nodeDef.translation)
  2440. }
  2441. if (nodeDef.rotation !== undefined) {
  2442. node.quaternion.fromArray(nodeDef.rotation)
  2443. }
  2444. if (nodeDef.scale !== undefined) {
  2445. node.scale.fromArray(nodeDef.scale)
  2446. }
  2447. }
  2448. if (!parser.associations.has(node)) {
  2449. parser.associations.set(node, {})
  2450. }
  2451. parser.associations.get(node).nodes = nodeIndex
  2452. return node
  2453. })
  2454. }
  2455. /**
  2456. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  2457. * @param {number} sceneIndex
  2458. * @return {Promise<Group>}
  2459. */
  2460. loadScene(sceneIndex) {
  2461. const json = this.json
  2462. const extensions = this.extensions
  2463. const sceneDef = this.json.scenes[sceneIndex]
  2464. const parser = this // THREE.Loader returns THREE.Group, not Scene.
  2465. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  2466. const scene = new THREE.Group()
  2467. if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name)
  2468. assignExtrasToUserData(scene, sceneDef)
  2469. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef)
  2470. const nodeIds = sceneDef.nodes || []
  2471. const pending = []
  2472. for (let i = 0, il = nodeIds.length; i < il; i++) {
  2473. pending.push(buildNodeHierarchy(nodeIds[i], scene, json, parser))
  2474. }
  2475. return Promise.all(pending).then(function () {
  2476. // Removes dangling associations, associations that reference a node that
  2477. // didn't make it into the scene.
  2478. const reduceAssociations = node => {
  2479. const reducedAssociations = new Map()
  2480. for (const [key, value] of parser.associations) {
  2481. if (key instanceof THREE.Material || key instanceof THREE.Texture) {
  2482. reducedAssociations.set(key, value)
  2483. }
  2484. }
  2485. node.traverse(node => {
  2486. const mappings = parser.associations.get(node)
  2487. if (mappings != null) {
  2488. reducedAssociations.set(node, mappings)
  2489. }
  2490. })
  2491. return reducedAssociations
  2492. }
  2493. parser.associations = reduceAssociations(scene)
  2494. return scene
  2495. })
  2496. }
  2497. }
  2498. function buildNodeHierarchy(nodeId, parentObject, json, parser) {
  2499. const nodeDef = json.nodes[nodeId]
  2500. return parser
  2501. .getDependency('node', nodeId)
  2502. .then(function (node) {
  2503. if (nodeDef.skin === undefined) return node // build skeleton here as well
  2504. let skinEntry
  2505. return parser
  2506. .getDependency('skin', nodeDef.skin)
  2507. .then(function (skin) {
  2508. skinEntry = skin
  2509. const pendingJoints = []
  2510. for (let i = 0, il = skinEntry.joints.length; i < il; i++) {
  2511. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]))
  2512. }
  2513. return Promise.all(pendingJoints)
  2514. })
  2515. .then(function (jointNodes) {
  2516. node.traverse(function (mesh) {
  2517. if (!mesh.isMesh) return
  2518. const bones = []
  2519. const boneInverses = []
  2520. for (let j = 0, jl = jointNodes.length; j < jl; j++) {
  2521. const jointNode = jointNodes[j]
  2522. if (jointNode) {
  2523. bones.push(jointNode)
  2524. const mat = new THREE.Matrix4()
  2525. if (skinEntry.inverseBindMatrices !== undefined) {
  2526. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16)
  2527. }
  2528. boneInverses.push(mat)
  2529. } else {
  2530. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j])
  2531. }
  2532. }
  2533. mesh.bind(new THREE.Skeleton(bones, boneInverses), mesh.matrixWorld)
  2534. })
  2535. return node
  2536. })
  2537. })
  2538. .then(function (node) {
  2539. // build node hierachy
  2540. parentObject.add(node)
  2541. const pending = []
  2542. if (nodeDef.children) {
  2543. const children = nodeDef.children
  2544. for (let i = 0, il = children.length; i < il; i++) {
  2545. const child = children[i]
  2546. pending.push(buildNodeHierarchy(child, node, json, parser))
  2547. }
  2548. }
  2549. return Promise.all(pending)
  2550. })
  2551. }
  2552. /**
  2553. * @param {BufferGeometry} geometry
  2554. * @param {GLTF.Primitive} primitiveDef
  2555. * @param {GLTFParser} parser
  2556. */
  2557. function computeBounds(geometry, primitiveDef, parser) {
  2558. const attributes = primitiveDef.attributes
  2559. const box = new THREE.Box3()
  2560. if (attributes.POSITION !== undefined) {
  2561. const accessor = parser.json.accessors[attributes.POSITION]
  2562. const min = accessor.min
  2563. const max = accessor.max // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  2564. if (min !== undefined && max !== undefined) {
  2565. box.set(new THREE.Vector3(min[0], min[1], min[2]), new THREE.Vector3(max[0], max[1], max[2]))
  2566. if (accessor.normalized) {
  2567. const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType])
  2568. box.min.multiplyScalar(boxScale)
  2569. box.max.multiplyScalar(boxScale)
  2570. }
  2571. } else {
  2572. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.')
  2573. return
  2574. }
  2575. } else {
  2576. return
  2577. }
  2578. const targets = primitiveDef.targets
  2579. if (targets !== undefined) {
  2580. const maxDisplacement = new THREE.Vector3()
  2581. const vector = new THREE.Vector3()
  2582. for (let i = 0, il = targets.length; i < il; i++) {
  2583. const target = targets[i]
  2584. if (target.POSITION !== undefined) {
  2585. const accessor = parser.json.accessors[target.POSITION]
  2586. const min = accessor.min
  2587. const max = accessor.max // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  2588. if (min !== undefined && max !== undefined) {
  2589. // we need to get max of absolute components because target weight is [-1,1]
  2590. vector.setX(Math.max(Math.abs(min[0]), Math.abs(max[0])))
  2591. vector.setY(Math.max(Math.abs(min[1]), Math.abs(max[1])))
  2592. vector.setZ(Math.max(Math.abs(min[2]), Math.abs(max[2])))
  2593. if (accessor.normalized) {
  2594. const boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType])
  2595. vector.multiplyScalar(boxScale)
  2596. } // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  2597. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  2598. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  2599. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  2600. maxDisplacement.max(vector)
  2601. } else {
  2602. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.')
  2603. }
  2604. }
  2605. } // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  2606. box.expandByVector(maxDisplacement)
  2607. }
  2608. geometry.boundingBox = box
  2609. const sphere = new THREE.Sphere()
  2610. box.getCenter(sphere.center)
  2611. sphere.radius = box.min.distanceTo(box.max) / 2
  2612. geometry.boundingSphere = sphere
  2613. }
  2614. /**
  2615. * @param {BufferGeometry} geometry
  2616. * @param {GLTF.Primitive} primitiveDef
  2617. * @param {GLTFParser} parser
  2618. * @return {Promise<BufferGeometry>}
  2619. */
  2620. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  2621. const attributes = primitiveDef.attributes
  2622. const pending = []
  2623. function assignAttributeAccessor(accessorIndex, attributeName) {
  2624. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  2625. geometry.setAttribute(attributeName, accessor)
  2626. })
  2627. }
  2628. for (const gltfAttributeName in attributes) {
  2629. const threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase() // Skip attributes already provided by e.g. Draco extension.
  2630. if (threeAttributeName in geometry.attributes) continue
  2631. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName))
  2632. }
  2633. if (primitiveDef.indices !== undefined && !geometry.index) {
  2634. const accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  2635. geometry.setIndex(accessor)
  2636. })
  2637. pending.push(accessor)
  2638. }
  2639. assignExtrasToUserData(geometry, primitiveDef)
  2640. computeBounds(geometry, primitiveDef, parser)
  2641. return Promise.all(pending).then(function () {
  2642. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry
  2643. })
  2644. }
  2645. /**
  2646. * @param {BufferGeometry} geometry
  2647. * @param {Number} drawMode
  2648. * @return {BufferGeometry}
  2649. */
  2650. function toTrianglesDrawMode(geometry, drawMode) {
  2651. let index = geometry.getIndex() // generate index if not present
  2652. if (index === null) {
  2653. const indices = []
  2654. const position = geometry.getAttribute('position')
  2655. if (position !== undefined) {
  2656. for (let i = 0; i < position.count; i++) {
  2657. indices.push(i)
  2658. }
  2659. geometry.setIndex(indices)
  2660. index = geometry.getIndex()
  2661. } else {
  2662. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.')
  2663. return geometry
  2664. }
  2665. } //
  2666. const numberOfTriangles = index.count - 2
  2667. const newIndices = []
  2668. if (drawMode === THREE.TriangleFanDrawMode) {
  2669. // gl.TRIANGLE_FAN
  2670. for (let i = 1; i <= numberOfTriangles; i++) {
  2671. newIndices.push(index.getX(0))
  2672. newIndices.push(index.getX(i))
  2673. newIndices.push(index.getX(i + 1))
  2674. }
  2675. } else {
  2676. // gl.TRIANGLE_STRIP
  2677. for (let i = 0; i < numberOfTriangles; i++) {
  2678. if (i % 2 === 0) {
  2679. newIndices.push(index.getX(i))
  2680. newIndices.push(index.getX(i + 1))
  2681. newIndices.push(index.getX(i + 2))
  2682. } else {
  2683. newIndices.push(index.getX(i + 2))
  2684. newIndices.push(index.getX(i + 1))
  2685. newIndices.push(index.getX(i))
  2686. }
  2687. }
  2688. }
  2689. if (newIndices.length / 3 !== numberOfTriangles) {
  2690. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.')
  2691. } // build final geometry
  2692. const newGeometry = geometry.clone()
  2693. newGeometry.setIndex(newIndices)
  2694. return newGeometry
  2695. }
  2696. THREE.GLTFLoader = GLTFLoader
  2697. })()