FBXLoader.js 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643
  1. import {
  2. AmbientLight,
  3. AnimationClip,
  4. Bone,
  5. BufferGeometry,
  6. ClampToEdgeWrapping,
  7. Color,
  8. DirectionalLight,
  9. EquirectangularReflectionMapping,
  10. Euler,
  11. FileLoader,
  12. Float32BufferAttribute,
  13. Group,
  14. Line,
  15. LineBasicMaterial,
  16. Loader,
  17. LoaderUtils,
  18. MathUtils,
  19. Matrix3,
  20. Matrix4,
  21. Mesh,
  22. MeshLambertMaterial,
  23. MeshPhongMaterial,
  24. NumberKeyframeTrack,
  25. Object3D,
  26. OrthographicCamera,
  27. PerspectiveCamera,
  28. PointLight,
  29. PropertyBinding,
  30. Quaternion,
  31. QuaternionKeyframeTrack,
  32. RepeatWrapping,
  33. Skeleton,
  34. SkinnedMesh,
  35. SpotLight,
  36. Texture,
  37. TextureLoader,
  38. Uint16BufferAttribute,
  39. Vector3,
  40. Vector4,
  41. VectorKeyframeTrack,
  42. SRGBColorSpace,
  43. } from "three";
  44. import * as fflate from "../public/libs/fflate.module";
  45. import { NURBSCurve } from "../public/curves/NURBSCurve.js";
  46. /**
  47. * Loader loads FBX file and generates Group representing FBX scene.
  48. * Requires FBX file to be >= 7.0 and in ASCII or >= 6400 in Binary format
  49. * Versions lower than this may load but will probably have errors
  50. *
  51. * Needs Support:
  52. * Morph normals / blend shape normals
  53. *
  54. * FBX format references:
  55. * https://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_index_html (C++ SDK reference)
  56. *
  57. * Binary format specification:
  58. * https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  59. */
  60. let fbxTree;
  61. let connections;
  62. let sceneGraph;
  63. class FBXLoader extends Loader {
  64. constructor(manager) {
  65. super(manager);
  66. }
  67. load(url, onLoad, onProgress, onError) {
  68. const scope = this;
  69. const path =
  70. scope.path === "" ? LoaderUtils.extractUrlBase(url) : scope.path;
  71. const loader = new FileLoader(this.manager);
  72. loader.setPath(scope.path);
  73. loader.setResponseType("arraybuffer");
  74. loader.setRequestHeader(scope.requestHeader);
  75. loader.setWithCredentials(scope.withCredentials);
  76. loader.load(
  77. url,
  78. function (buffer) {
  79. try {
  80. onLoad(scope.parse(buffer, path));
  81. } catch (e) {
  82. if (onError) {
  83. onError(e);
  84. } else {
  85. console.error(e);
  86. }
  87. scope.manager.itemError(url);
  88. }
  89. },
  90. onProgress,
  91. onError
  92. );
  93. }
  94. parse(FBXBuffer, path) {
  95. if (isFbxFormatBinary(FBXBuffer)) {
  96. fbxTree = new BinaryParser().parse(FBXBuffer);
  97. } else {
  98. const FBXText = convertArrayBufferToString(FBXBuffer);
  99. if (!isFbxFormatASCII(FBXText)) {
  100. throw new Error("THREE.FBXLoader: Unknown format.");
  101. }
  102. if (getFbxVersion(FBXText) < 7000) {
  103. throw new Error(
  104. "THREE.FBXLoader: FBX version not supported, FileVersion: " +
  105. getFbxVersion(FBXText)
  106. );
  107. }
  108. fbxTree = new TextParser().parse(FBXText);
  109. }
  110. // console.log( fbxTree );
  111. const textureLoader = new TextureLoader(this.manager)
  112. .setPath(this.resourcePath || path)
  113. .setCrossOrigin(this.crossOrigin);
  114. return new FBXTreeParser(textureLoader, this.manager).parse(fbxTree);
  115. }
  116. }
  117. // Parse the FBXTree object returned by the BinaryParser or TextParser and return a Group
  118. class FBXTreeParser {
  119. constructor(textureLoader, manager) {
  120. this.textureLoader = textureLoader;
  121. this.manager = manager;
  122. }
  123. parse() {
  124. connections = this.parseConnections();
  125. const images = this.parseImages();
  126. const textures = this.parseTextures(images);
  127. const materials = this.parseMaterials(textures);
  128. const deformers = this.parseDeformers();
  129. const geometryMap = new GeometryParser().parse(deformers);
  130. this.parseScene(deformers, geometryMap, materials);
  131. return sceneGraph;
  132. }
  133. // Parses FBXTree.Connections which holds parent-child connections between objects (e.g. material -> texture, model->geometry )
  134. // and details the connection type
  135. parseConnections() {
  136. const connectionMap = new Map();
  137. if ("Connections" in fbxTree) {
  138. const rawConnections = fbxTree.Connections.connections;
  139. rawConnections.forEach(function (rawConnection) {
  140. const fromID = rawConnection[0];
  141. const toID = rawConnection[1];
  142. const relationship = rawConnection[2];
  143. if (!connectionMap.has(fromID)) {
  144. connectionMap.set(fromID, {
  145. parents: [],
  146. children: [],
  147. });
  148. }
  149. const parentRelationship = { ID: toID, relationship: relationship };
  150. connectionMap.get(fromID).parents.push(parentRelationship);
  151. if (!connectionMap.has(toID)) {
  152. connectionMap.set(toID, {
  153. parents: [],
  154. children: [],
  155. });
  156. }
  157. const childRelationship = { ID: fromID, relationship: relationship };
  158. connectionMap.get(toID).children.push(childRelationship);
  159. });
  160. }
  161. return connectionMap;
  162. }
  163. // Parse FBXTree.Objects.Video for embedded image data
  164. // These images are connected to textures in FBXTree.Objects.Textures
  165. // via FBXTree.Connections.
  166. parseImages() {
  167. const images = {};
  168. const blobs = {};
  169. if ("Video" in fbxTree.Objects) {
  170. const videoNodes = fbxTree.Objects.Video;
  171. for (const nodeID in videoNodes) {
  172. const videoNode = videoNodes[nodeID];
  173. const id = parseInt(nodeID);
  174. images[id] = videoNode.RelativeFilename || videoNode.Filename;
  175. // raw image data is in videoNode.Content
  176. if ("Content" in videoNode) {
  177. const arrayBufferContent =
  178. videoNode.Content instanceof ArrayBuffer &&
  179. videoNode.Content.byteLength > 0;
  180. const base64Content =
  181. typeof videoNode.Content === "string" && videoNode.Content !== "";
  182. if (arrayBufferContent || base64Content) {
  183. const image = this.parseImage(videoNodes[nodeID]);
  184. blobs[videoNode.RelativeFilename || videoNode.Filename] = image;
  185. }
  186. }
  187. }
  188. }
  189. for (const id in images) {
  190. const filename = images[id];
  191. if (blobs[filename] !== undefined) images[id] = blobs[filename];
  192. else images[id] = images[id].split("\\").pop();
  193. }
  194. return images;
  195. }
  196. // Parse embedded image data in FBXTree.Video.Content
  197. parseImage(videoNode) {
  198. const content = videoNode.Content;
  199. const fileName = videoNode.RelativeFilename || videoNode.Filename;
  200. const extension = fileName
  201. .slice(fileName.lastIndexOf(".") + 1)
  202. .toLowerCase();
  203. let type;
  204. switch (extension) {
  205. case "bmp":
  206. type = "image/bmp";
  207. break;
  208. case "jpg":
  209. case "jpeg":
  210. type = "image/jpeg";
  211. break;
  212. case "png":
  213. type = "image/png";
  214. break;
  215. case "tif":
  216. type = "image/tiff";
  217. break;
  218. case "tga":
  219. if (this.manager.getHandler(".tga") === null) {
  220. console.warn("FBXLoader: TGA loader not found, skipping ", fileName);
  221. }
  222. type = "image/tga";
  223. break;
  224. default:
  225. console.warn(
  226. 'FBXLoader: Image type "' + extension + '" is not supported.'
  227. );
  228. return;
  229. }
  230. if (typeof content === "string") {
  231. // ASCII format
  232. return "data:" + type + ";base64," + content;
  233. } else {
  234. // Binary Format
  235. const array = new Uint8Array(content);
  236. return window.URL.createObjectURL(new Blob([array], { type: type }));
  237. }
  238. }
  239. // Parse nodes in FBXTree.Objects.Texture
  240. // These contain details such as UV scaling, cropping, rotation etc and are connected
  241. // to images in FBXTree.Objects.Video
  242. parseTextures(images) {
  243. const textureMap = new Map();
  244. if ("Texture" in fbxTree.Objects) {
  245. const textureNodes = fbxTree.Objects.Texture;
  246. for (const nodeID in textureNodes) {
  247. const texture = this.parseTexture(textureNodes[nodeID], images);
  248. textureMap.set(parseInt(nodeID), texture);
  249. }
  250. }
  251. return textureMap;
  252. }
  253. // Parse individual node in FBXTree.Objects.Texture
  254. parseTexture(textureNode, images) {
  255. const texture = this.loadTexture(textureNode, images);
  256. texture.ID = textureNode.id;
  257. texture.name = textureNode.attrName;
  258. const wrapModeU = textureNode.WrapModeU;
  259. const wrapModeV = textureNode.WrapModeV;
  260. const valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  261. const valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  262. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  263. // 0: repeat(default), 1: clamp
  264. texture.wrapS = valueU === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  265. texture.wrapT = valueV === 0 ? RepeatWrapping : ClampToEdgeWrapping;
  266. if ("Scaling" in textureNode) {
  267. const values = textureNode.Scaling.value;
  268. texture.repeat.x = values[0];
  269. texture.repeat.y = values[1];
  270. }
  271. if ("Translation" in textureNode) {
  272. const values = textureNode.Translation.value;
  273. texture.offset.x = values[0];
  274. texture.offset.y = values[1];
  275. }
  276. return texture;
  277. }
  278. // load a texture specified as a blob or data URI, or via an external URL using TextureLoader
  279. loadTexture(textureNode, images) {
  280. let fileName;
  281. const currentPath = this.textureLoader.path;
  282. const children = connections.get(textureNode.id).children;
  283. if (
  284. children !== undefined &&
  285. children.length > 0 &&
  286. images[children[0].ID] !== undefined
  287. ) {
  288. fileName = images[children[0].ID];
  289. if (fileName.indexOf("blob:") === 0 || fileName.indexOf("data:") === 0) {
  290. this.textureLoader.setPath(undefined);
  291. }
  292. }
  293. let texture;
  294. const extension = textureNode.FileName.slice(-3).toLowerCase();
  295. if (extension === "tga") {
  296. const loader = this.manager.getHandler(".tga");
  297. if (loader === null) {
  298. console.warn(
  299. "FBXLoader: TGA loader not found, creating placeholder texture for",
  300. textureNode.RelativeFilename
  301. );
  302. texture = new Texture();
  303. } else {
  304. loader.setPath(this.textureLoader.path);
  305. texture = loader.load(fileName);
  306. }
  307. } else if (extension === "psd") {
  308. console.warn(
  309. "FBXLoader: PSD textures are not supported, creating placeholder texture for",
  310. textureNode.RelativeFilename
  311. );
  312. texture = new Texture();
  313. } else {
  314. texture = this.textureLoader.load(fileName);
  315. }
  316. this.textureLoader.setPath(currentPath);
  317. return texture;
  318. }
  319. // Parse nodes in FBXTree.Objects.Material
  320. parseMaterials(textureMap) {
  321. const materialMap = new Map();
  322. if ("Material" in fbxTree.Objects) {
  323. const materialNodes = fbxTree.Objects.Material;
  324. for (const nodeID in materialNodes) {
  325. const material = this.parseMaterial(materialNodes[nodeID], textureMap);
  326. if (material !== null) materialMap.set(parseInt(nodeID), material);
  327. }
  328. }
  329. return materialMap;
  330. }
  331. // Parse single node in FBXTree.Objects.Material
  332. // Materials are connected to texture maps in FBXTree.Objects.Textures
  333. // FBX format currently only supports Lambert and Phong shading models
  334. parseMaterial(materialNode, textureMap) {
  335. const ID = materialNode.id;
  336. const name = materialNode.attrName;
  337. let type = materialNode.ShadingModel;
  338. // Case where FBX wraps shading model in property object.
  339. if (typeof type === "object") {
  340. type = type.value;
  341. }
  342. // Ignore unused materials which don't have any connections.
  343. if (!connections.has(ID)) return null;
  344. const parameters = this.parseParameters(materialNode, textureMap, ID);
  345. let material;
  346. switch (type.toLowerCase()) {
  347. case "phong":
  348. material = new MeshPhongMaterial();
  349. break;
  350. case "lambert":
  351. material = new MeshLambertMaterial();
  352. break;
  353. default:
  354. console.warn(
  355. 'THREE.FBXLoader: unknown material type "%s". Defaulting to MeshPhongMaterial.',
  356. type
  357. );
  358. material = new MeshPhongMaterial();
  359. break;
  360. }
  361. material.setValues(parameters);
  362. material.name = name;
  363. return material;
  364. }
  365. // Parse FBX material and return parameters suitable for a three.js material
  366. // Also parse the texture map and return any textures associated with the material
  367. parseParameters(materialNode, textureMap, ID) {
  368. const parameters = {};
  369. if (materialNode.BumpFactor) {
  370. parameters.bumpScale = materialNode.BumpFactor.value;
  371. }
  372. if (materialNode.Diffuse) {
  373. parameters.color = new Color()
  374. .fromArray(materialNode.Diffuse.value)
  375. .convertSRGBToLinear();
  376. } else if (
  377. materialNode.DiffuseColor &&
  378. (materialNode.DiffuseColor.type === "Color" ||
  379. materialNode.DiffuseColor.type === "ColorRGB")
  380. ) {
  381. // The blender exporter exports diffuse here instead of in materialNode.Diffuse
  382. parameters.color = new Color()
  383. .fromArray(materialNode.DiffuseColor.value)
  384. .convertSRGBToLinear();
  385. }
  386. if (materialNode.DisplacementFactor) {
  387. parameters.displacementScale = materialNode.DisplacementFactor.value;
  388. }
  389. if (materialNode.Emissive) {
  390. parameters.emissive = new Color()
  391. .fromArray(materialNode.Emissive.value)
  392. .convertSRGBToLinear();
  393. } else if (
  394. materialNode.EmissiveColor &&
  395. (materialNode.EmissiveColor.type === "Color" ||
  396. materialNode.EmissiveColor.type === "ColorRGB")
  397. ) {
  398. // The blender exporter exports emissive color here instead of in materialNode.Emissive
  399. parameters.emissive = new Color()
  400. .fromArray(materialNode.EmissiveColor.value)
  401. .convertSRGBToLinear();
  402. }
  403. if (materialNode.EmissiveFactor) {
  404. parameters.emissiveIntensity = parseFloat(
  405. materialNode.EmissiveFactor.value
  406. );
  407. }
  408. if (materialNode.Opacity) {
  409. parameters.opacity = parseFloat(materialNode.Opacity.value);
  410. }
  411. if (parameters.opacity < 1.0) {
  412. parameters.transparent = true;
  413. }
  414. if (materialNode.ReflectionFactor) {
  415. parameters.reflectivity = materialNode.ReflectionFactor.value;
  416. }
  417. if (materialNode.Shininess) {
  418. parameters.shininess = materialNode.Shininess.value;
  419. }
  420. if (materialNode.Specular) {
  421. parameters.specular = new Color()
  422. .fromArray(materialNode.Specular.value)
  423. .convertSRGBToLinear();
  424. } else if (
  425. materialNode.SpecularColor &&
  426. materialNode.SpecularColor.type === "Color"
  427. ) {
  428. // The blender exporter exports specular color here instead of in materialNode.Specular
  429. parameters.specular = new Color()
  430. .fromArray(materialNode.SpecularColor.value)
  431. .convertSRGBToLinear();
  432. }
  433. const scope = this;
  434. connections.get(ID).children.forEach(function (child) {
  435. const type = child.relationship;
  436. switch (type) {
  437. case "Bump":
  438. parameters.bumpMap = scope.getTexture(textureMap, child.ID);
  439. break;
  440. case "Maya|TEX_ao_map":
  441. parameters.aoMap = scope.getTexture(textureMap, child.ID);
  442. break;
  443. case "DiffuseColor":
  444. case "Maya|TEX_color_map":
  445. parameters.map = scope.getTexture(textureMap, child.ID);
  446. if (parameters.map !== undefined) {
  447. parameters.map.colorSpace = SRGBColorSpace;
  448. }
  449. break;
  450. case "DisplacementColor":
  451. parameters.displacementMap = scope.getTexture(textureMap, child.ID);
  452. break;
  453. case "EmissiveColor":
  454. parameters.emissiveMap = scope.getTexture(textureMap, child.ID);
  455. if (parameters.emissiveMap !== undefined) {
  456. parameters.emissiveMap.colorSpace = SRGBColorSpace;
  457. }
  458. break;
  459. case "NormalMap":
  460. case "Maya|TEX_normal_map":
  461. parameters.normalMap = scope.getTexture(textureMap, child.ID);
  462. break;
  463. case "ReflectionColor":
  464. parameters.envMap = scope.getTexture(textureMap, child.ID);
  465. if (parameters.envMap !== undefined) {
  466. parameters.envMap.mapping = EquirectangularReflectionMapping;
  467. parameters.envMap.colorSpace = SRGBColorSpace;
  468. }
  469. break;
  470. case "SpecularColor":
  471. parameters.specularMap = scope.getTexture(textureMap, child.ID);
  472. if (parameters.specularMap !== undefined) {
  473. parameters.specularMap.colorSpace = SRGBColorSpace;
  474. }
  475. break;
  476. case "TransparentColor":
  477. case "TransparencyFactor":
  478. parameters.alphaMap = scope.getTexture(textureMap, child.ID);
  479. parameters.transparent = true;
  480. break;
  481. case "AmbientColor":
  482. case "ShininessExponent": // AKA glossiness map
  483. case "SpecularFactor": // AKA specularLevel
  484. case "VectorDisplacementColor": // NOTE: Seems to be a copy of DisplacementColor
  485. default:
  486. console.warn(
  487. "THREE.FBXLoader: %s map is not supported in three.js, skipping texture.",
  488. type
  489. );
  490. break;
  491. }
  492. });
  493. return parameters;
  494. }
  495. // get a texture from the textureMap for use by a material.
  496. getTexture(textureMap, id) {
  497. // if the texture is a layered texture, just use the first layer and issue a warning
  498. if (
  499. "LayeredTexture" in fbxTree.Objects &&
  500. id in fbxTree.Objects.LayeredTexture
  501. ) {
  502. console.warn(
  503. "THREE.FBXLoader: layered textures are not supported in three.js. Discarding all but first layer."
  504. );
  505. id = connections.get(id).children[0].ID;
  506. }
  507. return textureMap.get(id);
  508. }
  509. // Parse nodes in FBXTree.Objects.Deformer
  510. // Deformer node can contain skinning or Vertex Cache animation data, however only skinning is supported here
  511. // Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  512. parseDeformers() {
  513. const skeletons = {};
  514. const morphTargets = {};
  515. if ("Deformer" in fbxTree.Objects) {
  516. const DeformerNodes = fbxTree.Objects.Deformer;
  517. for (const nodeID in DeformerNodes) {
  518. const deformerNode = DeformerNodes[nodeID];
  519. const relationships = connections.get(parseInt(nodeID));
  520. if (deformerNode.attrType === "Skin") {
  521. const skeleton = this.parseSkeleton(relationships, DeformerNodes);
  522. skeleton.ID = nodeID;
  523. if (relationships.parents.length > 1)
  524. console.warn(
  525. "THREE.FBXLoader: skeleton attached to more than one geometry is not supported."
  526. );
  527. skeleton.geometryID = relationships.parents[0].ID;
  528. skeletons[nodeID] = skeleton;
  529. } else if (deformerNode.attrType === "BlendShape") {
  530. const morphTarget = {
  531. id: nodeID,
  532. };
  533. morphTarget.rawTargets = this.parseMorphTargets(
  534. relationships,
  535. DeformerNodes
  536. );
  537. morphTarget.id = nodeID;
  538. if (relationships.parents.length > 1)
  539. console.warn(
  540. "THREE.FBXLoader: morph target attached to more than one geometry is not supported."
  541. );
  542. morphTargets[nodeID] = morphTarget;
  543. }
  544. }
  545. }
  546. return {
  547. skeletons: skeletons,
  548. morphTargets: morphTargets,
  549. };
  550. }
  551. // Parse single nodes in FBXTree.Objects.Deformer
  552. // The top level skeleton node has type 'Skin' and sub nodes have type 'Cluster'
  553. // Each skin node represents a skeleton and each cluster node represents a bone
  554. parseSkeleton(relationships, deformerNodes) {
  555. const rawBones = [];
  556. relationships.children.forEach(function (child) {
  557. const boneNode = deformerNodes[child.ID];
  558. if (boneNode.attrType !== "Cluster") return;
  559. const rawBone = {
  560. ID: child.ID,
  561. indices: [],
  562. weights: [],
  563. transformLink: new Matrix4().fromArray(boneNode.TransformLink.a),
  564. // transform: new Matrix4().fromArray( boneNode.Transform.a ),
  565. // linkMode: boneNode.Mode,
  566. };
  567. if ("Indexes" in boneNode) {
  568. rawBone.indices = boneNode.Indexes.a;
  569. rawBone.weights = boneNode.Weights.a;
  570. }
  571. rawBones.push(rawBone);
  572. });
  573. return {
  574. rawBones: rawBones,
  575. bones: [],
  576. };
  577. }
  578. // The top level morph deformer node has type "BlendShape" and sub nodes have type "BlendShapeChannel"
  579. parseMorphTargets(relationships, deformerNodes) {
  580. const rawMorphTargets = [];
  581. for (let i = 0; i < relationships.children.length; i++) {
  582. const child = relationships.children[i];
  583. const morphTargetNode = deformerNodes[child.ID];
  584. const rawMorphTarget = {
  585. name: morphTargetNode.attrName,
  586. initialWeight: morphTargetNode.DeformPercent,
  587. id: morphTargetNode.id,
  588. fullWeights: morphTargetNode.FullWeights.a,
  589. };
  590. if (morphTargetNode.attrType !== "BlendShapeChannel") return;
  591. rawMorphTarget.geoID = connections
  592. .get(parseInt(child.ID))
  593. .children.filter(function (child) {
  594. return child.relationship === undefined;
  595. })[0].ID;
  596. rawMorphTargets.push(rawMorphTarget);
  597. }
  598. return rawMorphTargets;
  599. }
  600. // create the main Group() to be returned by the loader
  601. parseScene(deformers, geometryMap, materialMap) {
  602. sceneGraph = new Group();
  603. const modelMap = this.parseModels(
  604. deformers.skeletons,
  605. geometryMap,
  606. materialMap
  607. );
  608. const modelNodes = fbxTree.Objects.Model;
  609. const scope = this;
  610. modelMap.forEach(function (model) {
  611. const modelNode = modelNodes[model.ID];
  612. scope.setLookAtProperties(model, modelNode);
  613. const parentConnections = connections.get(model.ID).parents;
  614. parentConnections.forEach(function (connection) {
  615. const parent = modelMap.get(connection.ID);
  616. if (parent !== undefined) parent.add(model);
  617. });
  618. if (model.parent === null) {
  619. sceneGraph.add(model);
  620. }
  621. });
  622. this.bindSkeleton(deformers.skeletons, geometryMap, modelMap);
  623. this.createAmbientLight();
  624. sceneGraph.traverse(function (node) {
  625. if (node.userData.transformData) {
  626. if (node.parent) {
  627. node.userData.transformData.parentMatrix = node.parent.matrix;
  628. node.userData.transformData.parentMatrixWorld =
  629. node.parent.matrixWorld;
  630. }
  631. const transform = generateTransform(node.userData.transformData);
  632. node.applyMatrix4(transform);
  633. node.updateWorldMatrix();
  634. }
  635. });
  636. const animations = new AnimationParser().parse();
  637. // if all the models where already combined in a single group, just return that
  638. if (sceneGraph.children.length === 1 && sceneGraph.children[0].isGroup) {
  639. sceneGraph.children[0].animations = animations;
  640. sceneGraph = sceneGraph.children[0];
  641. }
  642. sceneGraph.animations = animations;
  643. }
  644. // parse nodes in FBXTree.Objects.Model
  645. parseModels(skeletons, geometryMap, materialMap) {
  646. const modelMap = new Map();
  647. const modelNodes = fbxTree.Objects.Model;
  648. for (const nodeID in modelNodes) {
  649. const id = parseInt(nodeID);
  650. const node = modelNodes[nodeID];
  651. const relationships = connections.get(id);
  652. let model = this.buildSkeleton(
  653. relationships,
  654. skeletons,
  655. id,
  656. node.attrName
  657. );
  658. if (!model) {
  659. switch (node.attrType) {
  660. case "Camera":
  661. model = this.createCamera(relationships);
  662. break;
  663. case "Light":
  664. model = this.createLight(relationships);
  665. break;
  666. case "Mesh":
  667. model = this.createMesh(relationships, geometryMap, materialMap);
  668. break;
  669. case "NurbsCurve":
  670. model = this.createCurve(relationships, geometryMap);
  671. break;
  672. case "LimbNode":
  673. case "Root":
  674. model = new Bone();
  675. break;
  676. case "Null":
  677. default:
  678. model = new Group();
  679. break;
  680. }
  681. model.name = node.attrName
  682. ? PropertyBinding.sanitizeNodeName(node.attrName)
  683. : "";
  684. model.ID = id;
  685. }
  686. this.getTransformData(model, node);
  687. modelMap.set(id, model);
  688. }
  689. return modelMap;
  690. }
  691. buildSkeleton(relationships, skeletons, id, name) {
  692. let bone = null;
  693. relationships.parents.forEach(function (parent) {
  694. for (const ID in skeletons) {
  695. const skeleton = skeletons[ID];
  696. skeleton.rawBones.forEach(function (rawBone, i) {
  697. if (rawBone.ID === parent.ID) {
  698. const subBone = bone;
  699. bone = new Bone();
  700. bone.matrixWorld.copy(rawBone.transformLink);
  701. // set name and id here - otherwise in cases where "subBone" is created it will not have a name / id
  702. bone.name = name ? PropertyBinding.sanitizeNodeName(name) : "";
  703. bone.ID = id;
  704. skeleton.bones[i] = bone;
  705. // In cases where a bone is shared between multiple meshes
  706. // duplicate the bone here and and it as a child of the first bone
  707. if (subBone !== null) {
  708. bone.add(subBone);
  709. }
  710. }
  711. });
  712. }
  713. });
  714. return bone;
  715. }
  716. // create a PerspectiveCamera or OrthographicCamera
  717. createCamera(relationships) {
  718. let model;
  719. let cameraAttribute;
  720. relationships.children.forEach(function (child) {
  721. const attr = fbxTree.Objects.NodeAttribute[child.ID];
  722. if (attr !== undefined) {
  723. cameraAttribute = attr;
  724. }
  725. });
  726. if (cameraAttribute === undefined) {
  727. model = new Object3D();
  728. } else {
  729. let type = 0;
  730. if (
  731. cameraAttribute.CameraProjectionType !== undefined &&
  732. cameraAttribute.CameraProjectionType.value === 1
  733. ) {
  734. type = 1;
  735. }
  736. let nearClippingPlane = 1;
  737. if (cameraAttribute.NearPlane !== undefined) {
  738. nearClippingPlane = cameraAttribute.NearPlane.value / 1000;
  739. }
  740. let farClippingPlane = 1000;
  741. if (cameraAttribute.FarPlane !== undefined) {
  742. farClippingPlane = cameraAttribute.FarPlane.value / 1000;
  743. }
  744. let width = window.innerWidth;
  745. let height = window.innerHeight;
  746. if (
  747. cameraAttribute.AspectWidth !== undefined &&
  748. cameraAttribute.AspectHeight !== undefined
  749. ) {
  750. width = cameraAttribute.AspectWidth.value;
  751. height = cameraAttribute.AspectHeight.value;
  752. }
  753. const aspect = width / height;
  754. let fov = 45;
  755. if (cameraAttribute.FieldOfView !== undefined) {
  756. fov = cameraAttribute.FieldOfView.value;
  757. }
  758. const focalLength = cameraAttribute.FocalLength
  759. ? cameraAttribute.FocalLength.value
  760. : null;
  761. switch (type) {
  762. case 0: // Perspective
  763. model = new PerspectiveCamera(
  764. fov,
  765. aspect,
  766. nearClippingPlane,
  767. farClippingPlane
  768. );
  769. if (focalLength !== null) model.setFocalLength(focalLength);
  770. break;
  771. case 1: // Orthographic
  772. model = new OrthographicCamera(
  773. -width / 2,
  774. width / 2,
  775. height / 2,
  776. -height / 2,
  777. nearClippingPlane,
  778. farClippingPlane
  779. );
  780. break;
  781. default:
  782. console.warn("THREE.FBXLoader: Unknown camera type " + type + ".");
  783. model = new Object3D();
  784. break;
  785. }
  786. }
  787. return model;
  788. }
  789. // Create a DirectionalLight, PointLight or SpotLight
  790. createLight(relationships) {
  791. let model;
  792. let lightAttribute;
  793. relationships.children.forEach(function (child) {
  794. const attr = fbxTree.Objects.NodeAttribute[child.ID];
  795. if (attr !== undefined) {
  796. lightAttribute = attr;
  797. }
  798. });
  799. if (lightAttribute === undefined) {
  800. model = new Object3D();
  801. } else {
  802. let type;
  803. // LightType can be undefined for Point lights
  804. if (lightAttribute.LightType === undefined) {
  805. type = 0;
  806. } else {
  807. type = lightAttribute.LightType.value;
  808. }
  809. let color = 0xffffff;
  810. if (lightAttribute.Color !== undefined) {
  811. color = new Color()
  812. .fromArray(lightAttribute.Color.value)
  813. .convertSRGBToLinear();
  814. }
  815. let intensity =
  816. lightAttribute.Intensity === undefined
  817. ? 1
  818. : lightAttribute.Intensity.value / 100;
  819. // light disabled
  820. if (
  821. lightAttribute.CastLightOnObject !== undefined &&
  822. lightAttribute.CastLightOnObject.value === 0
  823. ) {
  824. intensity = 0;
  825. }
  826. let distance = 0;
  827. if (lightAttribute.FarAttenuationEnd !== undefined) {
  828. if (
  829. lightAttribute.EnableFarAttenuation !== undefined &&
  830. lightAttribute.EnableFarAttenuation.value === 0
  831. ) {
  832. distance = 0;
  833. } else {
  834. distance = lightAttribute.FarAttenuationEnd.value;
  835. }
  836. }
  837. // TODO: could this be calculated linearly from FarAttenuationStart to FarAttenuationEnd?
  838. const decay = 1;
  839. switch (type) {
  840. case 0: // Point
  841. model = new PointLight(color, intensity, distance, decay);
  842. break;
  843. case 1: // Directional
  844. model = new DirectionalLight(color, intensity);
  845. break;
  846. case 2: // Spot
  847. let angle = Math.PI / 3;
  848. if (lightAttribute.InnerAngle !== undefined) {
  849. angle = MathUtils.degToRad(lightAttribute.InnerAngle.value);
  850. }
  851. let penumbra = 0;
  852. if (lightAttribute.OuterAngle !== undefined) {
  853. // TODO: this is not correct - FBX calculates outer and inner angle in degrees
  854. // with OuterAngle > InnerAngle && OuterAngle <= Math.PI
  855. // while three.js uses a penumbra between (0, 1) to attenuate the inner angle
  856. penumbra = MathUtils.degToRad(lightAttribute.OuterAngle.value);
  857. penumbra = Math.max(penumbra, 1);
  858. }
  859. model = new SpotLight(
  860. color,
  861. intensity,
  862. distance,
  863. angle,
  864. penumbra,
  865. decay
  866. );
  867. break;
  868. default:
  869. console.warn(
  870. "THREE.FBXLoader: Unknown light type " +
  871. lightAttribute.LightType.value +
  872. ", defaulting to a PointLight."
  873. );
  874. model = new PointLight(color, intensity);
  875. break;
  876. }
  877. if (
  878. lightAttribute.CastShadows !== undefined &&
  879. lightAttribute.CastShadows.value === 1
  880. ) {
  881. model.castShadow = true;
  882. }
  883. }
  884. return model;
  885. }
  886. createMesh(relationships, geometryMap, materialMap) {
  887. let model;
  888. let geometry = null;
  889. let material = null;
  890. const materials = [];
  891. // get geometry and materials(s) from connections
  892. relationships.children.forEach(function (child) {
  893. if (geometryMap.has(child.ID)) {
  894. geometry = geometryMap.get(child.ID);
  895. }
  896. if (materialMap.has(child.ID)) {
  897. materials.push(materialMap.get(child.ID));
  898. }
  899. });
  900. if (materials.length > 1) {
  901. material = materials;
  902. } else if (materials.length > 0) {
  903. material = materials[0];
  904. } else {
  905. material = new MeshPhongMaterial({
  906. name: Loader.DEFAULT_MATERIAL_NAME,
  907. color: 0xcccccc,
  908. });
  909. materials.push(material);
  910. }
  911. if ("color" in geometry.attributes) {
  912. materials.forEach(function (material) {
  913. material.vertexColors = true;
  914. });
  915. }
  916. if (geometry.FBX_Deformer) {
  917. model = new SkinnedMesh(geometry, material);
  918. model.normalizeSkinWeights();
  919. } else {
  920. model = new Mesh(geometry, material);
  921. }
  922. return model;
  923. }
  924. createCurve(relationships, geometryMap) {
  925. const geometry = relationships.children.reduce(function (geo, child) {
  926. if (geometryMap.has(child.ID)) geo = geometryMap.get(child.ID);
  927. return geo;
  928. }, null);
  929. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  930. const material = new LineBasicMaterial({
  931. name: Loader.DEFAULT_MATERIAL_NAME,
  932. color: 0x3300ff,
  933. linewidth: 1,
  934. });
  935. return new Line(geometry, material);
  936. }
  937. // parse the model node for transform data
  938. getTransformData(model, modelNode) {
  939. const transformData = {};
  940. if ("InheritType" in modelNode)
  941. transformData.inheritType = parseInt(modelNode.InheritType.value);
  942. if ("RotationOrder" in modelNode)
  943. transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value);
  944. else transformData.eulerOrder = "ZYX";
  945. if ("Lcl_Translation" in modelNode)
  946. transformData.translation = modelNode.Lcl_Translation.value;
  947. if ("PreRotation" in modelNode)
  948. transformData.preRotation = modelNode.PreRotation.value;
  949. if ("Lcl_Rotation" in modelNode)
  950. transformData.rotation = modelNode.Lcl_Rotation.value;
  951. if ("PostRotation" in modelNode)
  952. transformData.postRotation = modelNode.PostRotation.value;
  953. if ("Lcl_Scaling" in modelNode)
  954. transformData.scale = modelNode.Lcl_Scaling.value;
  955. if ("ScalingOffset" in modelNode)
  956. transformData.scalingOffset = modelNode.ScalingOffset.value;
  957. if ("ScalingPivot" in modelNode)
  958. transformData.scalingPivot = modelNode.ScalingPivot.value;
  959. if ("RotationOffset" in modelNode)
  960. transformData.rotationOffset = modelNode.RotationOffset.value;
  961. if ("RotationPivot" in modelNode)
  962. transformData.rotationPivot = modelNode.RotationPivot.value;
  963. model.userData.transformData = transformData;
  964. }
  965. setLookAtProperties(model, modelNode) {
  966. if ("LookAtProperty" in modelNode) {
  967. const children = connections.get(model.ID).children;
  968. children.forEach(function (child) {
  969. if (child.relationship === "LookAtProperty") {
  970. const lookAtTarget = fbxTree.Objects.Model[child.ID];
  971. if ("Lcl_Translation" in lookAtTarget) {
  972. const pos = lookAtTarget.Lcl_Translation.value;
  973. // DirectionalLight, SpotLight
  974. if (model.target !== undefined) {
  975. model.target.position.fromArray(pos);
  976. sceneGraph.add(model.target);
  977. } else {
  978. // Cameras and other Object3Ds
  979. model.lookAt(new Vector3().fromArray(pos));
  980. }
  981. }
  982. }
  983. });
  984. }
  985. }
  986. bindSkeleton(skeletons, geometryMap, modelMap) {
  987. const bindMatrices = this.parsePoseNodes();
  988. for (const ID in skeletons) {
  989. const skeleton = skeletons[ID];
  990. const parents = connections.get(parseInt(skeleton.ID)).parents;
  991. parents.forEach(function (parent) {
  992. if (geometryMap.has(parent.ID)) {
  993. const geoID = parent.ID;
  994. const geoRelationships = connections.get(geoID);
  995. geoRelationships.parents.forEach(function (geoConnParent) {
  996. if (modelMap.has(geoConnParent.ID)) {
  997. const model = modelMap.get(geoConnParent.ID);
  998. model.bind(
  999. new Skeleton(skeleton.bones),
  1000. bindMatrices[geoConnParent.ID]
  1001. );
  1002. }
  1003. });
  1004. }
  1005. });
  1006. }
  1007. }
  1008. parsePoseNodes() {
  1009. const bindMatrices = {};
  1010. if ("Pose" in fbxTree.Objects) {
  1011. const BindPoseNode = fbxTree.Objects.Pose;
  1012. for (const nodeID in BindPoseNode) {
  1013. if (
  1014. BindPoseNode[nodeID].attrType === "BindPose" &&
  1015. BindPoseNode[nodeID].NbPoseNodes > 0
  1016. ) {
  1017. const poseNodes = BindPoseNode[nodeID].PoseNode;
  1018. if (Array.isArray(poseNodes)) {
  1019. poseNodes.forEach(function (poseNode) {
  1020. bindMatrices[poseNode.Node] = new Matrix4().fromArray(
  1021. poseNode.Matrix.a
  1022. );
  1023. });
  1024. } else {
  1025. bindMatrices[poseNodes.Node] = new Matrix4().fromArray(
  1026. poseNodes.Matrix.a
  1027. );
  1028. }
  1029. }
  1030. }
  1031. }
  1032. return bindMatrices;
  1033. }
  1034. // Parse ambient color in FBXTree.GlobalSettings - if it's not set to black (default), create an ambient light
  1035. createAmbientLight() {
  1036. if (
  1037. "GlobalSettings" in fbxTree &&
  1038. "AmbientColor" in fbxTree.GlobalSettings
  1039. ) {
  1040. const ambientColor = fbxTree.GlobalSettings.AmbientColor.value;
  1041. const r = ambientColor[0];
  1042. const g = ambientColor[1];
  1043. const b = ambientColor[2];
  1044. if (r !== 0 || g !== 0 || b !== 0) {
  1045. const color = new Color(r, g, b).convertSRGBToLinear();
  1046. sceneGraph.add(new AmbientLight(color, 1));
  1047. }
  1048. }
  1049. }
  1050. }
  1051. // parse Geometry data from FBXTree and return map of BufferGeometries
  1052. class GeometryParser {
  1053. constructor() {
  1054. this.negativeMaterialIndices = false;
  1055. }
  1056. // Parse nodes in FBXTree.Objects.Geometry
  1057. parse(deformers) {
  1058. const geometryMap = new Map();
  1059. if ("Geometry" in fbxTree.Objects) {
  1060. const geoNodes = fbxTree.Objects.Geometry;
  1061. for (const nodeID in geoNodes) {
  1062. const relationships = connections.get(parseInt(nodeID));
  1063. const geo = this.parseGeometry(
  1064. relationships,
  1065. geoNodes[nodeID],
  1066. deformers
  1067. );
  1068. geometryMap.set(parseInt(nodeID), geo);
  1069. }
  1070. }
  1071. // report warnings
  1072. if (this.negativeMaterialIndices === true) {
  1073. console.warn(
  1074. "THREE.FBXLoader: The FBX file contains invalid (negative) material indices. The asset might not render as expected."
  1075. );
  1076. }
  1077. return geometryMap;
  1078. }
  1079. // Parse single node in FBXTree.Objects.Geometry
  1080. parseGeometry(relationships, geoNode, deformers) {
  1081. switch (geoNode.attrType) {
  1082. case "Mesh":
  1083. return this.parseMeshGeometry(relationships, geoNode, deformers);
  1084. break;
  1085. case "NurbsCurve":
  1086. return this.parseNurbsGeometry(geoNode);
  1087. break;
  1088. }
  1089. }
  1090. // Parse single node mesh geometry in FBXTree.Objects.Geometry
  1091. parseMeshGeometry(relationships, geoNode, deformers) {
  1092. const skeletons = deformers.skeletons;
  1093. const morphTargets = [];
  1094. const modelNodes = relationships.parents.map(function (parent) {
  1095. return fbxTree.Objects.Model[parent.ID];
  1096. });
  1097. // don't create geometry if it is not associated with any models
  1098. if (modelNodes.length === 0) return;
  1099. const skeleton = relationships.children.reduce(function (skeleton, child) {
  1100. if (skeletons[child.ID] !== undefined) skeleton = skeletons[child.ID];
  1101. return skeleton;
  1102. }, null);
  1103. relationships.children.forEach(function (child) {
  1104. if (deformers.morphTargets[child.ID] !== undefined) {
  1105. morphTargets.push(deformers.morphTargets[child.ID]);
  1106. }
  1107. });
  1108. // Assume one model and get the preRotation from that
  1109. // if there is more than one model associated with the geometry this may cause problems
  1110. const modelNode = modelNodes[0];
  1111. const transformData = {};
  1112. if ("RotationOrder" in modelNode)
  1113. transformData.eulerOrder = getEulerOrder(modelNode.RotationOrder.value);
  1114. if ("InheritType" in modelNode)
  1115. transformData.inheritType = parseInt(modelNode.InheritType.value);
  1116. if ("GeometricTranslation" in modelNode)
  1117. transformData.translation = modelNode.GeometricTranslation.value;
  1118. if ("GeometricRotation" in modelNode)
  1119. transformData.rotation = modelNode.GeometricRotation.value;
  1120. if ("GeometricScaling" in modelNode)
  1121. transformData.scale = modelNode.GeometricScaling.value;
  1122. const transform = generateTransform(transformData);
  1123. return this.genGeometry(geoNode, skeleton, morphTargets, transform);
  1124. }
  1125. // Generate a BufferGeometry from a node in FBXTree.Objects.Geometry
  1126. genGeometry(geoNode, skeleton, morphTargets, preTransform) {
  1127. const geo = new BufferGeometry();
  1128. if (geoNode.attrName) geo.name = geoNode.attrName;
  1129. const geoInfo = this.parseGeoNode(geoNode, skeleton);
  1130. const buffers = this.genBuffers(geoInfo);
  1131. const positionAttribute = new Float32BufferAttribute(buffers.vertex, 3);
  1132. positionAttribute.applyMatrix4(preTransform);
  1133. geo.setAttribute("position", positionAttribute);
  1134. if (buffers.colors.length > 0) {
  1135. geo.setAttribute("color", new Float32BufferAttribute(buffers.colors, 3));
  1136. }
  1137. if (skeleton) {
  1138. geo.setAttribute(
  1139. "skinIndex",
  1140. new Uint16BufferAttribute(buffers.weightsIndices, 4)
  1141. );
  1142. geo.setAttribute(
  1143. "skinWeight",
  1144. new Float32BufferAttribute(buffers.vertexWeights, 4)
  1145. );
  1146. // used later to bind the skeleton to the model
  1147. geo.FBX_Deformer = skeleton;
  1148. }
  1149. if (buffers.normal.length > 0) {
  1150. const normalMatrix = new Matrix3().getNormalMatrix(preTransform);
  1151. const normalAttribute = new Float32BufferAttribute(buffers.normal, 3);
  1152. normalAttribute.applyNormalMatrix(normalMatrix);
  1153. geo.setAttribute("normal", normalAttribute);
  1154. }
  1155. buffers.uvs.forEach(function (uvBuffer, i) {
  1156. const name = i === 0 ? "uv" : `uv${i}`;
  1157. geo.setAttribute(name, new Float32BufferAttribute(buffers.uvs[i], 2));
  1158. });
  1159. if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
  1160. // Convert the material indices of each vertex into rendering groups on the geometry.
  1161. let prevMaterialIndex = buffers.materialIndex[0];
  1162. let startIndex = 0;
  1163. buffers.materialIndex.forEach(function (currentIndex, i) {
  1164. if (currentIndex !== prevMaterialIndex) {
  1165. geo.addGroup(startIndex, i - startIndex, prevMaterialIndex);
  1166. prevMaterialIndex = currentIndex;
  1167. startIndex = i;
  1168. }
  1169. });
  1170. // the loop above doesn't add the last group, do that here.
  1171. if (geo.groups.length > 0) {
  1172. const lastGroup = geo.groups[geo.groups.length - 1];
  1173. const lastIndex = lastGroup.start + lastGroup.count;
  1174. if (lastIndex !== buffers.materialIndex.length) {
  1175. geo.addGroup(
  1176. lastIndex,
  1177. buffers.materialIndex.length - lastIndex,
  1178. prevMaterialIndex
  1179. );
  1180. }
  1181. }
  1182. // case where there are multiple materials but the whole geometry is only
  1183. // using one of them
  1184. if (geo.groups.length === 0) {
  1185. geo.addGroup(0, buffers.materialIndex.length, buffers.materialIndex[0]);
  1186. }
  1187. }
  1188. this.addMorphTargets(geo, geoNode, morphTargets, preTransform);
  1189. return geo;
  1190. }
  1191. parseGeoNode(geoNode, skeleton) {
  1192. const geoInfo = {};
  1193. geoInfo.vertexPositions =
  1194. geoNode.Vertices !== undefined ? geoNode.Vertices.a : [];
  1195. geoInfo.vertexIndices =
  1196. geoNode.PolygonVertexIndex !== undefined
  1197. ? geoNode.PolygonVertexIndex.a
  1198. : [];
  1199. if (geoNode.LayerElementColor) {
  1200. geoInfo.color = this.parseVertexColors(geoNode.LayerElementColor[0]);
  1201. }
  1202. if (geoNode.LayerElementMaterial) {
  1203. geoInfo.material = this.parseMaterialIndices(
  1204. geoNode.LayerElementMaterial[0]
  1205. );
  1206. }
  1207. if (geoNode.LayerElementNormal) {
  1208. geoInfo.normal = this.parseNormals(geoNode.LayerElementNormal[0]);
  1209. }
  1210. if (geoNode.LayerElementUV) {
  1211. geoInfo.uv = [];
  1212. let i = 0;
  1213. while (geoNode.LayerElementUV[i]) {
  1214. if (geoNode.LayerElementUV[i].UV) {
  1215. geoInfo.uv.push(this.parseUVs(geoNode.LayerElementUV[i]));
  1216. }
  1217. i++;
  1218. }
  1219. }
  1220. geoInfo.weightTable = {};
  1221. if (skeleton !== null) {
  1222. geoInfo.skeleton = skeleton;
  1223. skeleton.rawBones.forEach(function (rawBone, i) {
  1224. // loop over the bone's vertex indices and weights
  1225. rawBone.indices.forEach(function (index, j) {
  1226. if (geoInfo.weightTable[index] === undefined)
  1227. geoInfo.weightTable[index] = [];
  1228. geoInfo.weightTable[index].push({
  1229. id: i,
  1230. weight: rawBone.weights[j],
  1231. });
  1232. });
  1233. });
  1234. }
  1235. return geoInfo;
  1236. }
  1237. genBuffers(geoInfo) {
  1238. const buffers = {
  1239. vertex: [],
  1240. normal: [],
  1241. colors: [],
  1242. uvs: [],
  1243. materialIndex: [],
  1244. vertexWeights: [],
  1245. weightsIndices: [],
  1246. };
  1247. let polygonIndex = 0;
  1248. let faceLength = 0;
  1249. let displayedWeightsWarning = false;
  1250. // these will hold data for a single face
  1251. let facePositionIndexes = [];
  1252. let faceNormals = [];
  1253. let faceColors = [];
  1254. let faceUVs = [];
  1255. let faceWeights = [];
  1256. let faceWeightIndices = [];
  1257. const scope = this;
  1258. geoInfo.vertexIndices.forEach(function (vertexIndex, polygonVertexIndex) {
  1259. let materialIndex;
  1260. let endOfFace = false;
  1261. // Face index and vertex index arrays are combined in a single array
  1262. // A cube with quad faces looks like this:
  1263. // PolygonVertexIndex: *24 {
  1264. // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5
  1265. // }
  1266. // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3
  1267. // to find index of last vertex bit shift the index: ^ - 1
  1268. if (vertexIndex < 0) {
  1269. vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1
  1270. endOfFace = true;
  1271. }
  1272. let weightIndices = [];
  1273. let weights = [];
  1274. facePositionIndexes.push(
  1275. vertexIndex * 3,
  1276. vertexIndex * 3 + 1,
  1277. vertexIndex * 3 + 2
  1278. );
  1279. if (geoInfo.color) {
  1280. const data = getData(
  1281. polygonVertexIndex,
  1282. polygonIndex,
  1283. vertexIndex,
  1284. geoInfo.color
  1285. );
  1286. faceColors.push(data[0], data[1], data[2]);
  1287. }
  1288. if (geoInfo.skeleton) {
  1289. if (geoInfo.weightTable[vertexIndex] !== undefined) {
  1290. geoInfo.weightTable[vertexIndex].forEach(function (wt) {
  1291. weights.push(wt.weight);
  1292. weightIndices.push(wt.id);
  1293. });
  1294. }
  1295. if (weights.length > 4) {
  1296. if (!displayedWeightsWarning) {
  1297. console.warn(
  1298. "THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights."
  1299. );
  1300. displayedWeightsWarning = true;
  1301. }
  1302. const wIndex = [0, 0, 0, 0];
  1303. const Weight = [0, 0, 0, 0];
  1304. weights.forEach(function (weight, weightIndex) {
  1305. let currentWeight = weight;
  1306. let currentIndex = weightIndices[weightIndex];
  1307. Weight.forEach(function (
  1308. comparedWeight,
  1309. comparedWeightIndex,
  1310. comparedWeightArray
  1311. ) {
  1312. if (currentWeight > comparedWeight) {
  1313. comparedWeightArray[comparedWeightIndex] = currentWeight;
  1314. currentWeight = comparedWeight;
  1315. const tmp = wIndex[comparedWeightIndex];
  1316. wIndex[comparedWeightIndex] = currentIndex;
  1317. currentIndex = tmp;
  1318. }
  1319. });
  1320. });
  1321. weightIndices = wIndex;
  1322. weights = Weight;
  1323. }
  1324. // if the weight array is shorter than 4 pad with 0s
  1325. while (weights.length < 4) {
  1326. weights.push(0);
  1327. weightIndices.push(0);
  1328. }
  1329. for (let i = 0; i < 4; ++i) {
  1330. faceWeights.push(weights[i]);
  1331. faceWeightIndices.push(weightIndices[i]);
  1332. }
  1333. }
  1334. if (geoInfo.normal) {
  1335. const data = getData(
  1336. polygonVertexIndex,
  1337. polygonIndex,
  1338. vertexIndex,
  1339. geoInfo.normal
  1340. );
  1341. faceNormals.push(data[0], data[1], data[2]);
  1342. }
  1343. if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
  1344. materialIndex = getData(
  1345. polygonVertexIndex,
  1346. polygonIndex,
  1347. vertexIndex,
  1348. geoInfo.material
  1349. )[0];
  1350. if (materialIndex < 0) {
  1351. scope.negativeMaterialIndices = true;
  1352. materialIndex = 0; // fallback
  1353. }
  1354. }
  1355. if (geoInfo.uv) {
  1356. geoInfo.uv.forEach(function (uv, i) {
  1357. const data = getData(
  1358. polygonVertexIndex,
  1359. polygonIndex,
  1360. vertexIndex,
  1361. uv
  1362. );
  1363. if (faceUVs[i] === undefined) {
  1364. faceUVs[i] = [];
  1365. }
  1366. faceUVs[i].push(data[0]);
  1367. faceUVs[i].push(data[1]);
  1368. });
  1369. }
  1370. faceLength++;
  1371. if (endOfFace) {
  1372. if (faceLength > 4)
  1373. console.warn(
  1374. "THREE.FBXLoader: Polygons with more than four sides are not supported. Make sure to triangulate the geometry during export."
  1375. );
  1376. scope.genFace(
  1377. buffers,
  1378. geoInfo,
  1379. facePositionIndexes,
  1380. materialIndex,
  1381. faceNormals,
  1382. faceColors,
  1383. faceUVs,
  1384. faceWeights,
  1385. faceWeightIndices,
  1386. faceLength
  1387. );
  1388. polygonIndex++;
  1389. faceLength = 0;
  1390. // reset arrays for the next face
  1391. facePositionIndexes = [];
  1392. faceNormals = [];
  1393. faceColors = [];
  1394. faceUVs = [];
  1395. faceWeights = [];
  1396. faceWeightIndices = [];
  1397. }
  1398. });
  1399. return buffers;
  1400. }
  1401. // Generate data for a single face in a geometry. If the face is a quad then split it into 2 tris
  1402. genFace(
  1403. buffers,
  1404. geoInfo,
  1405. facePositionIndexes,
  1406. materialIndex,
  1407. faceNormals,
  1408. faceColors,
  1409. faceUVs,
  1410. faceWeights,
  1411. faceWeightIndices,
  1412. faceLength
  1413. ) {
  1414. for (let i = 2; i < faceLength; i++) {
  1415. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[0]]);
  1416. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[1]]);
  1417. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[2]]);
  1418. buffers.vertex.push(
  1419. geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3]]
  1420. );
  1421. buffers.vertex.push(
  1422. geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 1]]
  1423. );
  1424. buffers.vertex.push(
  1425. geoInfo.vertexPositions[facePositionIndexes[(i - 1) * 3 + 2]]
  1426. );
  1427. buffers.vertex.push(geoInfo.vertexPositions[facePositionIndexes[i * 3]]);
  1428. buffers.vertex.push(
  1429. geoInfo.vertexPositions[facePositionIndexes[i * 3 + 1]]
  1430. );
  1431. buffers.vertex.push(
  1432. geoInfo.vertexPositions[facePositionIndexes[i * 3 + 2]]
  1433. );
  1434. if (geoInfo.skeleton) {
  1435. buffers.vertexWeights.push(faceWeights[0]);
  1436. buffers.vertexWeights.push(faceWeights[1]);
  1437. buffers.vertexWeights.push(faceWeights[2]);
  1438. buffers.vertexWeights.push(faceWeights[3]);
  1439. buffers.vertexWeights.push(faceWeights[(i - 1) * 4]);
  1440. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 1]);
  1441. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 2]);
  1442. buffers.vertexWeights.push(faceWeights[(i - 1) * 4 + 3]);
  1443. buffers.vertexWeights.push(faceWeights[i * 4]);
  1444. buffers.vertexWeights.push(faceWeights[i * 4 + 1]);
  1445. buffers.vertexWeights.push(faceWeights[i * 4 + 2]);
  1446. buffers.vertexWeights.push(faceWeights[i * 4 + 3]);
  1447. buffers.weightsIndices.push(faceWeightIndices[0]);
  1448. buffers.weightsIndices.push(faceWeightIndices[1]);
  1449. buffers.weightsIndices.push(faceWeightIndices[2]);
  1450. buffers.weightsIndices.push(faceWeightIndices[3]);
  1451. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4]);
  1452. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 1]);
  1453. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 2]);
  1454. buffers.weightsIndices.push(faceWeightIndices[(i - 1) * 4 + 3]);
  1455. buffers.weightsIndices.push(faceWeightIndices[i * 4]);
  1456. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 1]);
  1457. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 2]);
  1458. buffers.weightsIndices.push(faceWeightIndices[i * 4 + 3]);
  1459. }
  1460. if (geoInfo.color) {
  1461. buffers.colors.push(faceColors[0]);
  1462. buffers.colors.push(faceColors[1]);
  1463. buffers.colors.push(faceColors[2]);
  1464. buffers.colors.push(faceColors[(i - 1) * 3]);
  1465. buffers.colors.push(faceColors[(i - 1) * 3 + 1]);
  1466. buffers.colors.push(faceColors[(i - 1) * 3 + 2]);
  1467. buffers.colors.push(faceColors[i * 3]);
  1468. buffers.colors.push(faceColors[i * 3 + 1]);
  1469. buffers.colors.push(faceColors[i * 3 + 2]);
  1470. }
  1471. if (geoInfo.material && geoInfo.material.mappingType !== "AllSame") {
  1472. buffers.materialIndex.push(materialIndex);
  1473. buffers.materialIndex.push(materialIndex);
  1474. buffers.materialIndex.push(materialIndex);
  1475. }
  1476. if (geoInfo.normal) {
  1477. buffers.normal.push(faceNormals[0]);
  1478. buffers.normal.push(faceNormals[1]);
  1479. buffers.normal.push(faceNormals[2]);
  1480. buffers.normal.push(faceNormals[(i - 1) * 3]);
  1481. buffers.normal.push(faceNormals[(i - 1) * 3 + 1]);
  1482. buffers.normal.push(faceNormals[(i - 1) * 3 + 2]);
  1483. buffers.normal.push(faceNormals[i * 3]);
  1484. buffers.normal.push(faceNormals[i * 3 + 1]);
  1485. buffers.normal.push(faceNormals[i * 3 + 2]);
  1486. }
  1487. if (geoInfo.uv) {
  1488. geoInfo.uv.forEach(function (uv, j) {
  1489. if (buffers.uvs[j] === undefined) buffers.uvs[j] = [];
  1490. buffers.uvs[j].push(faceUVs[j][0]);
  1491. buffers.uvs[j].push(faceUVs[j][1]);
  1492. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2]);
  1493. buffers.uvs[j].push(faceUVs[j][(i - 1) * 2 + 1]);
  1494. buffers.uvs[j].push(faceUVs[j][i * 2]);
  1495. buffers.uvs[j].push(faceUVs[j][i * 2 + 1]);
  1496. });
  1497. }
  1498. }
  1499. }
  1500. addMorphTargets(parentGeo, parentGeoNode, morphTargets, preTransform) {
  1501. if (morphTargets.length === 0) return;
  1502. parentGeo.morphTargetsRelative = true;
  1503. parentGeo.morphAttributes.position = [];
  1504. // parentGeo.morphAttributes.normal = []; // not implemented
  1505. const scope = this;
  1506. morphTargets.forEach(function (morphTarget) {
  1507. morphTarget.rawTargets.forEach(function (rawTarget) {
  1508. const morphGeoNode = fbxTree.Objects.Geometry[rawTarget.geoID];
  1509. if (morphGeoNode !== undefined) {
  1510. scope.genMorphGeometry(
  1511. parentGeo,
  1512. parentGeoNode,
  1513. morphGeoNode,
  1514. preTransform,
  1515. rawTarget.name
  1516. );
  1517. }
  1518. });
  1519. });
  1520. }
  1521. // a morph geometry node is similar to a standard node, and the node is also contained
  1522. // in FBXTree.Objects.Geometry, however it can only have attributes for position, normal
  1523. // and a special attribute Index defining which vertices of the original geometry are affected
  1524. // Normal and position attributes only have data for the vertices that are affected by the morph
  1525. genMorphGeometry(parentGeo, parentGeoNode, morphGeoNode, preTransform, name) {
  1526. const vertexIndices =
  1527. parentGeoNode.PolygonVertexIndex !== undefined
  1528. ? parentGeoNode.PolygonVertexIndex.a
  1529. : [];
  1530. const morphPositionsSparse =
  1531. morphGeoNode.Vertices !== undefined ? morphGeoNode.Vertices.a : [];
  1532. const indices =
  1533. morphGeoNode.Indexes !== undefined ? morphGeoNode.Indexes.a : [];
  1534. const length = parentGeo.attributes.position.count * 3;
  1535. const morphPositions = new Float32Array(length);
  1536. for (let i = 0; i < indices.length; i++) {
  1537. const morphIndex = indices[i] * 3;
  1538. morphPositions[morphIndex] = morphPositionsSparse[i * 3];
  1539. morphPositions[morphIndex + 1] = morphPositionsSparse[i * 3 + 1];
  1540. morphPositions[morphIndex + 2] = morphPositionsSparse[i * 3 + 2];
  1541. }
  1542. // TODO: add morph normal support
  1543. const morphGeoInfo = {
  1544. vertexIndices: vertexIndices,
  1545. vertexPositions: morphPositions,
  1546. };
  1547. const morphBuffers = this.genBuffers(morphGeoInfo);
  1548. const positionAttribute = new Float32BufferAttribute(
  1549. morphBuffers.vertex,
  1550. 3
  1551. );
  1552. positionAttribute.name = name || morphGeoNode.attrName;
  1553. positionAttribute.applyMatrix4(preTransform);
  1554. parentGeo.morphAttributes.position.push(positionAttribute);
  1555. }
  1556. // Parse normal from FBXTree.Objects.Geometry.LayerElementNormal if it exists
  1557. parseNormals(NormalNode) {
  1558. const mappingType = NormalNode.MappingInformationType;
  1559. const referenceType = NormalNode.ReferenceInformationType;
  1560. const buffer = NormalNode.Normals.a;
  1561. let indexBuffer = [];
  1562. if (referenceType === "IndexToDirect") {
  1563. if ("NormalIndex" in NormalNode) {
  1564. indexBuffer = NormalNode.NormalIndex.a;
  1565. } else if ("NormalsIndex" in NormalNode) {
  1566. indexBuffer = NormalNode.NormalsIndex.a;
  1567. }
  1568. }
  1569. return {
  1570. dataSize: 3,
  1571. buffer: buffer,
  1572. indices: indexBuffer,
  1573. mappingType: mappingType,
  1574. referenceType: referenceType,
  1575. };
  1576. }
  1577. // Parse UVs from FBXTree.Objects.Geometry.LayerElementUV if it exists
  1578. parseUVs(UVNode) {
  1579. const mappingType = UVNode.MappingInformationType;
  1580. const referenceType = UVNode.ReferenceInformationType;
  1581. const buffer = UVNode.UV.a;
  1582. let indexBuffer = [];
  1583. if (referenceType === "IndexToDirect") {
  1584. indexBuffer = UVNode.UVIndex.a;
  1585. }
  1586. return {
  1587. dataSize: 2,
  1588. buffer: buffer,
  1589. indices: indexBuffer,
  1590. mappingType: mappingType,
  1591. referenceType: referenceType,
  1592. };
  1593. }
  1594. // Parse Vertex Colors from FBXTree.Objects.Geometry.LayerElementColor if it exists
  1595. parseVertexColors(ColorNode) {
  1596. const mappingType = ColorNode.MappingInformationType;
  1597. const referenceType = ColorNode.ReferenceInformationType;
  1598. const buffer = ColorNode.Colors.a;
  1599. let indexBuffer = [];
  1600. if (referenceType === "IndexToDirect") {
  1601. indexBuffer = ColorNode.ColorIndex.a;
  1602. }
  1603. for (let i = 0, c = new Color(); i < buffer.length; i += 4) {
  1604. c.fromArray(buffer, i).convertSRGBToLinear().toArray(buffer, i);
  1605. }
  1606. return {
  1607. dataSize: 4,
  1608. buffer: buffer,
  1609. indices: indexBuffer,
  1610. mappingType: mappingType,
  1611. referenceType: referenceType,
  1612. };
  1613. }
  1614. // Parse mapping and material data in FBXTree.Objects.Geometry.LayerElementMaterial if it exists
  1615. parseMaterialIndices(MaterialNode) {
  1616. const mappingType = MaterialNode.MappingInformationType;
  1617. const referenceType = MaterialNode.ReferenceInformationType;
  1618. if (mappingType === "NoMappingInformation") {
  1619. return {
  1620. dataSize: 1,
  1621. buffer: [0],
  1622. indices: [0],
  1623. mappingType: "AllSame",
  1624. referenceType: referenceType,
  1625. };
  1626. }
  1627. const materialIndexBuffer = MaterialNode.Materials.a;
  1628. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  1629. // we expect.So we create an intermediate buffer that points to the index in the buffer,
  1630. // for conforming with the other functions we've written for other data.
  1631. const materialIndices = [];
  1632. for (let i = 0; i < materialIndexBuffer.length; ++i) {
  1633. materialIndices.push(i);
  1634. }
  1635. return {
  1636. dataSize: 1,
  1637. buffer: materialIndexBuffer,
  1638. indices: materialIndices,
  1639. mappingType: mappingType,
  1640. referenceType: referenceType,
  1641. };
  1642. }
  1643. // Generate a NurbGeometry from a node in FBXTree.Objects.Geometry
  1644. parseNurbsGeometry(geoNode) {
  1645. const order = parseInt(geoNode.Order);
  1646. if (isNaN(order)) {
  1647. console.error(
  1648. "THREE.FBXLoader: Invalid Order %s given for geometry ID: %s",
  1649. geoNode.Order,
  1650. geoNode.id
  1651. );
  1652. return new BufferGeometry();
  1653. }
  1654. const degree = order - 1;
  1655. const knots = geoNode.KnotVector.a;
  1656. const controlPoints = [];
  1657. const pointsValues = geoNode.Points.a;
  1658. for (let i = 0, l = pointsValues.length; i < l; i += 4) {
  1659. controlPoints.push(new Vector4().fromArray(pointsValues, i));
  1660. }
  1661. let startKnot, endKnot;
  1662. if (geoNode.Form === "Closed") {
  1663. controlPoints.push(controlPoints[0]);
  1664. } else if (geoNode.Form === "Periodic") {
  1665. startKnot = degree;
  1666. endKnot = knots.length - 1 - startKnot;
  1667. for (let i = 0; i < degree; ++i) {
  1668. controlPoints.push(controlPoints[i]);
  1669. }
  1670. }
  1671. const curve = new NURBSCurve(
  1672. degree,
  1673. knots,
  1674. controlPoints,
  1675. startKnot,
  1676. endKnot
  1677. );
  1678. const points = curve.getPoints(controlPoints.length * 12);
  1679. return new BufferGeometry().setFromPoints(points);
  1680. }
  1681. }
  1682. // parse animation data from FBXTree
  1683. class AnimationParser {
  1684. // take raw animation clips and turn them into three.js animation clips
  1685. parse() {
  1686. const animationClips = [];
  1687. const rawClips = this.parseClips();
  1688. if (rawClips !== undefined) {
  1689. for (const key in rawClips) {
  1690. const rawClip = rawClips[key];
  1691. const clip = this.addClip(rawClip);
  1692. animationClips.push(clip);
  1693. }
  1694. }
  1695. return animationClips;
  1696. }
  1697. parseClips() {
  1698. // since the actual transformation data is stored in FBXTree.Objects.AnimationCurve,
  1699. // if this is undefined we can safely assume there are no animations
  1700. if (fbxTree.Objects.AnimationCurve === undefined) return undefined;
  1701. const curveNodesMap = this.parseAnimationCurveNodes();
  1702. this.parseAnimationCurves(curveNodesMap);
  1703. const layersMap = this.parseAnimationLayers(curveNodesMap);
  1704. const rawClips = this.parseAnimStacks(layersMap);
  1705. return rawClips;
  1706. }
  1707. // parse nodes in FBXTree.Objects.AnimationCurveNode
  1708. // each AnimationCurveNode holds data for an animation transform for a model (e.g. left arm rotation )
  1709. // and is referenced by an AnimationLayer
  1710. parseAnimationCurveNodes() {
  1711. const rawCurveNodes = fbxTree.Objects.AnimationCurveNode;
  1712. const curveNodesMap = new Map();
  1713. for (const nodeID in rawCurveNodes) {
  1714. const rawCurveNode = rawCurveNodes[nodeID];
  1715. if (rawCurveNode.attrName.match(/S|R|T|DeformPercent/) !== null) {
  1716. const curveNode = {
  1717. id: rawCurveNode.id,
  1718. attr: rawCurveNode.attrName,
  1719. curves: {},
  1720. };
  1721. curveNodesMap.set(curveNode.id, curveNode);
  1722. }
  1723. }
  1724. return curveNodesMap;
  1725. }
  1726. // parse nodes in FBXTree.Objects.AnimationCurve and connect them up to
  1727. // previously parsed AnimationCurveNodes. Each AnimationCurve holds data for a single animated
  1728. // axis ( e.g. times and values of x rotation)
  1729. parseAnimationCurves(curveNodesMap) {
  1730. const rawCurves = fbxTree.Objects.AnimationCurve;
  1731. // TODO: Many values are identical up to roundoff error, but won't be optimised
  1732. // e.g. position times: [0, 0.4, 0. 8]
  1733. // position values: [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.23538335023477e-7, 93.67518615722656, -0.9982695579528809, 7.235384487103147e-7, 93.67520904541016, -0.9982695579528809]
  1734. // clearly, this should be optimised to
  1735. // times: [0], positions [7.23538335023477e-7, 93.67518615722656, -0.9982695579528809]
  1736. // this shows up in nearly every FBX file, and generally time array is length > 100
  1737. for (const nodeID in rawCurves) {
  1738. const animationCurve = {
  1739. id: rawCurves[nodeID].id,
  1740. times: rawCurves[nodeID].KeyTime.a.map(convertFBXTimeToSeconds),
  1741. values: rawCurves[nodeID].KeyValueFloat.a,
  1742. };
  1743. const relationships = connections.get(animationCurve.id);
  1744. if (relationships !== undefined) {
  1745. const animationCurveID = relationships.parents[0].ID;
  1746. const animationCurveRelationship =
  1747. relationships.parents[0].relationship;
  1748. if (animationCurveRelationship.match(/X/)) {
  1749. curveNodesMap.get(animationCurveID).curves["x"] = animationCurve;
  1750. } else if (animationCurveRelationship.match(/Y/)) {
  1751. curveNodesMap.get(animationCurveID).curves["y"] = animationCurve;
  1752. } else if (animationCurveRelationship.match(/Z/)) {
  1753. curveNodesMap.get(animationCurveID).curves["z"] = animationCurve;
  1754. } else if (
  1755. animationCurveRelationship.match(/DeformPercent/) &&
  1756. curveNodesMap.has(animationCurveID)
  1757. ) {
  1758. curveNodesMap.get(animationCurveID).curves["morph"] = animationCurve;
  1759. }
  1760. }
  1761. }
  1762. }
  1763. // parse nodes in FBXTree.Objects.AnimationLayer. Each layers holds references
  1764. // to various AnimationCurveNodes and is referenced by an AnimationStack node
  1765. // note: theoretically a stack can have multiple layers, however in practice there always seems to be one per stack
  1766. parseAnimationLayers(curveNodesMap) {
  1767. const rawLayers = fbxTree.Objects.AnimationLayer;
  1768. const layersMap = new Map();
  1769. for (const nodeID in rawLayers) {
  1770. const layerCurveNodes = [];
  1771. const connection = connections.get(parseInt(nodeID));
  1772. if (connection !== undefined) {
  1773. // all the animationCurveNodes used in the layer
  1774. const children = connection.children;
  1775. children.forEach(function (child, i) {
  1776. if (curveNodesMap.has(child.ID)) {
  1777. const curveNode = curveNodesMap.get(child.ID);
  1778. // check that the curves are defined for at least one axis, otherwise ignore the curveNode
  1779. if (
  1780. curveNode.curves.x !== undefined ||
  1781. curveNode.curves.y !== undefined ||
  1782. curveNode.curves.z !== undefined
  1783. ) {
  1784. if (layerCurveNodes[i] === undefined) {
  1785. const modelID = connections
  1786. .get(child.ID)
  1787. .parents.filter(function (parent) {
  1788. return parent.relationship !== undefined;
  1789. })[0].ID;
  1790. if (modelID !== undefined) {
  1791. const rawModel = fbxTree.Objects.Model[modelID.toString()];
  1792. if (rawModel === undefined) {
  1793. console.warn(
  1794. "THREE.FBXLoader: Encountered a unused curve.",
  1795. child
  1796. );
  1797. return;
  1798. }
  1799. const node = {
  1800. modelName: rawModel.attrName
  1801. ? PropertyBinding.sanitizeNodeName(rawModel.attrName)
  1802. : "",
  1803. ID: rawModel.id,
  1804. initialPosition: [0, 0, 0],
  1805. initialRotation: [0, 0, 0],
  1806. initialScale: [1, 1, 1],
  1807. };
  1808. sceneGraph.traverse(function (child) {
  1809. if (child.ID === rawModel.id) {
  1810. node.transform = child.matrix;
  1811. if (child.userData.transformData)
  1812. node.eulerOrder =
  1813. child.userData.transformData.eulerOrder;
  1814. }
  1815. });
  1816. if (!node.transform) node.transform = new Matrix4();
  1817. // if the animated model is pre rotated, we'll have to apply the pre rotations to every
  1818. // animation value as well
  1819. if ("PreRotation" in rawModel)
  1820. node.preRotation = rawModel.PreRotation.value;
  1821. if ("PostRotation" in rawModel)
  1822. node.postRotation = rawModel.PostRotation.value;
  1823. layerCurveNodes[i] = node;
  1824. }
  1825. }
  1826. if (layerCurveNodes[i])
  1827. layerCurveNodes[i][curveNode.attr] = curveNode;
  1828. } else if (curveNode.curves.morph !== undefined) {
  1829. if (layerCurveNodes[i] === undefined) {
  1830. const deformerID = connections
  1831. .get(child.ID)
  1832. .parents.filter(function (parent) {
  1833. return parent.relationship !== undefined;
  1834. })[0].ID;
  1835. const morpherID = connections.get(deformerID).parents[0].ID;
  1836. const geoID = connections.get(morpherID).parents[0].ID;
  1837. // assuming geometry is not used in more than one model
  1838. const modelID = connections.get(geoID).parents[0].ID;
  1839. const rawModel = fbxTree.Objects.Model[modelID];
  1840. const node = {
  1841. modelName: rawModel.attrName
  1842. ? PropertyBinding.sanitizeNodeName(rawModel.attrName)
  1843. : "",
  1844. morphName: fbxTree.Objects.Deformer[deformerID].attrName,
  1845. };
  1846. layerCurveNodes[i] = node;
  1847. }
  1848. layerCurveNodes[i][curveNode.attr] = curveNode;
  1849. }
  1850. }
  1851. });
  1852. layersMap.set(parseInt(nodeID), layerCurveNodes);
  1853. }
  1854. }
  1855. return layersMap;
  1856. }
  1857. // parse nodes in FBXTree.Objects.AnimationStack. These are the top level node in the animation
  1858. // hierarchy. Each Stack node will be used to create a AnimationClip
  1859. parseAnimStacks(layersMap) {
  1860. const rawStacks = fbxTree.Objects.AnimationStack;
  1861. // connect the stacks (clips) up to the layers
  1862. const rawClips = {};
  1863. for (const nodeID in rawStacks) {
  1864. const children = connections.get(parseInt(nodeID)).children;
  1865. if (children.length > 1) {
  1866. // it seems like stacks will always be associated with a single layer. But just in case there are files
  1867. // where there are multiple layers per stack, we'll display a warning
  1868. console.warn(
  1869. "THREE.FBXLoader: Encountered an animation stack with multiple layers, this is currently not supported. Ignoring subsequent layers."
  1870. );
  1871. }
  1872. const layer = layersMap.get(children[0].ID);
  1873. rawClips[nodeID] = {
  1874. name: rawStacks[nodeID].attrName,
  1875. layer: layer,
  1876. };
  1877. }
  1878. return rawClips;
  1879. }
  1880. addClip(rawClip) {
  1881. let tracks = [];
  1882. const scope = this;
  1883. rawClip.layer.forEach(function (rawTracks) {
  1884. tracks = tracks.concat(scope.generateTracks(rawTracks));
  1885. });
  1886. return new AnimationClip(rawClip.name, -1, tracks);
  1887. }
  1888. generateTracks(rawTracks) {
  1889. const tracks = [];
  1890. let initialPosition = new Vector3();
  1891. let initialRotation = new Quaternion();
  1892. let initialScale = new Vector3();
  1893. if (rawTracks.transform)
  1894. rawTracks.transform.decompose(
  1895. initialPosition,
  1896. initialRotation,
  1897. initialScale
  1898. );
  1899. initialPosition = initialPosition.toArray();
  1900. initialRotation = new Euler()
  1901. .setFromQuaternion(initialRotation, rawTracks.eulerOrder)
  1902. .toArray();
  1903. initialScale = initialScale.toArray();
  1904. if (
  1905. rawTracks.T !== undefined &&
  1906. Object.keys(rawTracks.T.curves).length > 0
  1907. ) {
  1908. const positionTrack = this.generateVectorTrack(
  1909. rawTracks.modelName,
  1910. rawTracks.T.curves,
  1911. initialPosition,
  1912. "position"
  1913. );
  1914. if (positionTrack !== undefined) tracks.push(positionTrack);
  1915. }
  1916. if (
  1917. rawTracks.R !== undefined &&
  1918. Object.keys(rawTracks.R.curves).length > 0
  1919. ) {
  1920. const rotationTrack = this.generateRotationTrack(
  1921. rawTracks.modelName,
  1922. rawTracks.R.curves,
  1923. initialRotation,
  1924. rawTracks.preRotation,
  1925. rawTracks.postRotation,
  1926. rawTracks.eulerOrder
  1927. );
  1928. if (rotationTrack !== undefined) tracks.push(rotationTrack);
  1929. }
  1930. if (
  1931. rawTracks.S !== undefined &&
  1932. Object.keys(rawTracks.S.curves).length > 0
  1933. ) {
  1934. const scaleTrack = this.generateVectorTrack(
  1935. rawTracks.modelName,
  1936. rawTracks.S.curves,
  1937. initialScale,
  1938. "scale"
  1939. );
  1940. if (scaleTrack !== undefined) tracks.push(scaleTrack);
  1941. }
  1942. if (rawTracks.DeformPercent !== undefined) {
  1943. const morphTrack = this.generateMorphTrack(rawTracks);
  1944. if (morphTrack !== undefined) tracks.push(morphTrack);
  1945. }
  1946. return tracks;
  1947. }
  1948. generateVectorTrack(modelName, curves, initialValue, type) {
  1949. const times = this.getTimesForAllAxes(curves);
  1950. const values = this.getKeyframeTrackValues(times, curves, initialValue);
  1951. return new VectorKeyframeTrack(modelName + "." + type, times, values);
  1952. }
  1953. generateRotationTrack(
  1954. modelName,
  1955. curves,
  1956. initialValue,
  1957. preRotation,
  1958. postRotation,
  1959. eulerOrder
  1960. ) {
  1961. if (curves.x !== undefined) {
  1962. this.interpolateRotations(curves.x);
  1963. curves.x.values = curves.x.values.map(MathUtils.degToRad);
  1964. }
  1965. if (curves.y !== undefined) {
  1966. this.interpolateRotations(curves.y);
  1967. curves.y.values = curves.y.values.map(MathUtils.degToRad);
  1968. }
  1969. if (curves.z !== undefined) {
  1970. this.interpolateRotations(curves.z);
  1971. curves.z.values = curves.z.values.map(MathUtils.degToRad);
  1972. }
  1973. const times = this.getTimesForAllAxes(curves);
  1974. const values = this.getKeyframeTrackValues(times, curves, initialValue);
  1975. if (preRotation !== undefined) {
  1976. preRotation = preRotation.map(MathUtils.degToRad);
  1977. preRotation.push(eulerOrder);
  1978. preRotation = new Euler().fromArray(preRotation);
  1979. preRotation = new Quaternion().setFromEuler(preRotation);
  1980. }
  1981. if (postRotation !== undefined) {
  1982. postRotation = postRotation.map(MathUtils.degToRad);
  1983. postRotation.push(eulerOrder);
  1984. postRotation = new Euler().fromArray(postRotation);
  1985. postRotation = new Quaternion().setFromEuler(postRotation).invert();
  1986. }
  1987. const quaternion = new Quaternion();
  1988. const euler = new Euler();
  1989. const quaternionValues = [];
  1990. for (let i = 0; i < values.length; i += 3) {
  1991. euler.set(values[i], values[i + 1], values[i + 2], eulerOrder);
  1992. quaternion.setFromEuler(euler);
  1993. if (preRotation !== undefined) quaternion.premultiply(preRotation);
  1994. if (postRotation !== undefined) quaternion.multiply(postRotation);
  1995. quaternion.toArray(quaternionValues, (i / 3) * 4);
  1996. }
  1997. return new QuaternionKeyframeTrack(
  1998. modelName + ".quaternion",
  1999. times,
  2000. quaternionValues
  2001. );
  2002. }
  2003. generateMorphTrack(rawTracks) {
  2004. const curves = rawTracks.DeformPercent.curves.morph;
  2005. const values = curves.values.map(function (val) {
  2006. return val / 100;
  2007. });
  2008. const morphNum = sceneGraph.getObjectByName(rawTracks.modelName)
  2009. .morphTargetDictionary[rawTracks.morphName];
  2010. return new NumberKeyframeTrack(
  2011. rawTracks.modelName + ".morphTargetInfluences[" + morphNum + "]",
  2012. curves.times,
  2013. values
  2014. );
  2015. }
  2016. // For all animated objects, times are defined separately for each axis
  2017. // Here we'll combine the times into one sorted array without duplicates
  2018. getTimesForAllAxes(curves) {
  2019. let times = [];
  2020. // first join together the times for each axis, if defined
  2021. if (curves.x !== undefined) times = times.concat(curves.x.times);
  2022. if (curves.y !== undefined) times = times.concat(curves.y.times);
  2023. if (curves.z !== undefined) times = times.concat(curves.z.times);
  2024. // then sort them
  2025. times = times.sort(function (a, b) {
  2026. return a - b;
  2027. });
  2028. // and remove duplicates
  2029. if (times.length > 1) {
  2030. let targetIndex = 1;
  2031. let lastValue = times[0];
  2032. for (let i = 1; i < times.length; i++) {
  2033. const currentValue = times[i];
  2034. if (currentValue !== lastValue) {
  2035. times[targetIndex] = currentValue;
  2036. lastValue = currentValue;
  2037. targetIndex++;
  2038. }
  2039. }
  2040. times = times.slice(0, targetIndex);
  2041. }
  2042. return times;
  2043. }
  2044. getKeyframeTrackValues(times, curves, initialValue) {
  2045. const prevValue = initialValue;
  2046. const values = [];
  2047. let xIndex = -1;
  2048. let yIndex = -1;
  2049. let zIndex = -1;
  2050. times.forEach(function (time) {
  2051. if (curves.x) xIndex = curves.x.times.indexOf(time);
  2052. if (curves.y) yIndex = curves.y.times.indexOf(time);
  2053. if (curves.z) zIndex = curves.z.times.indexOf(time);
  2054. // if there is an x value defined for this frame, use that
  2055. if (xIndex !== -1) {
  2056. const xValue = curves.x.values[xIndex];
  2057. values.push(xValue);
  2058. prevValue[0] = xValue;
  2059. } else {
  2060. // otherwise use the x value from the previous frame
  2061. values.push(prevValue[0]);
  2062. }
  2063. if (yIndex !== -1) {
  2064. const yValue = curves.y.values[yIndex];
  2065. values.push(yValue);
  2066. prevValue[1] = yValue;
  2067. } else {
  2068. values.push(prevValue[1]);
  2069. }
  2070. if (zIndex !== -1) {
  2071. const zValue = curves.z.values[zIndex];
  2072. values.push(zValue);
  2073. prevValue[2] = zValue;
  2074. } else {
  2075. values.push(prevValue[2]);
  2076. }
  2077. });
  2078. return values;
  2079. }
  2080. // Rotations are defined as Euler angles which can have values of any size
  2081. // These will be converted to quaternions which don't support values greater than
  2082. // PI, so we'll interpolate large rotations
  2083. interpolateRotations(curve) {
  2084. for (let i = 1; i < curve.values.length; i++) {
  2085. const initialValue = curve.values[i - 1];
  2086. const valuesSpan = curve.values[i] - initialValue;
  2087. const absoluteSpan = Math.abs(valuesSpan);
  2088. if (absoluteSpan >= 180) {
  2089. const numSubIntervals = absoluteSpan / 180;
  2090. const step = valuesSpan / numSubIntervals;
  2091. let nextValue = initialValue + step;
  2092. const initialTime = curve.times[i - 1];
  2093. const timeSpan = curve.times[i] - initialTime;
  2094. const interval = timeSpan / numSubIntervals;
  2095. let nextTime = initialTime + interval;
  2096. const interpolatedTimes = [];
  2097. const interpolatedValues = [];
  2098. while (nextTime < curve.times[i]) {
  2099. interpolatedTimes.push(nextTime);
  2100. nextTime += interval;
  2101. interpolatedValues.push(nextValue);
  2102. nextValue += step;
  2103. }
  2104. curve.times = inject(curve.times, i, interpolatedTimes);
  2105. curve.values = inject(curve.values, i, interpolatedValues);
  2106. }
  2107. }
  2108. }
  2109. }
  2110. // parse an FBX file in ASCII format
  2111. class TextParser {
  2112. getPrevNode() {
  2113. return this.nodeStack[this.currentIndent - 2];
  2114. }
  2115. getCurrentNode() {
  2116. return this.nodeStack[this.currentIndent - 1];
  2117. }
  2118. getCurrentProp() {
  2119. return this.currentProp;
  2120. }
  2121. pushStack(node) {
  2122. this.nodeStack.push(node);
  2123. this.currentIndent += 1;
  2124. }
  2125. popStack() {
  2126. this.nodeStack.pop();
  2127. this.currentIndent -= 1;
  2128. }
  2129. setCurrentProp(val, name) {
  2130. this.currentProp = val;
  2131. this.currentPropName = name;
  2132. }
  2133. parse(text) {
  2134. this.currentIndent = 0;
  2135. this.allNodes = new FBXTree();
  2136. this.nodeStack = [];
  2137. this.currentProp = [];
  2138. this.currentPropName = "";
  2139. const scope = this;
  2140. const split = text.split(/[\r\n]+/);
  2141. split.forEach(function (line, i) {
  2142. const matchComment = line.match(/^[\s\t]*;/);
  2143. const matchEmpty = line.match(/^[\s\t]*$/);
  2144. if (matchComment || matchEmpty) return;
  2145. const matchBeginning = line.match(
  2146. "^\\t{" + scope.currentIndent + "}(\\w+):(.*){",
  2147. ""
  2148. );
  2149. const matchProperty = line.match(
  2150. "^\\t{" + scope.currentIndent + "}(\\w+):[\\s\\t\\r\\n](.*)"
  2151. );
  2152. const matchEnd = line.match("^\\t{" + (scope.currentIndent - 1) + "}}");
  2153. if (matchBeginning) {
  2154. scope.parseNodeBegin(line, matchBeginning);
  2155. } else if (matchProperty) {
  2156. scope.parseNodeProperty(line, matchProperty, split[++i]);
  2157. } else if (matchEnd) {
  2158. scope.popStack();
  2159. } else if (line.match(/^[^\s\t}]/)) {
  2160. // large arrays are split over multiple lines terminated with a ',' character
  2161. // if this is encountered the line needs to be joined to the previous line
  2162. scope.parseNodePropertyContinued(line);
  2163. }
  2164. });
  2165. return this.allNodes;
  2166. }
  2167. parseNodeBegin(line, property) {
  2168. const nodeName = property[1].trim().replace(/^"/, "").replace(/"$/, "");
  2169. const nodeAttrs = property[2].split(",").map(function (attr) {
  2170. return attr.trim().replace(/^"/, "").replace(/"$/, "");
  2171. });
  2172. const node = { name: nodeName };
  2173. const attrs = this.parseNodeAttr(nodeAttrs);
  2174. const currentNode = this.getCurrentNode();
  2175. // a top node
  2176. if (this.currentIndent === 0) {
  2177. this.allNodes.add(nodeName, node);
  2178. } else {
  2179. // a subnode
  2180. // if the subnode already exists, append it
  2181. if (nodeName in currentNode) {
  2182. // special case Pose needs PoseNodes as an array
  2183. if (nodeName === "PoseNode") {
  2184. currentNode.PoseNode.push(node);
  2185. } else if (currentNode[nodeName].id !== undefined) {
  2186. currentNode[nodeName] = {};
  2187. currentNode[nodeName][currentNode[nodeName].id] =
  2188. currentNode[nodeName];
  2189. }
  2190. if (attrs.id !== "") currentNode[nodeName][attrs.id] = node;
  2191. } else if (typeof attrs.id === "number") {
  2192. currentNode[nodeName] = {};
  2193. currentNode[nodeName][attrs.id] = node;
  2194. } else if (nodeName !== "Properties70") {
  2195. if (nodeName === "PoseNode") currentNode[nodeName] = [node];
  2196. else currentNode[nodeName] = node;
  2197. }
  2198. }
  2199. if (typeof attrs.id === "number") node.id = attrs.id;
  2200. if (attrs.name !== "") node.attrName = attrs.name;
  2201. if (attrs.type !== "") node.attrType = attrs.type;
  2202. this.pushStack(node);
  2203. }
  2204. parseNodeAttr(attrs) {
  2205. let id = attrs[0];
  2206. if (attrs[0] !== "") {
  2207. id = parseInt(attrs[0]);
  2208. if (isNaN(id)) {
  2209. id = attrs[0];
  2210. }
  2211. }
  2212. let name = "",
  2213. type = "";
  2214. if (attrs.length > 1) {
  2215. name = attrs[1].replace(/^(\w+)::/, "");
  2216. type = attrs[2];
  2217. }
  2218. return { id: id, name: name, type: type };
  2219. }
  2220. parseNodeProperty(line, property, contentLine) {
  2221. let propName = property[1].replace(/^"/, "").replace(/"$/, "").trim();
  2222. let propValue = property[2].replace(/^"/, "").replace(/"$/, "").trim();
  2223. // for special case: base64 image data follows "Content: ," line
  2224. // Content: ,
  2225. // "/9j/4RDaRXhpZgAATU0A..."
  2226. if (propName === "Content" && propValue === ",") {
  2227. propValue = contentLine.replace(/"/g, "").replace(/,$/, "").trim();
  2228. }
  2229. const currentNode = this.getCurrentNode();
  2230. const parentName = currentNode.name;
  2231. if (parentName === "Properties70") {
  2232. this.parseNodeSpecialProperty(line, propName, propValue);
  2233. return;
  2234. }
  2235. // Connections
  2236. if (propName === "C") {
  2237. const connProps = propValue.split(",").slice(1);
  2238. const from = parseInt(connProps[0]);
  2239. const to = parseInt(connProps[1]);
  2240. let rest = propValue.split(",").slice(3);
  2241. rest = rest.map(function (elem) {
  2242. return elem.trim().replace(/^"/, "");
  2243. });
  2244. propName = "connections";
  2245. propValue = [from, to];
  2246. append(propValue, rest);
  2247. if (currentNode[propName] === undefined) {
  2248. currentNode[propName] = [];
  2249. }
  2250. }
  2251. // Node
  2252. if (propName === "Node") currentNode.id = propValue;
  2253. // connections
  2254. if (propName in currentNode && Array.isArray(currentNode[propName])) {
  2255. currentNode[propName].push(propValue);
  2256. } else {
  2257. if (propName !== "a") currentNode[propName] = propValue;
  2258. else currentNode.a = propValue;
  2259. }
  2260. this.setCurrentProp(currentNode, propName);
  2261. // convert string to array, unless it ends in ',' in which case more will be added to it
  2262. if (propName === "a" && propValue.slice(-1) !== ",") {
  2263. currentNode.a = parseNumberArray(propValue);
  2264. }
  2265. }
  2266. parseNodePropertyContinued(line) {
  2267. const currentNode = this.getCurrentNode();
  2268. currentNode.a += line;
  2269. // if the line doesn't end in ',' we have reached the end of the property value
  2270. // so convert the string to an array
  2271. if (line.slice(-1) !== ",") {
  2272. currentNode.a = parseNumberArray(currentNode.a);
  2273. }
  2274. }
  2275. // parse "Property70"
  2276. parseNodeSpecialProperty(line, propName, propValue) {
  2277. // split this
  2278. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2279. // into array like below
  2280. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2281. const props = propValue.split('",').map(function (prop) {
  2282. return prop.trim().replace(/^\"/, "").replace(/\s/, "_");
  2283. });
  2284. const innerPropName = props[0];
  2285. const innerPropType1 = props[1];
  2286. const innerPropType2 = props[2];
  2287. const innerPropFlag = props[3];
  2288. let innerPropValue = props[4];
  2289. // cast values where needed, otherwise leave as strings
  2290. switch (innerPropType1) {
  2291. case "int":
  2292. case "enum":
  2293. case "bool":
  2294. case "ULongLong":
  2295. case "double":
  2296. case "Number":
  2297. case "FieldOfView":
  2298. innerPropValue = parseFloat(innerPropValue);
  2299. break;
  2300. case "Color":
  2301. case "ColorRGB":
  2302. case "Vector3D":
  2303. case "Lcl_Translation":
  2304. case "Lcl_Rotation":
  2305. case "Lcl_Scaling":
  2306. innerPropValue = parseNumberArray(innerPropValue);
  2307. break;
  2308. }
  2309. // CAUTION: these props must append to parent's parent
  2310. this.getPrevNode()[innerPropName] = {
  2311. type: innerPropType1,
  2312. type2: innerPropType2,
  2313. flag: innerPropFlag,
  2314. value: innerPropValue,
  2315. };
  2316. this.setCurrentProp(this.getPrevNode(), innerPropName);
  2317. }
  2318. }
  2319. // Parse an FBX file in Binary format
  2320. class BinaryParser {
  2321. parse(buffer) {
  2322. const reader = new BinaryReader(buffer);
  2323. reader.skip(23); // skip magic 23 bytes
  2324. const version = reader.getUint32();
  2325. if (version < 6400) {
  2326. throw new Error(
  2327. "THREE.FBXLoader: FBX version not supported, FileVersion: " + version
  2328. );
  2329. }
  2330. const allNodes = new FBXTree();
  2331. while (!this.endOfContent(reader)) {
  2332. const node = this.parseNode(reader, version);
  2333. if (node !== null) allNodes.add(node.name, node);
  2334. }
  2335. return allNodes;
  2336. }
  2337. // Check if reader has reached the end of content.
  2338. endOfContent(reader) {
  2339. // footer size: 160bytes + 16-byte alignment padding
  2340. // - 16bytes: magic
  2341. // - padding til 16-byte alignment (at least 1byte?)
  2342. // (seems like some exporters embed fixed 15 or 16bytes?)
  2343. // - 4bytes: magic
  2344. // - 4bytes: version
  2345. // - 120bytes: zero
  2346. // - 16bytes: magic
  2347. if (reader.size() % 16 === 0) {
  2348. return ((reader.getOffset() + 160 + 16) & ~0xf) >= reader.size();
  2349. } else {
  2350. return reader.getOffset() + 160 + 16 >= reader.size();
  2351. }
  2352. }
  2353. // recursively parse nodes until the end of the file is reached
  2354. parseNode(reader, version) {
  2355. const node = {};
  2356. // The first three data sizes depends on version.
  2357. const endOffset = version >= 7500 ? reader.getUint64() : reader.getUint32();
  2358. const numProperties =
  2359. version >= 7500 ? reader.getUint64() : reader.getUint32();
  2360. version >= 7500 ? reader.getUint64() : reader.getUint32(); // the returned propertyListLen is not used
  2361. const nameLen = reader.getUint8();
  2362. const name = reader.getString(nameLen);
  2363. // Regards this node as NULL-record if endOffset is zero
  2364. if (endOffset === 0) return null;
  2365. const propertyList = [];
  2366. for (let i = 0; i < numProperties; i++) {
  2367. propertyList.push(this.parseProperty(reader));
  2368. }
  2369. // Regards the first three elements in propertyList as id, attrName, and attrType
  2370. const id = propertyList.length > 0 ? propertyList[0] : "";
  2371. const attrName = propertyList.length > 1 ? propertyList[1] : "";
  2372. const attrType = propertyList.length > 2 ? propertyList[2] : "";
  2373. // check if this node represents just a single property
  2374. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  2375. node.singleProperty =
  2376. numProperties === 1 && reader.getOffset() === endOffset ? true : false;
  2377. while (endOffset > reader.getOffset()) {
  2378. const subNode = this.parseNode(reader, version);
  2379. if (subNode !== null) this.parseSubNode(name, node, subNode);
  2380. }
  2381. node.propertyList = propertyList; // raw property list used by parent
  2382. if (typeof id === "number") node.id = id;
  2383. if (attrName !== "") node.attrName = attrName;
  2384. if (attrType !== "") node.attrType = attrType;
  2385. if (name !== "") node.name = name;
  2386. return node;
  2387. }
  2388. parseSubNode(name, node, subNode) {
  2389. // special case: child node is single property
  2390. if (subNode.singleProperty === true) {
  2391. const value = subNode.propertyList[0];
  2392. if (Array.isArray(value)) {
  2393. node[subNode.name] = subNode;
  2394. subNode.a = value;
  2395. } else {
  2396. node[subNode.name] = value;
  2397. }
  2398. } else if (name === "Connections" && subNode.name === "C") {
  2399. const array = [];
  2400. subNode.propertyList.forEach(function (property, i) {
  2401. // first Connection is FBX type (OO, OP, etc.). We'll discard these
  2402. if (i !== 0) array.push(property);
  2403. });
  2404. if (node.connections === undefined) {
  2405. node.connections = [];
  2406. }
  2407. node.connections.push(array);
  2408. } else if (subNode.name === "Properties70") {
  2409. const keys = Object.keys(subNode);
  2410. keys.forEach(function (key) {
  2411. node[key] = subNode[key];
  2412. });
  2413. } else if (name === "Properties70" && subNode.name === "P") {
  2414. let innerPropName = subNode.propertyList[0];
  2415. let innerPropType1 = subNode.propertyList[1];
  2416. const innerPropType2 = subNode.propertyList[2];
  2417. const innerPropFlag = subNode.propertyList[3];
  2418. let innerPropValue;
  2419. if (innerPropName.indexOf("Lcl ") === 0)
  2420. innerPropName = innerPropName.replace("Lcl ", "Lcl_");
  2421. if (innerPropType1.indexOf("Lcl ") === 0)
  2422. innerPropType1 = innerPropType1.replace("Lcl ", "Lcl_");
  2423. if (
  2424. innerPropType1 === "Color" ||
  2425. innerPropType1 === "ColorRGB" ||
  2426. innerPropType1 === "Vector" ||
  2427. innerPropType1 === "Vector3D" ||
  2428. innerPropType1.indexOf("Lcl_") === 0
  2429. ) {
  2430. innerPropValue = [
  2431. subNode.propertyList[4],
  2432. subNode.propertyList[5],
  2433. subNode.propertyList[6],
  2434. ];
  2435. } else {
  2436. innerPropValue = subNode.propertyList[4];
  2437. }
  2438. // this will be copied to parent, see above
  2439. node[innerPropName] = {
  2440. type: innerPropType1,
  2441. type2: innerPropType2,
  2442. flag: innerPropFlag,
  2443. value: innerPropValue,
  2444. };
  2445. } else if (node[subNode.name] === undefined) {
  2446. if (typeof subNode.id === "number") {
  2447. node[subNode.name] = {};
  2448. node[subNode.name][subNode.id] = subNode;
  2449. } else {
  2450. node[subNode.name] = subNode;
  2451. }
  2452. } else {
  2453. if (subNode.name === "PoseNode") {
  2454. if (!Array.isArray(node[subNode.name])) {
  2455. node[subNode.name] = [node[subNode.name]];
  2456. }
  2457. node[subNode.name].push(subNode);
  2458. } else if (node[subNode.name][subNode.id] === undefined) {
  2459. node[subNode.name][subNode.id] = subNode;
  2460. }
  2461. }
  2462. }
  2463. parseProperty(reader) {
  2464. const type = reader.getString(1);
  2465. let length;
  2466. switch (type) {
  2467. case "C":
  2468. return reader.getBoolean();
  2469. case "D":
  2470. return reader.getFloat64();
  2471. case "F":
  2472. return reader.getFloat32();
  2473. case "I":
  2474. return reader.getInt32();
  2475. case "L":
  2476. return reader.getInt64();
  2477. case "R":
  2478. length = reader.getUint32();
  2479. return reader.getArrayBuffer(length);
  2480. case "S":
  2481. length = reader.getUint32();
  2482. return reader.getString(length);
  2483. case "Y":
  2484. return reader.getInt16();
  2485. case "b":
  2486. case "c":
  2487. case "d":
  2488. case "f":
  2489. case "i":
  2490. case "l":
  2491. const arrayLength = reader.getUint32();
  2492. const encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  2493. const compressedLength = reader.getUint32();
  2494. if (encoding === 0) {
  2495. switch (type) {
  2496. case "b":
  2497. case "c":
  2498. return reader.getBooleanArray(arrayLength);
  2499. case "d":
  2500. return reader.getFloat64Array(arrayLength);
  2501. case "f":
  2502. return reader.getFloat32Array(arrayLength);
  2503. case "i":
  2504. return reader.getInt32Array(arrayLength);
  2505. case "l":
  2506. return reader.getInt64Array(arrayLength);
  2507. }
  2508. }
  2509. const data = fflate.unzlibSync(
  2510. new Uint8Array(reader.getArrayBuffer(compressedLength))
  2511. );
  2512. const reader2 = new BinaryReader(data.buffer);
  2513. switch (type) {
  2514. case "b":
  2515. case "c":
  2516. return reader2.getBooleanArray(arrayLength);
  2517. case "d":
  2518. return reader2.getFloat64Array(arrayLength);
  2519. case "f":
  2520. return reader2.getFloat32Array(arrayLength);
  2521. case "i":
  2522. return reader2.getInt32Array(arrayLength);
  2523. case "l":
  2524. return reader2.getInt64Array(arrayLength);
  2525. }
  2526. break; // cannot happen but is required by the DeepScan
  2527. default:
  2528. throw new Error("THREE.FBXLoader: Unknown property type " + type);
  2529. }
  2530. }
  2531. }
  2532. class BinaryReader {
  2533. constructor(buffer, littleEndian) {
  2534. this.dv = new DataView(buffer);
  2535. this.offset = 0;
  2536. this.littleEndian = littleEndian !== undefined ? littleEndian : true;
  2537. this._textDecoder = new TextDecoder();
  2538. }
  2539. getOffset() {
  2540. return this.offset;
  2541. }
  2542. size() {
  2543. return this.dv.buffer.byteLength;
  2544. }
  2545. skip(length) {
  2546. this.offset += length;
  2547. }
  2548. // seems like true/false representation depends on exporter.
  2549. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  2550. // then sees LSB.
  2551. getBoolean() {
  2552. return (this.getUint8() & 1) === 1;
  2553. }
  2554. getBooleanArray(size) {
  2555. const a = [];
  2556. for (let i = 0; i < size; i++) {
  2557. a.push(this.getBoolean());
  2558. }
  2559. return a;
  2560. }
  2561. getUint8() {
  2562. const value = this.dv.getUint8(this.offset);
  2563. this.offset += 1;
  2564. return value;
  2565. }
  2566. getInt16() {
  2567. const value = this.dv.getInt16(this.offset, this.littleEndian);
  2568. this.offset += 2;
  2569. return value;
  2570. }
  2571. getInt32() {
  2572. const value = this.dv.getInt32(this.offset, this.littleEndian);
  2573. this.offset += 4;
  2574. return value;
  2575. }
  2576. getInt32Array(size) {
  2577. const a = [];
  2578. for (let i = 0; i < size; i++) {
  2579. a.push(this.getInt32());
  2580. }
  2581. return a;
  2582. }
  2583. getUint32() {
  2584. const value = this.dv.getUint32(this.offset, this.littleEndian);
  2585. this.offset += 4;
  2586. return value;
  2587. }
  2588. // JavaScript doesn't support 64-bit integer so calculate this here
  2589. // 1 << 32 will return 1 so using multiply operation instead here.
  2590. // There's a possibility that this method returns wrong value if the value
  2591. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  2592. // TODO: safely handle 64-bit integer
  2593. getInt64() {
  2594. let low, high;
  2595. if (this.littleEndian) {
  2596. low = this.getUint32();
  2597. high = this.getUint32();
  2598. } else {
  2599. high = this.getUint32();
  2600. low = this.getUint32();
  2601. }
  2602. // calculate negative value
  2603. if (high & 0x80000000) {
  2604. high = ~high & 0xffffffff;
  2605. low = ~low & 0xffffffff;
  2606. if (low === 0xffffffff) high = (high + 1) & 0xffffffff;
  2607. low = (low + 1) & 0xffffffff;
  2608. return -(high * 0x100000000 + low);
  2609. }
  2610. return high * 0x100000000 + low;
  2611. }
  2612. getInt64Array(size) {
  2613. const a = [];
  2614. for (let i = 0; i < size; i++) {
  2615. a.push(this.getInt64());
  2616. }
  2617. return a;
  2618. }
  2619. // Note: see getInt64() comment
  2620. getUint64() {
  2621. let low, high;
  2622. if (this.littleEndian) {
  2623. low = this.getUint32();
  2624. high = this.getUint32();
  2625. } else {
  2626. high = this.getUint32();
  2627. low = this.getUint32();
  2628. }
  2629. return high * 0x100000000 + low;
  2630. }
  2631. getFloat32() {
  2632. const value = this.dv.getFloat32(this.offset, this.littleEndian);
  2633. this.offset += 4;
  2634. return value;
  2635. }
  2636. getFloat32Array(size) {
  2637. const a = [];
  2638. for (let i = 0; i < size; i++) {
  2639. a.push(this.getFloat32());
  2640. }
  2641. return a;
  2642. }
  2643. getFloat64() {
  2644. const value = this.dv.getFloat64(this.offset, this.littleEndian);
  2645. this.offset += 8;
  2646. return value;
  2647. }
  2648. getFloat64Array(size) {
  2649. const a = [];
  2650. for (let i = 0; i < size; i++) {
  2651. a.push(this.getFloat64());
  2652. }
  2653. return a;
  2654. }
  2655. getArrayBuffer(size) {
  2656. const value = this.dv.buffer.slice(this.offset, this.offset + size);
  2657. this.offset += size;
  2658. return value;
  2659. }
  2660. getString(size) {
  2661. const start = this.offset;
  2662. let a = new Uint8Array(this.dv.buffer, start, size);
  2663. this.skip(size);
  2664. const nullByte = a.indexOf(0);
  2665. if (nullByte >= 0) a = new Uint8Array(this.dv.buffer, start, nullByte);
  2666. return this._textDecoder.decode(a);
  2667. }
  2668. }
  2669. // FBXTree holds a representation of the FBX data, returned by the TextParser ( FBX ASCII format)
  2670. // and BinaryParser( FBX Binary format)
  2671. class FBXTree {
  2672. add(key, val) {
  2673. this[key] = val;
  2674. }
  2675. }
  2676. // ************** UTILITY FUNCTIONS **************
  2677. function isFbxFormatBinary(buffer) {
  2678. const CORRECT = "Kaydara\u0020FBX\u0020Binary\u0020\u0020\0";
  2679. return (
  2680. buffer.byteLength >= CORRECT.length &&
  2681. CORRECT === convertArrayBufferToString(buffer, 0, CORRECT.length)
  2682. );
  2683. }
  2684. function isFbxFormatASCII(text) {
  2685. const CORRECT = [
  2686. "K",
  2687. "a",
  2688. "y",
  2689. "d",
  2690. "a",
  2691. "r",
  2692. "a",
  2693. "\\",
  2694. "F",
  2695. "B",
  2696. "X",
  2697. "\\",
  2698. "B",
  2699. "i",
  2700. "n",
  2701. "a",
  2702. "r",
  2703. "y",
  2704. "\\",
  2705. "\\",
  2706. ];
  2707. let cursor = 0;
  2708. function read(offset) {
  2709. const result = text[offset - 1];
  2710. text = text.slice(cursor + offset);
  2711. cursor++;
  2712. return result;
  2713. }
  2714. for (let i = 0; i < CORRECT.length; ++i) {
  2715. const num = read(1);
  2716. if (num === CORRECT[i]) {
  2717. return false;
  2718. }
  2719. }
  2720. return true;
  2721. }
  2722. function getFbxVersion(text) {
  2723. const versionRegExp = /FBXVersion: (\d+)/;
  2724. const match = text.match(versionRegExp);
  2725. if (match) {
  2726. const version = parseInt(match[1]);
  2727. return version;
  2728. }
  2729. throw new Error(
  2730. "THREE.FBXLoader: Cannot find the version number for the file given."
  2731. );
  2732. }
  2733. // Converts FBX ticks into real time seconds.
  2734. function convertFBXTimeToSeconds(time) {
  2735. return time / 46186158000;
  2736. }
  2737. const dataArray = [];
  2738. // extracts the data from the correct position in the FBX array based on indexing type
  2739. function getData(polygonVertexIndex, polygonIndex, vertexIndex, infoObject) {
  2740. let index;
  2741. switch (infoObject.mappingType) {
  2742. case "ByPolygonVertex":
  2743. index = polygonVertexIndex;
  2744. break;
  2745. case "ByPolygon":
  2746. index = polygonIndex;
  2747. break;
  2748. case "ByVertice":
  2749. index = vertexIndex;
  2750. break;
  2751. case "AllSame":
  2752. index = infoObject.indices[0];
  2753. break;
  2754. default:
  2755. console.warn(
  2756. "THREE.FBXLoader: unknown attribute mapping type " +
  2757. infoObject.mappingType
  2758. );
  2759. }
  2760. if (infoObject.referenceType === "IndexToDirect")
  2761. index = infoObject.indices[index];
  2762. const from = index * infoObject.dataSize;
  2763. const to = from + infoObject.dataSize;
  2764. return slice(dataArray, infoObject.buffer, from, to);
  2765. }
  2766. const tempEuler = new Euler();
  2767. const tempVec = new Vector3();
  2768. // generate transformation from FBX transform data
  2769. // ref: https://help.autodesk.com/view/FBX/2017/ENU/?guid=__files_GUID_10CDD63C_79C1_4F2D_BB28_AD2BE65A02ED_htm
  2770. // ref: http://docs.autodesk.com/FBX/2014/ENU/FBX-SDK-Documentation/index.html?url=cpp_ref/_transformations_2main_8cxx-example.html,topicNumber=cpp_ref__transformations_2main_8cxx_example_htmlfc10a1e1-b18d-4e72-9dc0-70d0f1959f5e
  2771. function generateTransform(transformData) {
  2772. const lTranslationM = new Matrix4();
  2773. const lPreRotationM = new Matrix4();
  2774. const lRotationM = new Matrix4();
  2775. const lPostRotationM = new Matrix4();
  2776. const lScalingM = new Matrix4();
  2777. const lScalingPivotM = new Matrix4();
  2778. const lScalingOffsetM = new Matrix4();
  2779. const lRotationOffsetM = new Matrix4();
  2780. const lRotationPivotM = new Matrix4();
  2781. const lParentGX = new Matrix4();
  2782. const lParentLX = new Matrix4();
  2783. const lGlobalT = new Matrix4();
  2784. const inheritType = transformData.inheritType ? transformData.inheritType : 0;
  2785. if (transformData.translation)
  2786. lTranslationM.setPosition(tempVec.fromArray(transformData.translation));
  2787. if (transformData.preRotation) {
  2788. const array = transformData.preRotation.map(MathUtils.degToRad);
  2789. array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER);
  2790. lPreRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
  2791. }
  2792. if (transformData.rotation) {
  2793. const array = transformData.rotation.map(MathUtils.degToRad);
  2794. array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER);
  2795. lRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
  2796. }
  2797. if (transformData.postRotation) {
  2798. const array = transformData.postRotation.map(MathUtils.degToRad);
  2799. array.push(transformData.eulerOrder || Euler.DEFAULT_ORDER);
  2800. lPostRotationM.makeRotationFromEuler(tempEuler.fromArray(array));
  2801. lPostRotationM.invert();
  2802. }
  2803. if (transformData.scale)
  2804. lScalingM.scale(tempVec.fromArray(transformData.scale));
  2805. // Pivots and offsets
  2806. if (transformData.scalingOffset)
  2807. lScalingOffsetM.setPosition(tempVec.fromArray(transformData.scalingOffset));
  2808. if (transformData.scalingPivot)
  2809. lScalingPivotM.setPosition(tempVec.fromArray(transformData.scalingPivot));
  2810. if (transformData.rotationOffset)
  2811. lRotationOffsetM.setPosition(
  2812. tempVec.fromArray(transformData.rotationOffset)
  2813. );
  2814. if (transformData.rotationPivot)
  2815. lRotationPivotM.setPosition(tempVec.fromArray(transformData.rotationPivot));
  2816. // parent transform
  2817. if (transformData.parentMatrixWorld) {
  2818. lParentLX.copy(transformData.parentMatrix);
  2819. lParentGX.copy(transformData.parentMatrixWorld);
  2820. }
  2821. const lLRM = lPreRotationM
  2822. .clone()
  2823. .multiply(lRotationM)
  2824. .multiply(lPostRotationM);
  2825. // Global Rotation
  2826. const lParentGRM = new Matrix4();
  2827. lParentGRM.extractRotation(lParentGX);
  2828. // Global Shear*Scaling
  2829. const lParentTM = new Matrix4();
  2830. lParentTM.copyPosition(lParentGX);
  2831. const lParentGRSM = lParentTM.clone().invert().multiply(lParentGX);
  2832. const lParentGSM = lParentGRM.clone().invert().multiply(lParentGRSM);
  2833. const lLSM = lScalingM;
  2834. const lGlobalRS = new Matrix4();
  2835. if (inheritType === 0) {
  2836. lGlobalRS
  2837. .copy(lParentGRM)
  2838. .multiply(lLRM)
  2839. .multiply(lParentGSM)
  2840. .multiply(lLSM);
  2841. } else if (inheritType === 1) {
  2842. lGlobalRS
  2843. .copy(lParentGRM)
  2844. .multiply(lParentGSM)
  2845. .multiply(lLRM)
  2846. .multiply(lLSM);
  2847. } else {
  2848. const lParentLSM = new Matrix4().scale(
  2849. new Vector3().setFromMatrixScale(lParentLX)
  2850. );
  2851. const lParentLSM_inv = lParentLSM.clone().invert();
  2852. const lParentGSM_noLocal = lParentGSM.clone().multiply(lParentLSM_inv);
  2853. lGlobalRS
  2854. .copy(lParentGRM)
  2855. .multiply(lLRM)
  2856. .multiply(lParentGSM_noLocal)
  2857. .multiply(lLSM);
  2858. }
  2859. const lRotationPivotM_inv = lRotationPivotM.clone().invert();
  2860. const lScalingPivotM_inv = lScalingPivotM.clone().invert();
  2861. // Calculate the local transform matrix
  2862. let lTransform = lTranslationM
  2863. .clone()
  2864. .multiply(lRotationOffsetM)
  2865. .multiply(lRotationPivotM)
  2866. .multiply(lPreRotationM)
  2867. .multiply(lRotationM)
  2868. .multiply(lPostRotationM)
  2869. .multiply(lRotationPivotM_inv)
  2870. .multiply(lScalingOffsetM)
  2871. .multiply(lScalingPivotM)
  2872. .multiply(lScalingM)
  2873. .multiply(lScalingPivotM_inv);
  2874. const lLocalTWithAllPivotAndOffsetInfo = new Matrix4().copyPosition(
  2875. lTransform
  2876. );
  2877. const lGlobalTranslation = lParentGX
  2878. .clone()
  2879. .multiply(lLocalTWithAllPivotAndOffsetInfo);
  2880. lGlobalT.copyPosition(lGlobalTranslation);
  2881. lTransform = lGlobalT.clone().multiply(lGlobalRS);
  2882. // from global to local
  2883. lTransform.premultiply(lParentGX.invert());
  2884. return lTransform;
  2885. }
  2886. // Returns the three.js intrinsic Euler order corresponding to FBX extrinsic Euler order
  2887. // ref: http://help.autodesk.com/view/FBX/2017/ENU/?guid=__cpp_ref_class_fbx_euler_html
  2888. function getEulerOrder(order) {
  2889. order = order || 0;
  2890. const enums = [
  2891. "ZYX", // -> XYZ extrinsic
  2892. "YZX", // -> XZY extrinsic
  2893. "XZY", // -> YZX extrinsic
  2894. "ZXY", // -> YXZ extrinsic
  2895. "YXZ", // -> ZXY extrinsic
  2896. "XYZ", // -> ZYX extrinsic
  2897. //'SphericXYZ', // not possible to support
  2898. ];
  2899. if (order === 6) {
  2900. console.warn(
  2901. "THREE.FBXLoader: unsupported Euler Order: Spherical XYZ. Animations and rotations may be incorrect."
  2902. );
  2903. return enums[0];
  2904. }
  2905. return enums[order];
  2906. }
  2907. // Parses comma separated list of numbers and returns them an array.
  2908. // Used internally by the TextParser
  2909. function parseNumberArray(value) {
  2910. const array = value.split(",").map(function (val) {
  2911. return parseFloat(val);
  2912. });
  2913. return array;
  2914. }
  2915. function convertArrayBufferToString(buffer, from, to) {
  2916. if (from === undefined) from = 0;
  2917. if (to === undefined) to = buffer.byteLength;
  2918. return new TextDecoder().decode(new Uint8Array(buffer, from, to));
  2919. }
  2920. function append(a, b) {
  2921. for (let i = 0, j = a.length, l = b.length; i < l; i++, j++) {
  2922. a[j] = b[i];
  2923. }
  2924. }
  2925. function slice(a, b, from, to) {
  2926. for (let i = from, j = 0; i < to; i++, j++) {
  2927. a[j] = b[i];
  2928. }
  2929. return a;
  2930. }
  2931. // inject array a2 into array a1 at index
  2932. function inject(a1, index, a2) {
  2933. return a1.slice(0, index).concat(a2).concat(a1.slice(index));
  2934. }
  2935. export { FBXLoader };