GLTFLoader.js 121 KB

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