FBXLoader.js 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134
  1. /**
  2. * @author Kyle-Larson https://github.com/Kyle-Larson
  3. * @author Takahiro https://github.com/takahirox
  4. *
  5. * Loader loads FBX file and generates Group representing FBX scene.
  6. * Requires FBX file to be >= 7.0 and in ASCII or to be any version in Binary format.
  7. *
  8. * Supports:
  9. * Mesh Generation (Positional Data)
  10. * Normal Data (Per Vertex Drawing Instance)
  11. * UV Data (Per Vertex Drawing Instance)
  12. * Skinning
  13. * Animation
  14. * - Separated Animations based on stacks.
  15. * - Skeletal & Non-Skeletal Animations
  16. * NURBS (Open, Closed and Periodic forms)
  17. *
  18. * Needs Support:
  19. * Indexed Buffers
  20. * PreRotation support.
  21. */
  22. ( function () {
  23. /**
  24. * Generates a loader for loading FBX files from URL and parsing into
  25. * a THREE.Group.
  26. * @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
  27. */
  28. THREE.FBXLoader = function ( manager ) {
  29. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  30. };
  31. Object.assign( THREE.FBXLoader.prototype, {
  32. /**
  33. * Loads an ASCII/Binary FBX file from URL and parses into a THREE.Group.
  34. * THREE.Group will have an animations property of AnimationClips
  35. * of the different animations exported with the FBX.
  36. * @param {string} url - URL of the FBX file.
  37. * @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
  38. * @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
  39. * @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
  40. */
  41. load: function ( url, onLoad, onProgress, onError ) {
  42. var self = this;
  43. var resourceDirectory = THREE.Loader.prototype.extractUrlBase( url );
  44. var loader = new THREE.FileLoader( this.manager );
  45. loader.setResponseType( 'arraybuffer' );
  46. loader.load( url, function ( buffer ) {
  47. try {
  48. var scene = self.parse( buffer, resourceDirectory );
  49. onLoad( scene );
  50. } catch ( error ) {
  51. window.setTimeout( function () {
  52. if ( onError ) onError( error );
  53. self.manager.itemError( url );
  54. }, 0 );
  55. }
  56. }, onProgress, onError );
  57. },
  58. /**
  59. * Parses an ASCII/Binary FBX file and returns a THREE.Group.
  60. * THREE.Group will have an animations property of AnimationClips
  61. * of the different animations within the FBX file.
  62. * @param {ArrayBuffer} FBXBuffer - Contents of FBX file to parse.
  63. * @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
  64. * @returns {THREE.Group}
  65. */
  66. parse: function ( FBXBuffer, resourceDirectory ) {
  67. var FBXTree;
  68. if ( isFbxFormatBinary( FBXBuffer ) ) {
  69. FBXTree = new BinaryParser().parse( FBXBuffer );
  70. } else {
  71. var FBXText = convertArrayBufferToString( FBXBuffer );
  72. if ( ! isFbxFormatASCII( FBXText ) ) {
  73. throw new Error( 'THREE.FBXLoader: Unknown format.' );
  74. }
  75. if ( getFbxVersion( FBXText ) < 7000 ) {
  76. throw new Error( 'THREE.FBXLoader: FBX version not supported, FileVersion: ' + getFbxVersion( FBXText ) );
  77. }
  78. FBXTree = new TextParser().parse( FBXText );
  79. }
  80. // console.log( FBXTree );
  81. var connections = parseConnections( FBXTree );
  82. var images = parseImages( FBXTree );
  83. var textures = parseTextures( FBXTree, new THREE.TextureLoader( this.manager ).setPath( resourceDirectory ), images, connections );
  84. var materials = parseMaterials( FBXTree, textures, connections );
  85. var deformers = parseDeformers( FBXTree, connections );
  86. var geometryMap = parseGeometries( FBXTree, connections, deformers );
  87. var sceneGraph = parseScene( FBXTree, connections, deformers, geometryMap, materials );
  88. return sceneGraph;
  89. }
  90. } );
  91. /**
  92. * Parses map of relationships between objects.
  93. * @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
  94. * @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  95. */
  96. function parseConnections( FBXTree ) {
  97. /**
  98. * @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
  99. */
  100. var connectionMap = new Map();
  101. if ( 'Connections' in FBXTree ) {
  102. /**
  103. * @type {[number, number, string][]}
  104. */
  105. var connectionArray = FBXTree.Connections.properties.connections;
  106. for ( var connectionArrayIndex = 0, connectionArrayLength = connectionArray.length; connectionArrayIndex < connectionArrayLength; ++ connectionArrayIndex ) {
  107. var connection = connectionArray[ connectionArrayIndex ];
  108. if ( ! connectionMap.has( connection[ 0 ] ) ) {
  109. connectionMap.set( connection[ 0 ], {
  110. parents: [],
  111. children: []
  112. } );
  113. }
  114. var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
  115. connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
  116. if ( ! connectionMap.has( connection[ 1 ] ) ) {
  117. connectionMap.set( connection[ 1 ], {
  118. parents: [],
  119. children: []
  120. } );
  121. }
  122. var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
  123. connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
  124. }
  125. }
  126. return connectionMap;
  127. }
  128. /**
  129. * Parses map of images referenced in FBXTree.
  130. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  131. * @returns {Map<number, string(image blob/data URL)>}
  132. */
  133. function parseImages( FBXTree ) {
  134. /**
  135. * @type {Map<number, string(image blob/data URL)>}
  136. */
  137. var imageMap = new Map();
  138. if ( 'Video' in FBXTree.Objects.subNodes ) {
  139. var videoNodes = FBXTree.Objects.subNodes.Video;
  140. for ( var nodeID in videoNodes ) {
  141. var videoNode = videoNodes[ nodeID ];
  142. // raw image data is in videoNode.properties.Content
  143. if ( 'Content' in videoNode.properties ) {
  144. var image = parseImage( videoNodes[ nodeID ] );
  145. imageMap.set( parseInt( nodeID ), image );
  146. }
  147. }
  148. }
  149. return imageMap;
  150. }
  151. /**
  152. * @param {videoNode} videoNode - Node to get texture image information from.
  153. * @returns {string} - image blob/data URL
  154. */
  155. function parseImage( videoNode ) {
  156. var content = videoNode.properties.Content;
  157. var fileName = videoNode.properties.RelativeFilename || videoNode.properties.Filename;
  158. var extension = fileName.slice( fileName.lastIndexOf( '.' ) + 1 ).toLowerCase();
  159. var type;
  160. switch ( extension ) {
  161. case 'bmp':
  162. type = 'image/bmp';
  163. break;
  164. case 'jpg':
  165. type = 'image/jpeg';
  166. break;
  167. case 'png':
  168. type = 'image/png';
  169. break;
  170. case 'tif':
  171. type = 'image/tiff';
  172. break;
  173. default:
  174. console.warn( 'FBXLoader: No support image type ' + extension );
  175. return;
  176. }
  177. if ( typeof content === 'string' ) {
  178. return 'data:' + type + ';base64,' + content;
  179. } else {
  180. var array = new Uint8Array( content );
  181. return window.URL.createObjectURL( new Blob( [ array ], { type: type } ) );
  182. }
  183. }
  184. /**
  185. * Parses map of textures referenced in FBXTree.
  186. * @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
  187. * @param {THREE.TextureLoader} loader
  188. * @param {Map<number, string(image blob/data URL)>} imageMap
  189. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  190. * @returns {Map<number, THREE.Texture>}
  191. */
  192. function parseTextures( FBXTree, loader, imageMap, connections ) {
  193. /**
  194. * @type {Map<number, THREE.Texture>}
  195. */
  196. var textureMap = new Map();
  197. if ( 'Texture' in FBXTree.Objects.subNodes ) {
  198. var textureNodes = FBXTree.Objects.subNodes.Texture;
  199. for ( var nodeID in textureNodes ) {
  200. var texture = parseTexture( textureNodes[ nodeID ], loader, imageMap, connections );
  201. textureMap.set( parseInt( nodeID ), texture );
  202. }
  203. }
  204. return textureMap;
  205. }
  206. /**
  207. * @param {textureNode} textureNode - Node to get texture information from.
  208. * @param {THREE.TextureLoader} loader
  209. * @param {Map<number, string(image blob/data URL)>} imageMap
  210. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  211. * @returns {THREE.Texture}
  212. */
  213. function parseTexture( textureNode, loader, imageMap, connections ) {
  214. var FBX_ID = textureNode.id;
  215. var name = textureNode.name;
  216. var fileName;
  217. var filePath = textureNode.properties.FileName;
  218. var relativeFilePath = textureNode.properties.RelativeFilename;
  219. var children = connections.get( FBX_ID ).children;
  220. if ( children !== undefined && children.length > 0 && imageMap.has( children[ 0 ].ID ) ) {
  221. fileName = imageMap.get( children[ 0 ].ID );
  222. } else if ( relativeFilePath !== undefined && relativeFilePath[ 0 ] !== '/' &&
  223. relativeFilePath.match( /^[a-zA-Z]:/ ) === null ) {
  224. // use textureNode.properties.RelativeFilename
  225. // if it exists and it doesn't seem an absolute path
  226. fileName = relativeFilePath;
  227. } else {
  228. var split = filePath.split( /[\\\/]/ );
  229. if ( split.length > 0 ) {
  230. fileName = split[ split.length - 1 ];
  231. } else {
  232. fileName = filePath;
  233. }
  234. }
  235. var currentPath = loader.path;
  236. if ( fileName.indexOf( 'blob:' ) === 0 || fileName.indexOf( 'data:' ) === 0 ) {
  237. loader.setPath( undefined );
  238. }
  239. /**
  240. * @type {THREE.Texture}
  241. */
  242. var texture = loader.load( fileName );
  243. texture.name = name;
  244. texture.FBX_ID = FBX_ID;
  245. var wrapModeU = textureNode.properties.WrapModeU;
  246. var wrapModeV = textureNode.properties.WrapModeV;
  247. var valueU = wrapModeU !== undefined ? wrapModeU.value : 0;
  248. var valueV = wrapModeV !== undefined ? wrapModeV.value : 0;
  249. // http://download.autodesk.com/us/fbx/SDKdocs/FBX_SDK_Help/files/fbxsdkref/class_k_fbx_texture.html#889640e63e2e681259ea81061b85143a
  250. // 0: repeat(default), 1: clamp
  251. texture.wrapS = valueU === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  252. texture.wrapT = valueV === 0 ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  253. loader.setPath( currentPath );
  254. return texture;
  255. }
  256. /**
  257. * Parses map of Material information.
  258. * @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
  259. * @param {Map<number, THREE.Texture>} textureMap
  260. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  261. * @returns {Map<number, THREE.Material>}
  262. */
  263. function parseMaterials( FBXTree, textureMap, connections ) {
  264. var materialMap = new Map();
  265. if ( 'Material' in FBXTree.Objects.subNodes ) {
  266. var materialNodes = FBXTree.Objects.subNodes.Material;
  267. for ( var nodeID in materialNodes ) {
  268. var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
  269. materialMap.set( parseInt( nodeID ), material );
  270. }
  271. }
  272. return materialMap;
  273. }
  274. /**
  275. * Takes information from Material node and returns a generated THREE.Material
  276. * @param {FBXMaterialNode} materialNode
  277. * @param {Map<number, THREE.Texture>} textureMap
  278. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  279. * @returns {THREE.Material}
  280. */
  281. function parseMaterial( materialNode, textureMap, connections ) {
  282. var FBX_ID = materialNode.id;
  283. var name = materialNode.attrName;
  284. var type = materialNode.properties.ShadingModel;
  285. //Case where FBXs wrap shading model in property object.
  286. if ( typeof type === 'object' ) {
  287. type = type.value;
  288. }
  289. var children = connections.get( FBX_ID ).children;
  290. var parameters = parseParameters( materialNode.properties, textureMap, children );
  291. var material;
  292. switch ( type.toLowerCase() ) {
  293. case 'phong':
  294. material = new THREE.MeshPhongMaterial();
  295. break;
  296. case 'lambert':
  297. material = new THREE.MeshLambertMaterial();
  298. break;
  299. default:
  300. console.warn( 'THREE.FBXLoader: No implementation given for material type %s in FBXLoader.js. Defaulting to basic material.', type );
  301. material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  302. break;
  303. }
  304. material.setValues( parameters );
  305. material.name = name;
  306. return material;
  307. }
  308. /**
  309. * @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
  310. */
  311. /**
  312. * @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
  313. */
  314. /**
  315. * @param {FBXMaterialProperties} properties
  316. * @param {Map<number, THREE.Texture>} textureMap
  317. * @param {{ID: number, relationship: string}[]} childrenRelationships
  318. * @returns {THREEMaterialParameterPack}
  319. */
  320. function parseParameters( properties, textureMap, childrenRelationships ) {
  321. var parameters = {};
  322. if ( properties.Diffuse ) {
  323. parameters.color = parseColor( properties.Diffuse );
  324. }
  325. if ( properties.Specular ) {
  326. parameters.specular = parseColor( properties.Specular );
  327. }
  328. if ( properties.Shininess ) {
  329. parameters.shininess = properties.Shininess.value;
  330. }
  331. if ( properties.Emissive ) {
  332. parameters.emissive = parseColor( properties.Emissive );
  333. }
  334. if ( properties.EmissiveFactor ) {
  335. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  336. }
  337. if ( properties.Opacity ) {
  338. parameters.opacity = properties.Opacity.value;
  339. }
  340. if ( parameters.opacity < 1.0 ) {
  341. parameters.transparent = true;
  342. }
  343. for ( var childrenRelationshipsIndex = 0, childrenRelationshipsLength = childrenRelationships.length; childrenRelationshipsIndex < childrenRelationshipsLength; ++ childrenRelationshipsIndex ) {
  344. var relationship = childrenRelationships[ childrenRelationshipsIndex ];
  345. var type = relationship.relationship;
  346. switch ( type ) {
  347. case 'DiffuseColor':
  348. case ' "DiffuseColor':
  349. parameters.map = textureMap.get( relationship.ID );
  350. break;
  351. case 'Bump':
  352. case ' "Bump':
  353. parameters.bumpMap = textureMap.get( relationship.ID );
  354. break;
  355. case 'NormalMap':
  356. case ' "NormalMap':
  357. parameters.normalMap = textureMap.get( relationship.ID );
  358. break;
  359. case 'AmbientColor':
  360. case 'EmissiveColor':
  361. case ' "AmbientColor':
  362. case ' "EmissiveColor':
  363. default:
  364. console.warn( 'THREE.FBXLoader: Unknown texture application of type %s, skipping texture.', type );
  365. break;
  366. }
  367. }
  368. return parameters;
  369. }
  370. /**
  371. * Generates map of Skeleton-like objects for use later when generating and binding skeletons.
  372. * @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
  373. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  374. * @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
  375. */
  376. function parseDeformers( FBXTree, connections ) {
  377. var deformers = {};
  378. if ( 'Deformer' in FBXTree.Objects.subNodes ) {
  379. var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
  380. for ( var nodeID in DeformerNodes ) {
  381. var deformerNode = DeformerNodes[ nodeID ];
  382. if ( deformerNode.attrType === 'Skin' ) {
  383. var conns = connections.get( parseInt( nodeID ) );
  384. var skeleton = parseSkeleton( conns, DeformerNodes );
  385. skeleton.FBX_ID = parseInt( nodeID );
  386. deformers[ nodeID ] = skeleton;
  387. }
  388. }
  389. }
  390. return deformers;
  391. }
  392. /**
  393. * Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
  394. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
  395. * @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
  396. * @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
  397. */
  398. function parseSkeleton( connections, DeformerNodes ) {
  399. var subDeformers = {};
  400. var children = connections.children;
  401. for ( var i = 0, l = children.length; i < l; ++ i ) {
  402. var child = children[ i ];
  403. var subDeformerNode = DeformerNodes[ child.ID ];
  404. var subDeformer = {
  405. FBX_ID: child.ID,
  406. index: i,
  407. indices: [],
  408. weights: [],
  409. transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
  410. transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
  411. linkMode: subDeformerNode.properties.Mode
  412. };
  413. if ( 'Indexes' in subDeformerNode.subNodes ) {
  414. subDeformer.indices = parseIntArray( subDeformerNode.subNodes.Indexes.properties.a );
  415. subDeformer.weights = parseFloatArray( subDeformerNode.subNodes.Weights.properties.a );
  416. }
  417. subDeformers[ child.ID ] = subDeformer;
  418. }
  419. return {
  420. map: subDeformers,
  421. bones: []
  422. };
  423. }
  424. /**
  425. * Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
  426. * @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
  427. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  428. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  429. * @returns {Map<number, THREE.BufferGeometry>}
  430. */
  431. function parseGeometries( FBXTree, connections, deformers ) {
  432. var geometryMap = new Map();
  433. if ( 'Geometry' in FBXTree.Objects.subNodes ) {
  434. var geometryNodes = FBXTree.Objects.subNodes.Geometry;
  435. for ( var nodeID in geometryNodes ) {
  436. var relationships = connections.get( parseInt( nodeID ) );
  437. var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformers );
  438. geometryMap.set( parseInt( nodeID ), geo );
  439. }
  440. }
  441. return geometryMap;
  442. }
  443. /**
  444. * Generates BufferGeometry from FBXGeometryNode.
  445. * @param {FBXGeometryNode} geometryNode
  446. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  447. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers
  448. * @returns {THREE.BufferGeometry}
  449. */
  450. function parseGeometry( geometryNode, relationships, deformers ) {
  451. switch ( geometryNode.attrType ) {
  452. case 'Mesh':
  453. return parseMeshGeometry( geometryNode, relationships, deformers );
  454. break;
  455. case 'NurbsCurve':
  456. return parseNurbsGeometry( geometryNode );
  457. break;
  458. }
  459. }
  460. /**
  461. * Specialty function for parsing Mesh based Geometry Nodes.
  462. * @param {FBXGeometryNode} geometryNode
  463. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
  464. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformers - Map object of deformers and subDeformers by ID.
  465. * @returns {THREE.BufferGeometry}
  466. */
  467. function parseMeshGeometry( geometryNode, relationships, deformers ) {
  468. for ( var i = 0; i < relationships.children.length; ++ i ) {
  469. var deformer = deformers[ relationships.children[ i ].ID ];
  470. if ( deformer !== undefined ) break;
  471. }
  472. return genGeometry( geometryNode, deformer );
  473. }
  474. /**
  475. * @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance.
  476. * @returns {THREE.BufferGeometry}
  477. */
  478. function genGeometry( geometryNode, deformer ) {
  479. var geometry = new Geometry();
  480. var subNodes = geometryNode.subNodes;
  481. // First, each index is going to be its own vertex.
  482. var vertexBuffer = parseFloatArray( subNodes.Vertices.properties.a );
  483. var indexBuffer = parseIntArray( subNodes.PolygonVertexIndex.properties.a );
  484. if ( subNodes.LayerElementNormal ) {
  485. var normalInfo = getNormals( subNodes.LayerElementNormal[ 0 ] );
  486. }
  487. if ( subNodes.LayerElementUV ) {
  488. var uvInfo = getUVs( subNodes.LayerElementUV[ 0 ] );
  489. }
  490. if ( subNodes.LayerElementColor ) {
  491. var colorInfo = getColors( subNodes.LayerElementColor[ 0 ] );
  492. }
  493. if ( subNodes.LayerElementMaterial ) {
  494. var materialInfo = getMaterials( subNodes.LayerElementMaterial[ 0 ] );
  495. }
  496. var weightTable = {};
  497. if ( deformer ) {
  498. var subDeformers = deformer.map;
  499. for ( var key in subDeformers ) {
  500. var subDeformer = subDeformers[ key ];
  501. var indices = subDeformer.indices;
  502. for ( var j = 0; j < indices.length; j ++ ) {
  503. var index = indices[ j ];
  504. var weight = subDeformer.weights[ j ];
  505. if ( weightTable[ index ] === undefined ) weightTable[ index ] = [];
  506. weightTable[ index ].push( {
  507. id: subDeformer.index,
  508. weight: weight
  509. } );
  510. }
  511. }
  512. }
  513. var faceVertexBuffer = [];
  514. var polygonIndex = 0;
  515. var displayedWeightsWarning = false;
  516. for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; polygonVertexIndex ++ ) {
  517. var vertexIndex = indexBuffer[ polygonVertexIndex ];
  518. var endOfFace = false;
  519. if ( vertexIndex < 0 ) {
  520. vertexIndex = vertexIndex ^ - 1;
  521. indexBuffer[ polygonVertexIndex ] = vertexIndex;
  522. endOfFace = true;
  523. }
  524. var vertex = new Vertex();
  525. var weightIndices = [];
  526. var weights = [];
  527. vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
  528. if ( deformer ) {
  529. if ( weightTable[ vertexIndex ] !== undefined ) {
  530. var array = weightTable[ vertexIndex ];
  531. for ( var j = 0, jl = array.length; j < jl; j ++ ) {
  532. weights.push( array[ j ].weight );
  533. weightIndices.push( array[ j ].id );
  534. }
  535. }
  536. if ( weights.length > 4 ) {
  537. if ( ! displayedWeightsWarning ) {
  538. console.warn( 'THREE.FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
  539. displayedWeightsWarning = true;
  540. }
  541. var WIndex = [ 0, 0, 0, 0 ];
  542. var Weight = [ 0, 0, 0, 0 ];
  543. weights.forEach( function ( weight, weightIndex ) {
  544. var currentWeight = weight;
  545. var currentIndex = weightIndices[ weightIndex ];
  546. Weight.forEach( function ( comparedWeight, comparedWeightIndex, comparedWeightArray ) {
  547. if ( currentWeight > comparedWeight ) {
  548. comparedWeightArray[ comparedWeightIndex ] = currentWeight;
  549. currentWeight = comparedWeight;
  550. var tmp = WIndex[ comparedWeightIndex ];
  551. WIndex[ comparedWeightIndex ] = currentIndex;
  552. currentIndex = tmp;
  553. }
  554. } );
  555. } );
  556. weightIndices = WIndex;
  557. weights = Weight;
  558. }
  559. for ( var i = weights.length; i < 4; ++ i ) {
  560. weights[ i ] = 0;
  561. weightIndices[ i ] = 0;
  562. }
  563. vertex.skinWeights.fromArray( weights );
  564. vertex.skinIndices.fromArray( weightIndices );
  565. }
  566. if ( normalInfo ) {
  567. vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
  568. }
  569. if ( uvInfo ) {
  570. vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) );
  571. }
  572. if ( colorInfo ) {
  573. vertex.color.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, colorInfo ) );
  574. }
  575. faceVertexBuffer.push( vertex );
  576. if ( endOfFace ) {
  577. var face = new Face();
  578. face.genTrianglesFromVertices( faceVertexBuffer );
  579. if ( materialInfo !== undefined ) {
  580. var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
  581. face.materialIndex = materials[ 0 ];
  582. } else {
  583. // Seems like some models don't have materialInfo(subNodes.LayerElementMaterial).
  584. // Set 0 in such a case.
  585. face.materialIndex = 0;
  586. }
  587. geometry.faces.push( face );
  588. faceVertexBuffer = [];
  589. polygonIndex ++;
  590. endOfFace = false;
  591. }
  592. }
  593. /**
  594. * @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  595. */
  596. var bufferInfo = geometry.flattenToBuffers();
  597. var geo = new THREE.BufferGeometry();
  598. geo.name = geometryNode.name;
  599. geo.addAttribute( 'position', new THREE.Float32BufferAttribute( bufferInfo.vertexBuffer, 3 ) );
  600. if ( bufferInfo.normalBuffer.length > 0 ) {
  601. geo.addAttribute( 'normal', new THREE.Float32BufferAttribute( bufferInfo.normalBuffer, 3 ) );
  602. }
  603. if ( bufferInfo.uvBuffer.length > 0 ) {
  604. geo.addAttribute( 'uv', new THREE.Float32BufferAttribute( bufferInfo.uvBuffer, 2 ) );
  605. }
  606. if ( subNodes.LayerElementColor ) {
  607. geo.addAttribute( 'color', new THREE.Float32BufferAttribute( bufferInfo.colorBuffer, 3 ) );
  608. }
  609. if ( deformer ) {
  610. geo.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( bufferInfo.skinIndexBuffer, 4 ) );
  611. geo.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( bufferInfo.skinWeightBuffer, 4 ) );
  612. geo.FBX_Deformer = deformer;
  613. }
  614. // Convert the material indices of each vertex into rendering groups on the geometry.
  615. var materialIndexBuffer = bufferInfo.materialIndexBuffer;
  616. var prevMaterialIndex = materialIndexBuffer[ 0 ];
  617. var startIndex = 0;
  618. for ( var i = 0; i < materialIndexBuffer.length; ++ i ) {
  619. if ( materialIndexBuffer[ i ] !== prevMaterialIndex ) {
  620. geo.addGroup( startIndex, i - startIndex, prevMaterialIndex );
  621. prevMaterialIndex = materialIndexBuffer[ i ];
  622. startIndex = i;
  623. }
  624. }
  625. return geo;
  626. }
  627. /**
  628. * Parses normal information for geometry.
  629. * @param {FBXGeometryNode} geometryNode
  630. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  631. */
  632. function getNormals( NormalNode ) {
  633. var mappingType = NormalNode.properties.MappingInformationType;
  634. var referenceType = NormalNode.properties.ReferenceInformationType;
  635. var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
  636. var indexBuffer = [];
  637. if ( referenceType === 'IndexToDirect' ) {
  638. if ( 'NormalIndex' in NormalNode.subNodes ) {
  639. indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
  640. } else if ( 'NormalsIndex' in NormalNode.subNodes ) {
  641. indexBuffer = parseIntArray( NormalNode.subNodes.NormalsIndex.properties.a );
  642. }
  643. }
  644. return {
  645. dataSize: 3,
  646. buffer: buffer,
  647. indices: indexBuffer,
  648. mappingType: mappingType,
  649. referenceType: referenceType
  650. };
  651. }
  652. /**
  653. * Parses UV information for geometry.
  654. * @param {FBXGeometryNode} geometryNode
  655. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  656. */
  657. function getUVs( UVNode ) {
  658. var mappingType = UVNode.properties.MappingInformationType;
  659. var referenceType = UVNode.properties.ReferenceInformationType;
  660. var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
  661. var indexBuffer = [];
  662. if ( referenceType === 'IndexToDirect' ) {
  663. indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
  664. }
  665. return {
  666. dataSize: 2,
  667. buffer: buffer,
  668. indices: indexBuffer,
  669. mappingType: mappingType,
  670. referenceType: referenceType
  671. };
  672. }
  673. /**
  674. * Parses Vertex Color information for geometry.
  675. * @param {FBXGeometryNode} geometryNode
  676. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  677. */
  678. function getColors( ColorNode ) {
  679. var mappingType = ColorNode.properties.MappingInformationType;
  680. var referenceType = ColorNode.properties.ReferenceInformationType;
  681. var buffer = parseFloatArray( ColorNode.subNodes.Colors.properties.a );
  682. var indexBuffer = [];
  683. if ( referenceType === 'IndexToDirect' ) {
  684. indexBuffer = parseFloatArray( ColorNode.subNodes.ColorIndex.properties.a );
  685. }
  686. return {
  687. dataSize: 4,
  688. buffer: buffer,
  689. indices: indexBuffer,
  690. mappingType: mappingType,
  691. referenceType: referenceType
  692. };
  693. }
  694. /**
  695. * Parses material application information for geometry.
  696. * @param {FBXGeometryNode}
  697. * @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  698. */
  699. function getMaterials( MaterialNode ) {
  700. var mappingType = MaterialNode.properties.MappingInformationType;
  701. var referenceType = MaterialNode.properties.ReferenceInformationType;
  702. if ( mappingType === 'NoMappingInformation' ) {
  703. return {
  704. dataSize: 1,
  705. buffer: [ 0 ],
  706. indices: [ 0 ],
  707. mappingType: 'AllSame',
  708. referenceType: referenceType
  709. };
  710. }
  711. var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
  712. // Since materials are stored as indices, there's a bit of a mismatch between FBX and what
  713. // we expect. So we create an intermediate buffer that points to the index in the buffer,
  714. // for conforming with the other functions we've written for other data.
  715. var materialIndices = [];
  716. for ( var materialIndexBufferIndex = 0, materialIndexBufferLength = materialIndexBuffer.length; materialIndexBufferIndex < materialIndexBufferLength; ++ materialIndexBufferIndex ) {
  717. materialIndices.push( materialIndexBufferIndex );
  718. }
  719. return {
  720. dataSize: 1,
  721. buffer: materialIndexBuffer,
  722. indices: materialIndices,
  723. mappingType: mappingType,
  724. referenceType: referenceType
  725. };
  726. }
  727. /**
  728. * Function uses the infoObject and given indices to return value array of object.
  729. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  730. * @param {number} polygonIndex - Index of polygon in geometry.
  731. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  732. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  733. * @returns {number[]}
  734. */
  735. var dataArray = [];
  736. var GetData = {
  737. ByPolygonVertex: {
  738. /**
  739. * Function uses the infoObject and given indices to return value array of object.
  740. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  741. * @param {number} polygonIndex - Index of polygon in geometry.
  742. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  743. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  744. * @returns {number[]}
  745. */
  746. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  747. var from = ( polygonVertexIndex * infoObject.dataSize );
  748. var to = ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  749. // return infoObject.buffer.slice( from, to );
  750. return slice( dataArray, infoObject.buffer, from, to );
  751. },
  752. /**
  753. * Function uses the infoObject and given indices to return value array of object.
  754. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  755. * @param {number} polygonIndex - Index of polygon in geometry.
  756. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  757. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  758. * @returns {number[]}
  759. */
  760. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  761. var index = infoObject.indices[ polygonVertexIndex ];
  762. var from = ( index * infoObject.dataSize );
  763. var to = ( index * infoObject.dataSize ) + infoObject.dataSize;
  764. // return infoObject.buffer.slice( from, to );
  765. return slice( dataArray, infoObject.buffer, from, to );
  766. }
  767. },
  768. ByPolygon: {
  769. /**
  770. * Function uses the infoObject and given indices to return value array of object.
  771. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  772. * @param {number} polygonIndex - Index of polygon in geometry.
  773. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  774. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  775. * @returns {number[]}
  776. */
  777. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  778. var from = polygonIndex * infoObject.dataSize;
  779. var to = polygonIndex * infoObject.dataSize + infoObject.dataSize;
  780. // return infoObject.buffer.slice( from, to );
  781. return slice( dataArray, infoObject.buffer, from, to );
  782. },
  783. /**
  784. * Function uses the infoObject and given indices to return value array of object.
  785. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  786. * @param {number} polygonIndex - Index of polygon in geometry.
  787. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  788. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  789. * @returns {number[]}
  790. */
  791. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  792. var index = infoObject.indices[ polygonIndex ];
  793. var from = index * infoObject.dataSize;
  794. var to = index * infoObject.dataSize + infoObject.dataSize;
  795. // return infoObject.buffer.slice( from, to );
  796. return slice( dataArray, infoObject.buffer, from, to );
  797. }
  798. },
  799. ByVertice: {
  800. Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  801. var from = ( vertexIndex * infoObject.dataSize );
  802. var to = ( vertexIndex * infoObject.dataSize ) + infoObject.dataSize;
  803. // return infoObject.buffer.slice( from, to );
  804. return slice( dataArray, infoObject.buffer, from, to );
  805. }
  806. },
  807. AllSame: {
  808. /**
  809. * Function uses the infoObject and given indices to return value array of object.
  810. * @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
  811. * @param {number} polygonIndex - Index of polygon in geometry.
  812. * @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
  813. * @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
  814. * @returns {number[]}
  815. */
  816. IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  817. var from = infoObject.indices[ 0 ] * infoObject.dataSize;
  818. var to = infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize;
  819. // return infoObject.buffer.slice( from, to );
  820. return slice( dataArray, infoObject.buffer, from, to );
  821. }
  822. }
  823. };
  824. function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
  825. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
  826. }
  827. /**
  828. * Specialty function for parsing NurbsCurve based Geometry Nodes.
  829. * @param {FBXGeometryNode} geometryNode
  830. * @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
  831. * @returns {THREE.BufferGeometry}
  832. */
  833. function parseNurbsGeometry( geometryNode ) {
  834. if ( THREE.NURBSCurve === undefined ) {
  835. console.error( 'THREE.FBXLoader: The loader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry.' );
  836. return new THREE.BufferGeometry();
  837. }
  838. var order = parseInt( geometryNode.properties.Order );
  839. if ( isNaN( order ) ) {
  840. console.error( 'THREE.FBXLoader: Invalid Order %s given for geometry ID: %s', geometryNode.properties.Order, geometryNode.id );
  841. return new THREE.BufferGeometry();
  842. }
  843. var degree = order - 1;
  844. var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
  845. var controlPoints = [];
  846. var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
  847. for ( var i = 0, l = pointsValues.length; i < l; i += 4 ) {
  848. controlPoints.push( new THREE.Vector4().fromArray( pointsValues, i ) );
  849. }
  850. var startKnot, endKnot;
  851. if ( geometryNode.properties.Form === 'Closed' ) {
  852. controlPoints.push( controlPoints[ 0 ] );
  853. } else if ( geometryNode.properties.Form === 'Periodic' ) {
  854. startKnot = degree;
  855. endKnot = knots.length - 1 - startKnot;
  856. for ( var i = 0; i < degree; ++ i ) {
  857. controlPoints.push( controlPoints[ i ] );
  858. }
  859. }
  860. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  861. var vertices = curve.getPoints( controlPoints.length * 7 );
  862. var positions = new Float32Array( vertices.length * 3 );
  863. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  864. vertices[ i ].toArray( positions, i * 3 );
  865. }
  866. var geometry = new THREE.BufferGeometry();
  867. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  868. return geometry;
  869. }
  870. /**
  871. * Finally generates Scene graph and Scene graph Objects.
  872. * @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
  873. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  874. * @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformers
  875. * @param {Map<number, THREE.BufferGeometry>} geometryMap
  876. * @param {Map<number, THREE.Material>} materialMap
  877. * @returns {THREE.Group}
  878. */
  879. function parseScene( FBXTree, connections, deformers, geometryMap, materialMap ) {
  880. var sceneGraph = new THREE.Group();
  881. var ModelNode = FBXTree.Objects.subNodes.Model;
  882. /**
  883. * @type {Array.<THREE.Object3D>}
  884. */
  885. var modelArray = [];
  886. /**
  887. * @type {Map.<number, THREE.Object3D>}
  888. */
  889. var modelMap = new Map();
  890. for ( var nodeID in ModelNode ) {
  891. var id = parseInt( nodeID );
  892. var node = ModelNode[ nodeID ];
  893. var conns = connections.get( id );
  894. var model = null;
  895. for ( var i = 0; i < conns.parents.length; ++ i ) {
  896. for ( var FBX_ID in deformers ) {
  897. var deformer = deformers[ FBX_ID ];
  898. var subDeformers = deformer.map;
  899. var subDeformer = subDeformers[ conns.parents[ i ].ID ];
  900. if ( subDeformer ) {
  901. var model2 = model;
  902. model = new THREE.Bone();
  903. deformer.bones[ subDeformer.index ] = model;
  904. // seems like we need this not to make non-connected bone, maybe?
  905. // TODO: confirm
  906. if ( model2 !== null ) model.add( model2 );
  907. }
  908. }
  909. }
  910. if ( ! model ) {
  911. switch ( node.attrType ) {
  912. case 'Mesh':
  913. /**
  914. * @type {?THREE.BufferGeometry}
  915. */
  916. var geometry = null;
  917. /**
  918. * @type {THREE.MultiMaterial|THREE.Material}
  919. */
  920. var material = null;
  921. /**
  922. * @type {Array.<THREE.Material>}
  923. */
  924. var materials = [];
  925. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  926. var child = conns.children[ childrenIndex ];
  927. if ( geometryMap.has( child.ID ) ) {
  928. geometry = geometryMap.get( child.ID );
  929. }
  930. if ( materialMap.has( child.ID ) ) {
  931. materials.push( materialMap.get( child.ID ) );
  932. }
  933. }
  934. if ( materials.length > 1 ) {
  935. material = materials;
  936. } else if ( materials.length > 0 ) {
  937. material = materials[ 0 ];
  938. } else {
  939. material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  940. materials.push( material );
  941. }
  942. if ( 'color' in geometry.attributes ) {
  943. for ( var materialIndex = 0, numMaterials = materials.length; materialIndex < numMaterials; ++materialIndex ) {
  944. materials[ materialIndex ].vertexColors = THREE.VertexColors;
  945. }
  946. }
  947. if ( geometry.FBX_Deformer ) {
  948. for ( var materialsIndex = 0, materialsLength = materials.length; materialsIndex < materialsLength; ++ materialsIndex ) {
  949. materials[ materialsIndex ].skinning = true;
  950. }
  951. model = new THREE.SkinnedMesh( geometry, material );
  952. } else {
  953. model = new THREE.Mesh( geometry, material );
  954. }
  955. break;
  956. case 'NurbsCurve':
  957. var geometry = null;
  958. for ( var childrenIndex = 0, childrenLength = conns.children.length; childrenIndex < childrenLength; ++ childrenIndex ) {
  959. var child = conns.children[ childrenIndex ];
  960. if ( geometryMap.has( child.ID ) ) {
  961. geometry = geometryMap.get( child.ID );
  962. }
  963. }
  964. // FBX does not list materials for Nurbs lines, so we'll just put our own in here.
  965. material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
  966. model = new THREE.Line( geometry, material );
  967. break;
  968. default:
  969. model = new THREE.Object3D();
  970. break;
  971. }
  972. }
  973. model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
  974. model.FBX_ID = id;
  975. modelArray.push( model );
  976. modelMap.set( id, model );
  977. }
  978. for ( var modelArrayIndex = 0, modelArrayLength = modelArray.length; modelArrayIndex < modelArrayLength; ++ modelArrayIndex ) {
  979. var model = modelArray[ modelArrayIndex ];
  980. var node = ModelNode[ model.FBX_ID ];
  981. if ( 'Lcl_Translation' in node.properties ) {
  982. model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
  983. }
  984. if ( 'Lcl_Rotation' in node.properties ) {
  985. var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( degreeToRadian );
  986. rotation.push( 'ZYX' );
  987. model.rotation.fromArray( rotation );
  988. }
  989. if ( 'Lcl_Scaling' in node.properties ) {
  990. model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
  991. }
  992. if ( 'PreRotation' in node.properties ) {
  993. var preRotations = new THREE.Euler().setFromVector3( parseVector3( node.properties.PreRotation ).multiplyScalar( DEG2RAD ), 'ZYX' );
  994. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  995. var currentRotation = new THREE.Quaternion().setFromEuler( model.rotation );
  996. preRotations.multiply( currentRotation );
  997. model.rotation.setFromQuaternion( preRotations, 'ZYX' );
  998. }
  999. // allow transformed pivots - see https://github.com/mrdoob/three.js/issues/11895
  1000. if ( 'GeometricTranslation' in node.properties ) {
  1001. var array = node.properties.GeometricTranslation.value;
  1002. model.traverse( function ( child ) {
  1003. if ( child.geometry ) {
  1004. child.geometry.translate( array[ 0 ], array[ 1 ], array[ 2 ] );
  1005. }
  1006. } );
  1007. }
  1008. var conns = connections.get( model.FBX_ID );
  1009. for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
  1010. var pIndex = findIndex( modelArray, function ( mod ) {
  1011. return mod.FBX_ID === conns.parents[ parentIndex ].ID;
  1012. } );
  1013. if ( pIndex > - 1 ) {
  1014. modelArray[ pIndex ].add( model );
  1015. break;
  1016. }
  1017. }
  1018. if ( model.parent === null ) {
  1019. sceneGraph.add( model );
  1020. }
  1021. }
  1022. // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
  1023. sceneGraph.updateMatrixWorld( true );
  1024. // Put skeleton into bind pose.
  1025. var BindPoseNode = FBXTree.Objects.subNodes.Pose;
  1026. for ( var nodeID in BindPoseNode ) {
  1027. if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
  1028. BindPoseNode = BindPoseNode[ nodeID ];
  1029. break;
  1030. }
  1031. }
  1032. if ( BindPoseNode ) {
  1033. var PoseNode = BindPoseNode.subNodes.PoseNode;
  1034. var worldMatrices = new Map();
  1035. for ( var PoseNodeIndex = 0, PoseNodeLength = PoseNode.length; PoseNodeIndex < PoseNodeLength; ++ PoseNodeIndex ) {
  1036. var node = PoseNode[ PoseNodeIndex ];
  1037. var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
  1038. worldMatrices.set( parseInt( node.id ), rawMatWrd );
  1039. }
  1040. }
  1041. for ( var FBX_ID in deformers ) {
  1042. var deformer = deformers[ FBX_ID ];
  1043. var subDeformers = deformer.map;
  1044. for ( var key in subDeformers ) {
  1045. var subDeformer = subDeformers[ key ];
  1046. var subDeformerIndex = subDeformer.index;
  1047. /**
  1048. * @type {THREE.Bone}
  1049. */
  1050. var bone = deformer.bones[ subDeformerIndex ];
  1051. if ( ! worldMatrices.has( bone.FBX_ID ) ) {
  1052. break;
  1053. }
  1054. var mat = worldMatrices.get( bone.FBX_ID );
  1055. bone.matrixWorld.copy( mat );
  1056. }
  1057. // Now that skeleton is in bind pose, bind to model.
  1058. deformer.skeleton = new THREE.Skeleton( deformer.bones );
  1059. var conns = connections.get( deformer.FBX_ID );
  1060. var parents = conns.parents;
  1061. for ( var parentsIndex = 0, parentsLength = parents.length; parentsIndex < parentsLength; ++ parentsIndex ) {
  1062. var parent = parents[ parentsIndex ];
  1063. if ( geometryMap.has( parent.ID ) ) {
  1064. var geoID = parent.ID;
  1065. var geoConns = connections.get( geoID );
  1066. for ( var i = 0; i < geoConns.parents.length; ++ i ) {
  1067. if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
  1068. var model = modelMap.get( geoConns.parents[ i ].ID );
  1069. //ASSERT model typeof SkinnedMesh
  1070. model.bind( deformer.skeleton, model.matrixWorld );
  1071. break;
  1072. }
  1073. }
  1074. }
  1075. }
  1076. }
  1077. //Skeleton is now bound, return objects to starting
  1078. //world positions.
  1079. sceneGraph.updateMatrixWorld( true );
  1080. // Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
  1081. // to attach animations to, since FBXs treat animations as animations for the entire scene,
  1082. // not just for individual objects.
  1083. sceneGraph.skeleton = {
  1084. bones: modelArray
  1085. };
  1086. var animations = parseAnimations( FBXTree, connections, sceneGraph );
  1087. addAnimations( sceneGraph, animations );
  1088. return sceneGraph;
  1089. }
  1090. /**
  1091. * Parses animation information from FBXTree and generates an AnimationInfoObject.
  1092. * @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
  1093. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1094. */
  1095. function parseAnimations( FBXTree, connections, sceneGraph ) {
  1096. var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
  1097. var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
  1098. var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
  1099. var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
  1100. /**
  1101. * @type {{
  1102. curves: Map<number, {
  1103. T: {
  1104. id: number;
  1105. attr: string;
  1106. internalID: number;
  1107. attrX: boolean;
  1108. attrY: boolean;
  1109. attrZ: boolean;
  1110. containerBoneID: number;
  1111. containerID: number;
  1112. curves: {
  1113. x: {
  1114. version: any;
  1115. id: number;
  1116. internalID: number;
  1117. times: number[];
  1118. values: number[];
  1119. attrFlag: number[];
  1120. attrData: number[];
  1121. };
  1122. y: {
  1123. version: any;
  1124. id: number;
  1125. internalID: number;
  1126. times: number[];
  1127. values: number[];
  1128. attrFlag: number[];
  1129. attrData: number[];
  1130. };
  1131. z: {
  1132. version: any;
  1133. id: number;
  1134. internalID: number;
  1135. times: number[];
  1136. values: number[];
  1137. attrFlag: number[];
  1138. attrData: number[];
  1139. };
  1140. };
  1141. },
  1142. R: {
  1143. id: number;
  1144. attr: string;
  1145. internalID: number;
  1146. attrX: boolean;
  1147. attrY: boolean;
  1148. attrZ: boolean;
  1149. containerBoneID: number;
  1150. containerID: number;
  1151. curves: {
  1152. x: {
  1153. version: any;
  1154. id: number;
  1155. internalID: number;
  1156. times: number[];
  1157. values: number[];
  1158. attrFlag: number[];
  1159. attrData: number[];
  1160. };
  1161. y: {
  1162. version: any;
  1163. id: number;
  1164. internalID: number;
  1165. times: number[];
  1166. values: number[];
  1167. attrFlag: number[];
  1168. attrData: number[];
  1169. };
  1170. z: {
  1171. version: any;
  1172. id: number;
  1173. internalID: number;
  1174. times: number[];
  1175. values: number[];
  1176. attrFlag: number[];
  1177. attrData: number[];
  1178. };
  1179. };
  1180. },
  1181. S: {
  1182. id: number;
  1183. attr: string;
  1184. internalID: number;
  1185. attrX: boolean;
  1186. attrY: boolean;
  1187. attrZ: boolean;
  1188. containerBoneID: number;
  1189. containerID: number;
  1190. curves: {
  1191. x: {
  1192. version: any;
  1193. id: number;
  1194. internalID: number;
  1195. times: number[];
  1196. values: number[];
  1197. attrFlag: number[];
  1198. attrData: number[];
  1199. };
  1200. y: {
  1201. version: any;
  1202. id: number;
  1203. internalID: number;
  1204. times: number[];
  1205. values: number[];
  1206. attrFlag: number[];
  1207. attrData: number[];
  1208. };
  1209. z: {
  1210. version: any;
  1211. id: number;
  1212. internalID: number;
  1213. times: number[];
  1214. values: number[];
  1215. attrFlag: number[];
  1216. attrData: number[];
  1217. };
  1218. };
  1219. }
  1220. }>,
  1221. layers: Map<number, {
  1222. T: {
  1223. id: number;
  1224. attr: string;
  1225. internalID: number;
  1226. attrX: boolean;
  1227. attrY: boolean;
  1228. attrZ: boolean;
  1229. containerBoneID: number;
  1230. containerID: number;
  1231. curves: {
  1232. x: {
  1233. version: any;
  1234. id: number;
  1235. internalID: number;
  1236. times: number[];
  1237. values: number[];
  1238. attrFlag: number[];
  1239. attrData: number[];
  1240. };
  1241. y: {
  1242. version: any;
  1243. id: number;
  1244. internalID: number;
  1245. times: number[];
  1246. values: number[];
  1247. attrFlag: number[];
  1248. attrData: number[];
  1249. };
  1250. z: {
  1251. version: any;
  1252. id: number;
  1253. internalID: number;
  1254. times: number[];
  1255. values: number[];
  1256. attrFlag: number[];
  1257. attrData: number[];
  1258. };
  1259. },
  1260. },
  1261. R: {
  1262. id: number;
  1263. attr: string;
  1264. internalID: number;
  1265. attrX: boolean;
  1266. attrY: boolean;
  1267. attrZ: boolean;
  1268. containerBoneID: number;
  1269. containerID: number;
  1270. curves: {
  1271. x: {
  1272. version: any;
  1273. id: number;
  1274. internalID: number;
  1275. times: number[];
  1276. values: number[];
  1277. attrFlag: number[];
  1278. attrData: number[];
  1279. };
  1280. y: {
  1281. version: any;
  1282. id: number;
  1283. internalID: number;
  1284. times: number[];
  1285. values: number[];
  1286. attrFlag: number[];
  1287. attrData: number[];
  1288. };
  1289. z: {
  1290. version: any;
  1291. id: number;
  1292. internalID: number;
  1293. times: number[];
  1294. values: number[];
  1295. attrFlag: number[];
  1296. attrData: number[];
  1297. };
  1298. },
  1299. },
  1300. S: {
  1301. id: number;
  1302. attr: string;
  1303. internalID: number;
  1304. attrX: boolean;
  1305. attrY: boolean;
  1306. attrZ: boolean;
  1307. containerBoneID: number;
  1308. containerID: number;
  1309. curves: {
  1310. x: {
  1311. version: any;
  1312. id: number;
  1313. internalID: number;
  1314. times: number[];
  1315. values: number[];
  1316. attrFlag: number[];
  1317. attrData: number[];
  1318. };
  1319. y: {
  1320. version: any;
  1321. id: number;
  1322. internalID: number;
  1323. times: number[];
  1324. values: number[];
  1325. attrFlag: number[];
  1326. attrData: number[];
  1327. };
  1328. z: {
  1329. version: any;
  1330. id: number;
  1331. internalID: number;
  1332. times: number[];
  1333. values: number[];
  1334. attrFlag: number[];
  1335. attrData: number[];
  1336. };
  1337. },
  1338. }
  1339. }[]>,
  1340. stacks: Map<number, {
  1341. name: string,
  1342. layers: {
  1343. T: {
  1344. id: number;
  1345. attr: string;
  1346. internalID: number;
  1347. attrX: boolean;
  1348. attrY: boolean;
  1349. attrZ: boolean;
  1350. containerBoneID: number;
  1351. containerID: number;
  1352. curves: {
  1353. x: {
  1354. version: any;
  1355. id: number;
  1356. internalID: number;
  1357. times: number[];
  1358. values: number[];
  1359. attrFlag: number[];
  1360. attrData: number[];
  1361. };
  1362. y: {
  1363. version: any;
  1364. id: number;
  1365. internalID: number;
  1366. times: number[];
  1367. values: number[];
  1368. attrFlag: number[];
  1369. attrData: number[];
  1370. };
  1371. z: {
  1372. version: any;
  1373. id: number;
  1374. internalID: number;
  1375. times: number[];
  1376. values: number[];
  1377. attrFlag: number[];
  1378. attrData: number[];
  1379. };
  1380. };
  1381. };
  1382. R: {
  1383. id: number;
  1384. attr: string;
  1385. internalID: number;
  1386. attrX: boolean;
  1387. attrY: boolean;
  1388. attrZ: boolean;
  1389. containerBoneID: number;
  1390. containerID: number;
  1391. curves: {
  1392. x: {
  1393. version: any;
  1394. id: number;
  1395. internalID: number;
  1396. times: number[];
  1397. values: number[];
  1398. attrFlag: number[];
  1399. attrData: number[];
  1400. };
  1401. y: {
  1402. version: any;
  1403. id: number;
  1404. internalID: number;
  1405. times: number[];
  1406. values: number[];
  1407. attrFlag: number[];
  1408. attrData: number[];
  1409. };
  1410. z: {
  1411. version: any;
  1412. id: number;
  1413. internalID: number;
  1414. times: number[];
  1415. values: number[];
  1416. attrFlag: number[];
  1417. attrData: number[];
  1418. };
  1419. };
  1420. };
  1421. S: {
  1422. id: number;
  1423. attr: string;
  1424. internalID: number;
  1425. attrX: boolean;
  1426. attrY: boolean;
  1427. attrZ: boolean;
  1428. containerBoneID: number;
  1429. containerID: number;
  1430. curves: {
  1431. x: {
  1432. version: any;
  1433. id: number;
  1434. internalID: number;
  1435. times: number[];
  1436. values: number[];
  1437. attrFlag: number[];
  1438. attrData: number[];
  1439. };
  1440. y: {
  1441. version: any;
  1442. id: number;
  1443. internalID: number;
  1444. times: number[];
  1445. values: number[];
  1446. attrFlag: number[];
  1447. attrData: number[];
  1448. };
  1449. z: {
  1450. version: any;
  1451. id: number;
  1452. internalID: number;
  1453. times: number[];
  1454. values: number[];
  1455. attrFlag: number[];
  1456. attrData: number[];
  1457. };
  1458. };
  1459. };
  1460. }[][],
  1461. length: number,
  1462. frames: number }>,
  1463. length: number,
  1464. fps: number,
  1465. frames: number
  1466. }}
  1467. */
  1468. var returnObject = {
  1469. curves: new Map(),
  1470. layers: {},
  1471. stacks: {},
  1472. length: 0,
  1473. fps: 30,
  1474. frames: 0
  1475. };
  1476. /**
  1477. * @type {Array.<{
  1478. id: number;
  1479. attr: string;
  1480. internalID: number;
  1481. attrX: boolean;
  1482. attrY: boolean;
  1483. attrZ: boolean;
  1484. containerBoneID: number;
  1485. containerID: number;
  1486. }>}
  1487. */
  1488. var animationCurveNodes = [];
  1489. for ( var nodeID in rawNodes ) {
  1490. if ( nodeID.match( /\d+/ ) ) {
  1491. var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
  1492. animationCurveNodes.push( animationNode );
  1493. }
  1494. }
  1495. /**
  1496. * @type {Map.<number, {
  1497. id: number,
  1498. attr: string,
  1499. internalID: number,
  1500. attrX: boolean,
  1501. attrY: boolean,
  1502. attrZ: boolean,
  1503. containerBoneID: number,
  1504. containerID: number,
  1505. curves: {
  1506. x: {
  1507. version: any,
  1508. id: number,
  1509. internalID: number,
  1510. times: number[],
  1511. values: number[],
  1512. attrFlag: number[],
  1513. attrData: number[],
  1514. },
  1515. y: {
  1516. version: any,
  1517. id: number,
  1518. internalID: number,
  1519. times: number[],
  1520. values: number[],
  1521. attrFlag: number[],
  1522. attrData: number[],
  1523. },
  1524. z: {
  1525. version: any,
  1526. id: number,
  1527. internalID: number,
  1528. times: number[],
  1529. values: number[],
  1530. attrFlag: number[],
  1531. attrData: number[],
  1532. }
  1533. }
  1534. }>}
  1535. */
  1536. var tmpMap = new Map();
  1537. for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
  1538. if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
  1539. continue;
  1540. }
  1541. tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
  1542. }
  1543. /**
  1544. * @type {{
  1545. version: any,
  1546. id: number,
  1547. internalID: number,
  1548. times: number[],
  1549. values: number[],
  1550. attrFlag: number[],
  1551. attrData: number[],
  1552. }[]}
  1553. */
  1554. var animationCurves = [];
  1555. for ( nodeID in rawCurves ) {
  1556. if ( nodeID.match( /\d+/ ) ) {
  1557. var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
  1558. // seems like this check would be necessary?
  1559. if ( ! connections.has( animationCurve.id ) ) continue;
  1560. animationCurves.push( animationCurve );
  1561. var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
  1562. var firstParentID = firstParentConn.ID;
  1563. var firstParentRelationship = firstParentConn.relationship;
  1564. var axis = '';
  1565. if ( firstParentRelationship.match( /X/ ) ) {
  1566. axis = 'x';
  1567. } else if ( firstParentRelationship.match( /Y/ ) ) {
  1568. axis = 'y';
  1569. } else if ( firstParentRelationship.match( /Z/ ) ) {
  1570. axis = 'z';
  1571. } else {
  1572. continue;
  1573. }
  1574. tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
  1575. }
  1576. }
  1577. tmpMap.forEach( function ( curveNode ) {
  1578. var id = curveNode.containerBoneID;
  1579. if ( ! returnObject.curves.has( id ) ) {
  1580. returnObject.curves.set( id, { T: null, R: null, S: null } );
  1581. }
  1582. returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
  1583. if ( curveNode.attr === 'R' ) {
  1584. var curves = curveNode.curves;
  1585. // Seems like some FBX files have AnimationCurveNode
  1586. // which doesn't have any connected AnimationCurve.
  1587. // Setting animation parameter for them here.
  1588. if ( curves.x === null ) {
  1589. curves.x = {
  1590. version: null,
  1591. times: [ 0.0 ],
  1592. values: [ 0.0 ]
  1593. };
  1594. }
  1595. if ( curves.y === null ) {
  1596. curves.y = {
  1597. version: null,
  1598. times: [ 0.0 ],
  1599. values: [ 0.0 ]
  1600. };
  1601. }
  1602. if ( curves.z === null ) {
  1603. curves.z = {
  1604. version: null,
  1605. times: [ 0.0 ],
  1606. values: [ 0.0 ]
  1607. };
  1608. }
  1609. curves.x.values = curves.x.values.map( degreeToRadian );
  1610. curves.y.values = curves.y.values.map( degreeToRadian );
  1611. curves.z.values = curves.z.values.map( degreeToRadian );
  1612. if ( curveNode.preRotations !== null ) {
  1613. var preRotations = new THREE.Euler().setFromVector3( curveNode.preRotations, 'ZYX' );
  1614. preRotations = new THREE.Quaternion().setFromEuler( preRotations );
  1615. var frameRotation = new THREE.Euler();
  1616. var frameRotationQuaternion = new THREE.Quaternion();
  1617. for ( var frame = 0; frame < curves.x.times.length; ++ frame ) {
  1618. frameRotation.set( curves.x.values[ frame ], curves.y.values[ frame ], curves.z.values[ frame ], 'ZYX' );
  1619. frameRotationQuaternion.setFromEuler( frameRotation ).premultiply( preRotations );
  1620. frameRotation.setFromQuaternion( frameRotationQuaternion, 'ZYX' );
  1621. curves.x.values[ frame ] = frameRotation.x;
  1622. curves.y.values[ frame ] = frameRotation.y;
  1623. curves.z.values[ frame ] = frameRotation.z;
  1624. }
  1625. }
  1626. }
  1627. } );
  1628. for ( var nodeID in rawLayers ) {
  1629. /**
  1630. * @type {{
  1631. T: {
  1632. id: number;
  1633. attr: string;
  1634. internalID: number;
  1635. attrX: boolean;
  1636. attrY: boolean;
  1637. attrZ: boolean;
  1638. containerBoneID: number;
  1639. containerID: number;
  1640. curves: {
  1641. x: {
  1642. version: any;
  1643. id: number;
  1644. internalID: number;
  1645. times: number[];
  1646. values: number[];
  1647. attrFlag: number[];
  1648. attrData: number[];
  1649. };
  1650. y: {
  1651. version: any;
  1652. id: number;
  1653. internalID: number;
  1654. times: number[];
  1655. values: number[];
  1656. attrFlag: number[];
  1657. attrData: number[];
  1658. };
  1659. z: {
  1660. version: any;
  1661. id: number;
  1662. internalID: number;
  1663. times: number[];
  1664. values: number[];
  1665. attrFlag: number[];
  1666. attrData: number[];
  1667. };
  1668. },
  1669. },
  1670. R: {
  1671. id: number;
  1672. attr: string;
  1673. internalID: number;
  1674. attrX: boolean;
  1675. attrY: boolean;
  1676. attrZ: boolean;
  1677. containerBoneID: number;
  1678. containerID: number;
  1679. curves: {
  1680. x: {
  1681. version: any;
  1682. id: number;
  1683. internalID: number;
  1684. times: number[];
  1685. values: number[];
  1686. attrFlag: number[];
  1687. attrData: number[];
  1688. };
  1689. y: {
  1690. version: any;
  1691. id: number;
  1692. internalID: number;
  1693. times: number[];
  1694. values: number[];
  1695. attrFlag: number[];
  1696. attrData: number[];
  1697. };
  1698. z: {
  1699. version: any;
  1700. id: number;
  1701. internalID: number;
  1702. times: number[];
  1703. values: number[];
  1704. attrFlag: number[];
  1705. attrData: number[];
  1706. };
  1707. },
  1708. },
  1709. S: {
  1710. id: number;
  1711. attr: string;
  1712. internalID: number;
  1713. attrX: boolean;
  1714. attrY: boolean;
  1715. attrZ: boolean;
  1716. containerBoneID: number;
  1717. containerID: number;
  1718. curves: {
  1719. x: {
  1720. version: any;
  1721. id: number;
  1722. internalID: number;
  1723. times: number[];
  1724. values: number[];
  1725. attrFlag: number[];
  1726. attrData: number[];
  1727. };
  1728. y: {
  1729. version: any;
  1730. id: number;
  1731. internalID: number;
  1732. times: number[];
  1733. values: number[];
  1734. attrFlag: number[];
  1735. attrData: number[];
  1736. };
  1737. z: {
  1738. version: any;
  1739. id: number;
  1740. internalID: number;
  1741. times: number[];
  1742. values: number[];
  1743. attrFlag: number[];
  1744. attrData: number[];
  1745. };
  1746. },
  1747. }
  1748. }[]}
  1749. */
  1750. var layer = [];
  1751. var children = connections.get( parseInt( nodeID ) ).children;
  1752. for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
  1753. // Skip lockInfluenceWeights
  1754. if ( tmpMap.has( children[ childIndex ].ID ) ) {
  1755. var curveNode = tmpMap.get( children[ childIndex ].ID );
  1756. var boneID = curveNode.containerBoneID;
  1757. if ( layer[ boneID ] === undefined ) {
  1758. layer[ boneID ] = {
  1759. T: null,
  1760. R: null,
  1761. S: null
  1762. };
  1763. }
  1764. layer[ boneID ][ curveNode.attr ] = curveNode;
  1765. }
  1766. }
  1767. returnObject.layers[ nodeID ] = layer;
  1768. }
  1769. for ( var nodeID in rawStacks ) {
  1770. var layers = [];
  1771. var children = connections.get( parseInt( nodeID ) ).children;
  1772. var timestamps = { max: 0, min: Number.MAX_VALUE };
  1773. for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
  1774. var currentLayer = returnObject.layers[ children[ childIndex ].ID ];
  1775. if ( currentLayer !== undefined ) {
  1776. layers.push( currentLayer );
  1777. for ( var currentLayerIndex = 0, currentLayerLength = currentLayer.length; currentLayerIndex < currentLayerLength; ++ currentLayerIndex ) {
  1778. var layer = currentLayer[ currentLayerIndex ];
  1779. if ( layer ) {
  1780. getCurveNodeMaxMinTimeStamps( layer, timestamps );
  1781. }
  1782. }
  1783. }
  1784. }
  1785. // Do we have an animation clip with actual length?
  1786. if ( timestamps.max > timestamps.min ) {
  1787. returnObject.stacks[ nodeID ] = {
  1788. name: rawStacks[ nodeID ].attrName,
  1789. layers: layers,
  1790. length: timestamps.max - timestamps.min,
  1791. frames: ( timestamps.max - timestamps.min ) * 30
  1792. };
  1793. }
  1794. }
  1795. return returnObject;
  1796. }
  1797. /**
  1798. * @param {Object} FBXTree
  1799. * @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
  1800. * @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
  1801. * @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
  1802. */
  1803. function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
  1804. var rawModels = FBXTree.Objects.subNodes.Model;
  1805. var returnObject = {
  1806. /**
  1807. * @type {number}
  1808. */
  1809. id: animationCurveNode.id,
  1810. /**
  1811. * @type {string}
  1812. */
  1813. attr: animationCurveNode.attrName,
  1814. /**
  1815. * @type {number}
  1816. */
  1817. internalID: animationCurveNode.id,
  1818. /**
  1819. * @type {boolean}
  1820. */
  1821. attrX: false,
  1822. /**
  1823. * @type {boolean}
  1824. */
  1825. attrY: false,
  1826. /**
  1827. * @type {boolean}
  1828. */
  1829. attrZ: false,
  1830. /**
  1831. * @type {number}
  1832. */
  1833. containerBoneID: - 1,
  1834. /**
  1835. * @type {number}
  1836. */
  1837. containerID: - 1,
  1838. curves: {
  1839. x: null,
  1840. y: null,
  1841. z: null
  1842. },
  1843. /**
  1844. * @type {number[]}
  1845. */
  1846. preRotations: null
  1847. };
  1848. if ( returnObject.attr.match( /S|R|T/ ) ) {
  1849. for ( var attributeKey in animationCurveNode.properties ) {
  1850. if ( attributeKey.match( /X/ ) ) {
  1851. returnObject.attrX = true;
  1852. }
  1853. if ( attributeKey.match( /Y/ ) ) {
  1854. returnObject.attrY = true;
  1855. }
  1856. if ( attributeKey.match( /Z/ ) ) {
  1857. returnObject.attrZ = true;
  1858. }
  1859. }
  1860. } else {
  1861. return null;
  1862. }
  1863. var conns = connections.get( returnObject.id );
  1864. var containerIndices = conns.parents;
  1865. for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
  1866. var boneID = findIndex( sceneGraph.skeleton.bones, function ( bone ) {
  1867. return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
  1868. } );
  1869. if ( boneID > - 1 ) {
  1870. returnObject.containerBoneID = boneID;
  1871. returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
  1872. var model = rawModels[ returnObject.containerID.toString() ];
  1873. if ( 'PreRotation' in model.properties ) {
  1874. returnObject.preRotations = parseVector3( model.properties.PreRotation ).multiplyScalar( Math.PI / 180 );
  1875. }
  1876. break;
  1877. }
  1878. }
  1879. return returnObject;
  1880. }
  1881. /**
  1882. * @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
  1883. */
  1884. function parseAnimationCurve( animationCurve ) {
  1885. return {
  1886. version: null,
  1887. id: animationCurve.id,
  1888. internalID: animationCurve.id,
  1889. times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( convertFBXTimeToSeconds ),
  1890. values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
  1891. attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
  1892. attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
  1893. };
  1894. }
  1895. /**
  1896. * Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
  1897. * than the max or min respectively.
  1898. * @param {{
  1899. T: {
  1900. id: number,
  1901. attr: string,
  1902. internalID: number,
  1903. attrX: boolean,
  1904. attrY: boolean,
  1905. attrZ: boolean,
  1906. containerBoneID: number,
  1907. containerID: number,
  1908. curves: {
  1909. x: {
  1910. version: any,
  1911. id: number,
  1912. internalID: number,
  1913. times: number[],
  1914. values: number[],
  1915. attrFlag: number[],
  1916. attrData: number[],
  1917. },
  1918. y: {
  1919. version: any,
  1920. id: number,
  1921. internalID: number,
  1922. times: number[],
  1923. values: number[],
  1924. attrFlag: number[],
  1925. attrData: number[],
  1926. },
  1927. z: {
  1928. version: any,
  1929. id: number,
  1930. internalID: number,
  1931. times: number[],
  1932. values: number[],
  1933. attrFlag: number[],
  1934. attrData: number[],
  1935. },
  1936. },
  1937. },
  1938. R: {
  1939. id: number,
  1940. attr: string,
  1941. internalID: number,
  1942. attrX: boolean,
  1943. attrY: boolean,
  1944. attrZ: boolean,
  1945. containerBoneID: number,
  1946. containerID: number,
  1947. curves: {
  1948. x: {
  1949. version: any,
  1950. id: number,
  1951. internalID: number,
  1952. times: number[],
  1953. values: number[],
  1954. attrFlag: number[],
  1955. attrData: number[],
  1956. },
  1957. y: {
  1958. version: any,
  1959. id: number,
  1960. internalID: number,
  1961. times: number[],
  1962. values: number[],
  1963. attrFlag: number[],
  1964. attrData: number[],
  1965. },
  1966. z: {
  1967. version: any,
  1968. id: number,
  1969. internalID: number,
  1970. times: number[],
  1971. values: number[],
  1972. attrFlag: number[],
  1973. attrData: number[],
  1974. },
  1975. },
  1976. },
  1977. S: {
  1978. id: number,
  1979. attr: string,
  1980. internalID: number,
  1981. attrX: boolean,
  1982. attrY: boolean,
  1983. attrZ: boolean,
  1984. containerBoneID: number,
  1985. containerID: number,
  1986. curves: {
  1987. x: {
  1988. version: any,
  1989. id: number,
  1990. internalID: number,
  1991. times: number[],
  1992. values: number[],
  1993. attrFlag: number[],
  1994. attrData: number[],
  1995. },
  1996. y: {
  1997. version: any,
  1998. id: number,
  1999. internalID: number,
  2000. times: number[],
  2001. values: number[],
  2002. attrFlag: number[],
  2003. attrData: number[],
  2004. },
  2005. z: {
  2006. version: any,
  2007. id: number,
  2008. internalID: number,
  2009. times: number[],
  2010. values: number[],
  2011. attrFlag: number[],
  2012. attrData: number[],
  2013. },
  2014. },
  2015. },
  2016. }} layer
  2017. */
  2018. function getCurveNodeMaxMinTimeStamps( layer, timestamps ) {
  2019. if ( layer.R ) {
  2020. getCurveMaxMinTimeStamp( layer.R.curves, timestamps );
  2021. }
  2022. if ( layer.S ) {
  2023. getCurveMaxMinTimeStamp( layer.S.curves, timestamps );
  2024. }
  2025. if ( layer.T ) {
  2026. getCurveMaxMinTimeStamp( layer.T.curves, timestamps );
  2027. }
  2028. }
  2029. /**
  2030. * Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
  2031. * exceeds the maximum or minimum.
  2032. * @param {{
  2033. x: {
  2034. version: any,
  2035. id: number,
  2036. internalID: number,
  2037. times: number[],
  2038. values: number[],
  2039. attrFlag: number[],
  2040. attrData: number[],
  2041. },
  2042. y: {
  2043. version: any,
  2044. id: number,
  2045. internalID: number,
  2046. times: number[],
  2047. values: number[],
  2048. attrFlag: number[],
  2049. attrData: number[],
  2050. },
  2051. z: {
  2052. version: any,
  2053. id: number,
  2054. internalID: number,
  2055. times: number[],
  2056. values: number[],
  2057. attrFlag: number[],
  2058. attrData: number[],
  2059. }
  2060. }} curve
  2061. */
  2062. function getCurveMaxMinTimeStamp( curve, timestamps ) {
  2063. if ( curve.x ) {
  2064. getCurveAxisMaxMinTimeStamps( curve.x, timestamps );
  2065. }
  2066. if ( curve.y ) {
  2067. getCurveAxisMaxMinTimeStamps( curve.y, timestamps );
  2068. }
  2069. if ( curve.z ) {
  2070. getCurveAxisMaxMinTimeStamps( curve.z, timestamps );
  2071. }
  2072. }
  2073. /**
  2074. * Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
  2075. * @param {{times: number[]}} axis
  2076. */
  2077. function getCurveAxisMaxMinTimeStamps( axis, timestamps ) {
  2078. timestamps.max = axis.times[ axis.times.length - 1 ] > timestamps.max ? axis.times[ axis.times.length - 1 ] : timestamps.max;
  2079. timestamps.min = axis.times[ 0 ] < timestamps.min ? axis.times[ 0 ] : timestamps.min;
  2080. }
  2081. /**
  2082. * @param {{
  2083. curves: Map<number, {
  2084. T: {
  2085. id: number;
  2086. attr: string;
  2087. internalID: number;
  2088. attrX: boolean;
  2089. attrY: boolean;
  2090. attrZ: boolean;
  2091. containerBoneID: number;
  2092. containerID: number;
  2093. curves: {
  2094. x: {
  2095. version: any;
  2096. id: number;
  2097. internalID: number;
  2098. times: number[];
  2099. values: number[];
  2100. attrFlag: number[];
  2101. attrData: number[];
  2102. };
  2103. y: {
  2104. version: any;
  2105. id: number;
  2106. internalID: number;
  2107. times: number[];
  2108. values: number[];
  2109. attrFlag: number[];
  2110. attrData: number[];
  2111. };
  2112. z: {
  2113. version: any;
  2114. id: number;
  2115. internalID: number;
  2116. times: number[];
  2117. values: number[];
  2118. attrFlag: number[];
  2119. attrData: number[];
  2120. };
  2121. };
  2122. };
  2123. R: {
  2124. id: number;
  2125. attr: string;
  2126. internalID: number;
  2127. attrX: boolean;
  2128. attrY: boolean;
  2129. attrZ: boolean;
  2130. containerBoneID: number;
  2131. containerID: number;
  2132. curves: {
  2133. x: {
  2134. version: any;
  2135. id: number;
  2136. internalID: number;
  2137. times: number[];
  2138. values: number[];
  2139. attrFlag: number[];
  2140. attrData: number[];
  2141. };
  2142. y: {
  2143. version: any;
  2144. id: number;
  2145. internalID: number;
  2146. times: number[];
  2147. values: number[];
  2148. attrFlag: number[];
  2149. attrData: number[];
  2150. };
  2151. z: {
  2152. version: any;
  2153. id: number;
  2154. internalID: number;
  2155. times: number[];
  2156. values: number[];
  2157. attrFlag: number[];
  2158. attrData: number[];
  2159. };
  2160. };
  2161. };
  2162. S: {
  2163. id: number;
  2164. attr: string;
  2165. internalID: number;
  2166. attrX: boolean;
  2167. attrY: boolean;
  2168. attrZ: boolean;
  2169. containerBoneID: number;
  2170. containerID: number;
  2171. curves: {
  2172. x: {
  2173. version: any;
  2174. id: number;
  2175. internalID: number;
  2176. times: number[];
  2177. values: number[];
  2178. attrFlag: number[];
  2179. attrData: number[];
  2180. };
  2181. y: {
  2182. version: any;
  2183. id: number;
  2184. internalID: number;
  2185. times: number[];
  2186. values: number[];
  2187. attrFlag: number[];
  2188. attrData: number[];
  2189. };
  2190. z: {
  2191. version: any;
  2192. id: number;
  2193. internalID: number;
  2194. times: number[];
  2195. values: number[];
  2196. attrFlag: number[];
  2197. attrData: number[];
  2198. };
  2199. };
  2200. };
  2201. }>;
  2202. layers: Map<number, {
  2203. T: {
  2204. id: number;
  2205. attr: string;
  2206. internalID: number;
  2207. attrX: boolean;
  2208. attrY: boolean;
  2209. attrZ: boolean;
  2210. containerBoneID: number;
  2211. containerID: number;
  2212. curves: {
  2213. x: {
  2214. version: any;
  2215. id: number;
  2216. internalID: number;
  2217. times: number[];
  2218. values: number[];
  2219. attrFlag: number[];
  2220. attrData: number[];
  2221. };
  2222. y: {
  2223. version: any;
  2224. id: number;
  2225. internalID: number;
  2226. times: number[];
  2227. values: number[];
  2228. attrFlag: number[];
  2229. attrData: number[];
  2230. };
  2231. z: {
  2232. version: any;
  2233. id: number;
  2234. internalID: number;
  2235. times: number[];
  2236. values: number[];
  2237. attrFlag: number[];
  2238. attrData: number[];
  2239. };
  2240. };
  2241. };
  2242. R: {
  2243. id: number;
  2244. attr: string;
  2245. internalID: number;
  2246. attrX: boolean;
  2247. attrY: boolean;
  2248. attrZ: boolean;
  2249. containerBoneID: number;
  2250. containerID: number;
  2251. curves: {
  2252. x: {
  2253. version: any;
  2254. id: number;
  2255. internalID: number;
  2256. times: number[];
  2257. values: number[];
  2258. attrFlag: number[];
  2259. attrData: number[];
  2260. };
  2261. y: {
  2262. version: any;
  2263. id: number;
  2264. internalID: number;
  2265. times: number[];
  2266. values: number[];
  2267. attrFlag: number[];
  2268. attrData: number[];
  2269. };
  2270. z: {
  2271. version: any;
  2272. id: number;
  2273. internalID: number;
  2274. times: number[];
  2275. values: number[];
  2276. attrFlag: number[];
  2277. attrData: number[];
  2278. };
  2279. };
  2280. };
  2281. S: {
  2282. id: number;
  2283. attr: string;
  2284. internalID: number;
  2285. attrX: boolean;
  2286. attrY: boolean;
  2287. attrZ: boolean;
  2288. containerBoneID: number;
  2289. containerID: number;
  2290. curves: {
  2291. x: {
  2292. version: any;
  2293. id: number;
  2294. internalID: number;
  2295. times: number[];
  2296. values: number[];
  2297. attrFlag: number[];
  2298. attrData: number[];
  2299. };
  2300. y: {
  2301. version: any;
  2302. id: number;
  2303. internalID: number;
  2304. times: number[];
  2305. values: number[];
  2306. attrFlag: number[];
  2307. attrData: number[];
  2308. };
  2309. z: {
  2310. version: any;
  2311. id: number;
  2312. internalID: number;
  2313. times: number[];
  2314. values: number[];
  2315. attrFlag: number[];
  2316. attrData: number[];
  2317. };
  2318. };
  2319. };
  2320. }[]>;
  2321. stacks: Map<number, {
  2322. name: string;
  2323. layers: {
  2324. T: {
  2325. id: number;
  2326. attr: string;
  2327. internalID: number;
  2328. attrX: boolean;
  2329. attrY: boolean;
  2330. attrZ: boolean;
  2331. containerBoneID: number;
  2332. containerID: number;
  2333. curves: {
  2334. x: {
  2335. version: any;
  2336. id: number;
  2337. internalID: number;
  2338. times: number[];
  2339. values: number[];
  2340. attrFlag: number[];
  2341. attrData: number[];
  2342. };
  2343. y: {
  2344. version: any;
  2345. id: number;
  2346. internalID: number;
  2347. times: number[];
  2348. values: number[];
  2349. attrFlag: number[];
  2350. attrData: number[];
  2351. };
  2352. z: {
  2353. version: any;
  2354. id: number;
  2355. internalID: number;
  2356. times: number[];
  2357. values: number[];
  2358. attrFlag: number[];
  2359. attrData: number[];
  2360. };
  2361. };
  2362. };
  2363. R: {
  2364. id: number;
  2365. attr: string;
  2366. internalID: number;
  2367. attrX: boolean;
  2368. attrY: boolean;
  2369. attrZ: boolean;
  2370. containerBoneID: number;
  2371. containerID: number;
  2372. curves: {
  2373. x: {
  2374. version: any;
  2375. id: number;
  2376. internalID: number;
  2377. times: number[];
  2378. values: number[];
  2379. attrFlag: number[];
  2380. attrData: number[];
  2381. };
  2382. y: {
  2383. version: any;
  2384. id: number;
  2385. internalID: number;
  2386. times: number[];
  2387. values: number[];
  2388. attrFlag: number[];
  2389. attrData: number[];
  2390. };
  2391. z: {
  2392. version: any;
  2393. id: number;
  2394. internalID: number;
  2395. times: number[];
  2396. values: number[];
  2397. attrFlag: number[];
  2398. attrData: number[];
  2399. };
  2400. };
  2401. };
  2402. S: {
  2403. id: number;
  2404. attr: string;
  2405. internalID: number;
  2406. attrX: boolean;
  2407. attrY: boolean;
  2408. attrZ: boolean;
  2409. containerBoneID: number;
  2410. containerID: number;
  2411. curves: {
  2412. x: {
  2413. version: any;
  2414. id: number;
  2415. internalID: number;
  2416. times: number[];
  2417. values: number[];
  2418. attrFlag: number[];
  2419. attrData: number[];
  2420. };
  2421. y: {
  2422. version: any;
  2423. id: number;
  2424. internalID: number;
  2425. times: number[];
  2426. values: number[];
  2427. attrFlag: number[];
  2428. attrData: number[];
  2429. };
  2430. z: {
  2431. version: any;
  2432. id: number;
  2433. internalID: number;
  2434. times: number[];
  2435. values: number[];
  2436. attrFlag: number[];
  2437. attrData: number[];
  2438. };
  2439. };
  2440. };
  2441. }[][];
  2442. length: number;
  2443. frames: number;
  2444. }>;
  2445. length: number;
  2446. fps: number;
  2447. frames: number;
  2448. }} animations,
  2449. * @param {{skeleton: { bones: THREE.Bone[]}}} group
  2450. */
  2451. function addAnimations( group, animations ) {
  2452. if ( group.animations === undefined ) {
  2453. group.animations = [];
  2454. }
  2455. var stacks = animations.stacks;
  2456. for ( var key in stacks ) {
  2457. var stack = stacks[ key ];
  2458. /**
  2459. * @type {{
  2460. * name: string,
  2461. * fps: number,
  2462. * length: number,
  2463. * hierarchy: Array.<{
  2464. * parent: number,
  2465. * name: string,
  2466. * keys: Array.<{
  2467. * time: number,
  2468. * pos: Array.<number>,
  2469. * rot: Array.<number>,
  2470. * scl: Array.<number>
  2471. * }>
  2472. * }>
  2473. * }}
  2474. */
  2475. var animationData = {
  2476. name: stack.name,
  2477. fps: 30,
  2478. length: stack.length,
  2479. hierarchy: []
  2480. };
  2481. var bones = group.skeleton.bones;
  2482. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2483. var bone = bones[ bonesIndex ];
  2484. var name = bone.name.replace( /.*:/, '' );
  2485. var parentIndex = findIndex( bones, function ( parentBone ) {
  2486. return bone.parent === parentBone;
  2487. } );
  2488. animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
  2489. }
  2490. for ( var frame = 0; frame <= stack.frames; frame ++ ) {
  2491. for ( var bonesIndex = 0, bonesLength = bones.length; bonesIndex < bonesLength; ++ bonesIndex ) {
  2492. var bone = bones[ bonesIndex ];
  2493. var boneIndex = bonesIndex;
  2494. var animationNode = stack.layers[ 0 ][ boneIndex ];
  2495. for ( var hierarchyIndex = 0, hierarchyLength = animationData.hierarchy.length; hierarchyIndex < hierarchyLength; ++ hierarchyIndex ) {
  2496. var node = animationData.hierarchy[ hierarchyIndex ];
  2497. if ( node.name === bone.name ) {
  2498. node.keys.push( generateKey( animations, animationNode, bone, frame ) );
  2499. }
  2500. }
  2501. }
  2502. }
  2503. group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
  2504. }
  2505. }
  2506. var euler = new THREE.Euler();
  2507. var quaternion = new THREE.Quaternion();
  2508. /**
  2509. * @param {THREE.Bone} bone
  2510. */
  2511. function generateKey( animations, animationNode, bone, frame ) {
  2512. var key = {
  2513. time: frame / animations.fps,
  2514. pos: bone.position.toArray(),
  2515. rot: bone.quaternion.toArray(),
  2516. scl: bone.scale.toArray()
  2517. };
  2518. if ( animationNode === undefined ) return key;
  2519. try {
  2520. if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
  2521. key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
  2522. }
  2523. if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
  2524. var rotationX = animationNode.R.curves.x.values[ frame ];
  2525. var rotationY = animationNode.R.curves.y.values[ frame ];
  2526. var rotationZ = animationNode.R.curves.z.values[ frame ];
  2527. quaternion.setFromEuler( euler.set( rotationX, rotationY, rotationZ, 'ZYX' ) );
  2528. key.rot = quaternion.toArray();
  2529. }
  2530. if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
  2531. key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
  2532. }
  2533. } catch ( error ) {
  2534. // Curve is not fully plotted.
  2535. console.log( 'THREE.FBXLoader: ', bone );
  2536. console.log( 'THREE.FBXLoader: ', error );
  2537. }
  2538. return key;
  2539. }
  2540. var AXES = [ 'x', 'y', 'z' ];
  2541. function hasCurve( animationNode, attribute ) {
  2542. if ( animationNode === undefined ) {
  2543. return false;
  2544. }
  2545. var attributeNode = animationNode[ attribute ];
  2546. if ( ! attributeNode ) {
  2547. return false;
  2548. }
  2549. return AXES.every( function ( key ) {
  2550. return attributeNode.curves[ key ] !== null;
  2551. } );
  2552. }
  2553. function hasKeyOnFrame( attributeNode, frame ) {
  2554. return AXES.every( function ( key ) {
  2555. return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
  2556. } );
  2557. }
  2558. function isKeyExistOnFrame( curve, frame ) {
  2559. return curve.values[ frame ] !== undefined;
  2560. }
  2561. /**
  2562. * An instance of a Vertex with data for drawing vertices to the screen.
  2563. * @constructor
  2564. */
  2565. function Vertex() {
  2566. /**
  2567. * Position of the vertex.
  2568. * @type {THREE.Vector3}
  2569. */
  2570. this.position = new THREE.Vector3();
  2571. /**
  2572. * Normal of the vertex
  2573. * @type {THREE.Vector3}
  2574. */
  2575. this.normal = new THREE.Vector3();
  2576. /**
  2577. * UV coordinates of the vertex.
  2578. * @type {THREE.Vector2}
  2579. */
  2580. this.uv = new THREE.Vector2();
  2581. /**
  2582. * Color of the vertex
  2583. * @type {THREE.Vector3}
  2584. */
  2585. this.color = new THREE.Vector3();
  2586. /**
  2587. * Indices of the bones vertex is influenced by.
  2588. * @type {THREE.Vector4}
  2589. */
  2590. this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
  2591. /**
  2592. * Weights that each bone influences the vertex.
  2593. * @type {THREE.Vector4}
  2594. */
  2595. this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
  2596. }
  2597. Object.assign( Vertex.prototype, {
  2598. copy: function ( target ) {
  2599. var returnVar = target || new Vertex();
  2600. returnVar.position.copy( this.position );
  2601. returnVar.normal.copy( this.normal );
  2602. returnVar.uv.copy( this.uv );
  2603. returnVar.skinIndices.copy( this.skinIndices );
  2604. returnVar.skinWeights.copy( this.skinWeights );
  2605. return returnVar;
  2606. },
  2607. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2608. this.position.toArray( vertexBuffer, vertexBuffer.length );
  2609. this.normal.toArray( normalBuffer, normalBuffer.length );
  2610. this.uv.toArray( uvBuffer, uvBuffer.length );
  2611. this.color.toArray( colorBuffer, colorBuffer.length );
  2612. this.skinIndices.toArray( skinIndexBuffer, skinIndexBuffer.length );
  2613. this.skinWeights.toArray( skinWeightBuffer, skinWeightBuffer.length );
  2614. }
  2615. } );
  2616. /**
  2617. * @constructor
  2618. */
  2619. function Triangle() {
  2620. /**
  2621. * @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
  2622. */
  2623. this.vertices = [];
  2624. }
  2625. Object.assign( Triangle.prototype, {
  2626. copy: function ( target ) {
  2627. var returnVar = target || new Triangle();
  2628. for ( var i = 0; i < this.vertices.length; ++ i ) {
  2629. this.vertices[ i ].copy( returnVar.vertices[ i ] );
  2630. }
  2631. return returnVar;
  2632. },
  2633. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer ) {
  2634. var vertices = this.vertices;
  2635. for ( var i = 0, l = vertices.length; i < l; ++ i ) {
  2636. vertices[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2637. }
  2638. }
  2639. } );
  2640. /**
  2641. * @constructor
  2642. */
  2643. function Face() {
  2644. /**
  2645. * @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
  2646. */
  2647. this.triangles = [];
  2648. this.materialIndex = 0;
  2649. }
  2650. Object.assign( Face.prototype, {
  2651. copy: function ( target ) {
  2652. var returnVar = target || new Face();
  2653. for ( var i = 0; i < this.triangles.length; ++ i ) {
  2654. this.triangles[ i ].copy( returnVar.triangles[ i ] );
  2655. }
  2656. returnVar.materialIndex = this.materialIndex;
  2657. return returnVar;
  2658. },
  2659. genTrianglesFromVertices: function ( vertexArray ) {
  2660. for ( var i = 2; i < vertexArray.length; ++ i ) {
  2661. var triangle = new Triangle();
  2662. triangle.vertices[ 0 ] = vertexArray[ 0 ];
  2663. triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
  2664. triangle.vertices[ 2 ] = vertexArray[ i ];
  2665. this.triangles.push( triangle );
  2666. }
  2667. },
  2668. flattenToBuffers: function ( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer ) {
  2669. var triangles = this.triangles;
  2670. var materialIndex = this.materialIndex;
  2671. for ( var i = 0, l = triangles.length; i < l; ++ i ) {
  2672. triangles[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer );
  2673. append( materialIndexBuffer, [ materialIndex, materialIndex, materialIndex ] );
  2674. }
  2675. }
  2676. } );
  2677. /**
  2678. * @constructor
  2679. */
  2680. function Geometry() {
  2681. /**
  2682. * @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
  2683. */
  2684. this.faces = [];
  2685. /**
  2686. * @type {{}|THREE.Skeleton}
  2687. */
  2688. this.skeleton = null;
  2689. }
  2690. Object.assign( Geometry.prototype, {
  2691. /**
  2692. * @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
  2693. */
  2694. flattenToBuffers: function () {
  2695. var vertexBuffer = [];
  2696. var normalBuffer = [];
  2697. var uvBuffer = [];
  2698. var colorBuffer = [];
  2699. var skinIndexBuffer = [];
  2700. var skinWeightBuffer = [];
  2701. var materialIndexBuffer = [];
  2702. var faces = this.faces;
  2703. for ( var i = 0, l = faces.length; i < l; ++ i ) {
  2704. faces[ i ].flattenToBuffers( vertexBuffer, normalBuffer, uvBuffer, colorBuffer, skinIndexBuffer, skinWeightBuffer, materialIndexBuffer );
  2705. }
  2706. return {
  2707. vertexBuffer: vertexBuffer,
  2708. normalBuffer: normalBuffer,
  2709. uvBuffer: uvBuffer,
  2710. colorBuffer: colorBuffer,
  2711. skinIndexBuffer: skinIndexBuffer,
  2712. skinWeightBuffer: skinWeightBuffer,
  2713. materialIndexBuffer: materialIndexBuffer
  2714. };
  2715. }
  2716. } );
  2717. function TextParser() {}
  2718. Object.assign( TextParser.prototype, {
  2719. getPrevNode: function () {
  2720. return this.nodeStack[ this.currentIndent - 2 ];
  2721. },
  2722. getCurrentNode: function () {
  2723. return this.nodeStack[ this.currentIndent - 1 ];
  2724. },
  2725. getCurrentProp: function () {
  2726. return this.currentProp;
  2727. },
  2728. pushStack: function ( node ) {
  2729. this.nodeStack.push( node );
  2730. this.currentIndent += 1;
  2731. },
  2732. popStack: function () {
  2733. this.nodeStack.pop();
  2734. this.currentIndent -= 1;
  2735. },
  2736. setCurrentProp: function ( val, name ) {
  2737. this.currentProp = val;
  2738. this.currentPropName = name;
  2739. },
  2740. // ----------parse ---------------------------------------------------
  2741. parse: function ( text ) {
  2742. this.currentIndent = 0;
  2743. this.allNodes = new FBXTree();
  2744. this.nodeStack = [];
  2745. this.currentProp = [];
  2746. this.currentPropName = '';
  2747. var split = text.split( '\n' );
  2748. for ( var lineNum = 0, lineLength = split.length; lineNum < lineLength; lineNum ++ ) {
  2749. var l = split[ lineNum ];
  2750. // skip comment line
  2751. if ( l.match( /^[\s\t]*;/ ) ) {
  2752. continue;
  2753. }
  2754. // skip empty line
  2755. if ( l.match( /^[\s\t]*$/ ) ) {
  2756. continue;
  2757. }
  2758. // beginning of node
  2759. var beginningOfNodeExp = new RegExp( '^\\t{' + this.currentIndent + '}(\\w+):(.*){', '' );
  2760. var match = l.match( beginningOfNodeExp );
  2761. if ( match ) {
  2762. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2763. var nodeAttrs = match[ 2 ].split( ',' );
  2764. for ( var i = 0, l = nodeAttrs.length; i < l; i ++ ) {
  2765. nodeAttrs[ i ] = nodeAttrs[ i ].trim().replace( /^"/, '' ).replace( /"$/, '' );
  2766. }
  2767. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  2768. continue;
  2769. }
  2770. // node's property
  2771. var propExp = new RegExp( '^\\t{' + ( this.currentIndent ) + '}(\\w+):[\\s\\t\\r\\n](.*)' );
  2772. var match = l.match( propExp );
  2773. if ( match ) {
  2774. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2775. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, '' ).trim();
  2776. // for special case: base64 image data follows "Content: ," line
  2777. // Content: ,
  2778. // "iVB..."
  2779. if ( propName === 'Content' && propValue === ',' ) {
  2780. propValue = split[ ++ lineNum ].replace( /"/g, '' ).trim();
  2781. }
  2782. this.parseNodeProperty( l, propName, propValue );
  2783. continue;
  2784. }
  2785. // end of node
  2786. var endOfNodeExp = new RegExp( '^\\t{' + ( this.currentIndent - 1 ) + '}}' );
  2787. if ( l.match( endOfNodeExp ) ) {
  2788. this.nodeEnd();
  2789. continue;
  2790. }
  2791. // for special case,
  2792. //
  2793. // Vertices: *8670 {
  2794. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  2795. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  2796. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  2797. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  2798. //
  2799. // these case the lines must contiue with previous line
  2800. if ( l.match( /^[^\s\t}]/ ) ) {
  2801. this.parseNodePropertyContinued( l );
  2802. }
  2803. }
  2804. return this.allNodes;
  2805. },
  2806. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  2807. // var nodeName = match[1];
  2808. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  2809. var attrs = this.parseNodeAttr( nodeAttrs );
  2810. var currentNode = this.getCurrentNode();
  2811. // a top node
  2812. if ( this.currentIndent === 0 ) {
  2813. this.allNodes.add( nodeName, node );
  2814. } else {
  2815. // a subnode
  2816. // already exists subnode, then append it
  2817. if ( nodeName in currentNode.subNodes ) {
  2818. var tmp = currentNode.subNodes[ nodeName ];
  2819. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  2820. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  2821. if ( attrs.id === '' ) {
  2822. currentNode.subNodes[ nodeName ] = [];
  2823. currentNode.subNodes[ nodeName ].push( tmp );
  2824. } else {
  2825. currentNode.subNodes[ nodeName ] = {};
  2826. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  2827. }
  2828. }
  2829. if ( attrs.id === '' ) {
  2830. currentNode.subNodes[ nodeName ].push( node );
  2831. } else {
  2832. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2833. }
  2834. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  2835. currentNode.subNodes[ nodeName ] = {};
  2836. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  2837. } else {
  2838. currentNode.subNodes[ nodeName ] = node;
  2839. }
  2840. }
  2841. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  2842. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  2843. if ( nodeAttrs ) {
  2844. node.id = attrs.id;
  2845. node.attrName = attrs.name;
  2846. node.attrType = attrs.type;
  2847. }
  2848. this.pushStack( node );
  2849. },
  2850. parseNodeAttr: function ( attrs ) {
  2851. var id = attrs[ 0 ];
  2852. if ( attrs[ 0 ] !== '' ) {
  2853. id = parseInt( attrs[ 0 ] );
  2854. if ( isNaN( id ) ) {
  2855. // PolygonVertexIndex: *16380 {
  2856. id = attrs[ 0 ];
  2857. }
  2858. }
  2859. var name = '', type = '';
  2860. if ( attrs.length > 1 ) {
  2861. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  2862. type = attrs[ 2 ];
  2863. }
  2864. return { id: id, name: name, type: type };
  2865. },
  2866. parseNodeProperty: function ( line, propName, propValue ) {
  2867. var currentNode = this.getCurrentNode();
  2868. var parentName = currentNode.name;
  2869. // special case parent node's is like "Properties70"
  2870. // these children nodes must treat with careful
  2871. if ( parentName !== undefined ) {
  2872. var propMatch = parentName.match( /Properties(\d)+/ );
  2873. if ( propMatch ) {
  2874. this.parseNodeSpecialProperty( line, propName, propValue );
  2875. return;
  2876. }
  2877. }
  2878. // special case Connections
  2879. if ( propName === 'C' ) {
  2880. var connProps = propValue.split( ',' ).slice( 1 );
  2881. var from = parseInt( connProps[ 0 ] );
  2882. var to = parseInt( connProps[ 1 ] );
  2883. var rest = propValue.split( ',' ).slice( 3 );
  2884. propName = 'connections';
  2885. propValue = [ from, to ];
  2886. append( propValue, rest );
  2887. if ( currentNode.properties[ propName ] === undefined ) {
  2888. currentNode.properties[ propName ] = [];
  2889. }
  2890. }
  2891. // special case Connections
  2892. if ( propName === 'Node' ) {
  2893. var id = parseInt( propValue );
  2894. currentNode.properties.id = id;
  2895. currentNode.id = id;
  2896. }
  2897. // already exists in properties, then append this
  2898. if ( propName in currentNode.properties ) {
  2899. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  2900. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2901. currentNode.properties[ propName ].push( propValue );
  2902. } else {
  2903. currentNode.properties[ propName ] += propValue;
  2904. }
  2905. } else {
  2906. // console.log( propName + ": " + propValue );
  2907. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  2908. currentNode.properties[ propName ].push( propValue );
  2909. } else {
  2910. currentNode.properties[ propName ] = propValue;
  2911. }
  2912. }
  2913. this.setCurrentProp( currentNode.properties, propName );
  2914. },
  2915. // TODO:
  2916. parseNodePropertyContinued: function ( line ) {
  2917. this.currentProp[ this.currentPropName ] += line;
  2918. },
  2919. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  2920. // split this
  2921. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  2922. // into array like below
  2923. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  2924. var props = propValue.split( '",' );
  2925. for ( var i = 0, l = props.length; i < l; i ++ ) {
  2926. props[ i ] = props[ i ].trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  2927. }
  2928. var innerPropName = props[ 0 ];
  2929. var innerPropType1 = props[ 1 ];
  2930. var innerPropType2 = props[ 2 ];
  2931. var innerPropFlag = props[ 3 ];
  2932. var innerPropValue = props[ 4 ];
  2933. /*
  2934. if ( innerPropValue === undefined ) {
  2935. innerPropValue = props[3];
  2936. }
  2937. */
  2938. // cast value in its type
  2939. switch ( innerPropType1 ) {
  2940. case 'int':
  2941. innerPropValue = parseInt( innerPropValue );
  2942. break;
  2943. case 'double':
  2944. innerPropValue = parseFloat( innerPropValue );
  2945. break;
  2946. case 'ColorRGB':
  2947. case 'Vector3D':
  2948. innerPropValue = parseFloatArray( innerPropValue );
  2949. break;
  2950. }
  2951. // CAUTION: these props must append to parent's parent
  2952. this.getPrevNode().properties[ innerPropName ] = {
  2953. 'type': innerPropType1,
  2954. 'type2': innerPropType2,
  2955. 'flag': innerPropFlag,
  2956. 'value': innerPropValue
  2957. };
  2958. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  2959. },
  2960. nodeEnd: function () {
  2961. this.popStack();
  2962. },
  2963. /* ---------------------------------------------------------------- */
  2964. /* util */
  2965. isFlattenNode: function ( node ) {
  2966. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  2967. }
  2968. } );
  2969. // Binary format specification:
  2970. // https://code.blender.org/2013/08/fbx-binary-file-format-specification/
  2971. // https://wiki.rogiken.org/specifications/file-format/fbx/ (more detail but Japanese)
  2972. function BinaryParser() {}
  2973. Object.assign( BinaryParser.prototype, {
  2974. /**
  2975. * Parses binary data and builds FBXTree as much compatible as possible with the one built by TextParser.
  2976. * @param {ArrayBuffer} buffer
  2977. * @returns {THREE.FBXTree}
  2978. */
  2979. parse: function ( buffer ) {
  2980. var reader = new BinaryReader( buffer );
  2981. reader.skip( 23 ); // skip magic 23 bytes
  2982. var version = reader.getUint32();
  2983. console.log( 'THREE.FBXLoader: FBX binary version: ' + version );
  2984. var allNodes = new FBXTree();
  2985. while ( ! this.endOfContent( reader ) ) {
  2986. var node = this.parseNode( reader, version );
  2987. if ( node !== null ) allNodes.add( node.name, node );
  2988. }
  2989. return allNodes;
  2990. },
  2991. /**
  2992. * Checks if reader has reached the end of content.
  2993. * @param {BinaryReader} reader
  2994. * @returns {boolean}
  2995. */
  2996. endOfContent: function( reader ) {
  2997. // footer size: 160bytes + 16-byte alignment padding
  2998. // - 16bytes: magic
  2999. // - padding til 16-byte alignment (at least 1byte?)
  3000. // (seems like some exporters embed fixed 15 or 16bytes?)
  3001. // - 4bytes: magic
  3002. // - 4bytes: version
  3003. // - 120bytes: zero
  3004. // - 16bytes: magic
  3005. if ( reader.size() % 16 === 0 ) {
  3006. return ( ( reader.getOffset() + 160 + 16 ) & ~0xf ) >= reader.size();
  3007. } else {
  3008. return reader.getOffset() + 160 + 16 >= reader.size();
  3009. }
  3010. },
  3011. /**
  3012. * Parses Node as much compatible as possible with the one parsed by TextParser
  3013. * TODO: could be optimized more?
  3014. * @param {BinaryReader} reader
  3015. * @param {number} version
  3016. * @returns {Object} - Returns an Object as node, or null if NULL-record.
  3017. */
  3018. parseNode: function ( reader, version ) {
  3019. // The first three data sizes depends on version.
  3020. var endOffset = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3021. var numProperties = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3022. var propertyListLen = ( version >= 7500 ) ? reader.getUint64() : reader.getUint32();
  3023. var nameLen = reader.getUint8();
  3024. var name = reader.getString( nameLen );
  3025. // Regards this node as NULL-record if endOffset is zero
  3026. if ( endOffset === 0 ) return null;
  3027. var propertyList = [];
  3028. for ( var i = 0; i < numProperties; i ++ ) {
  3029. propertyList.push( this.parseProperty( reader ) );
  3030. }
  3031. // Regards the first three elements in propertyList as id, attrName, and attrType
  3032. var id = propertyList.length > 0 ? propertyList[ 0 ] : '';
  3033. var attrName = propertyList.length > 1 ? propertyList[ 1 ] : '';
  3034. var attrType = propertyList.length > 2 ? propertyList[ 2 ] : '';
  3035. var subNodes = {};
  3036. var properties = {};
  3037. var isSingleProperty = false;
  3038. // if this node represents just a single property
  3039. // like (name, 0) set or (name2, [0, 1, 2]) set of {name: 0, name2: [0, 1, 2]}
  3040. if ( numProperties === 1 && reader.getOffset() === endOffset ) {
  3041. isSingleProperty = true;
  3042. }
  3043. while ( endOffset > reader.getOffset() ) {
  3044. var node = this.parseNode( reader, version );
  3045. if ( node === null ) continue;
  3046. // special case: child node is single property
  3047. if ( node.singleProperty === true ) {
  3048. var value = node.propertyList[ 0 ];
  3049. if ( Array.isArray( value ) ) {
  3050. // node represents
  3051. // Vertices: *3 {
  3052. // a: 0.01, 0.02, 0.03
  3053. // }
  3054. // of text format here.
  3055. node.properties[ node.name ] = node.propertyList[ 0 ];
  3056. subNodes[ node.name ] = node;
  3057. // Later phase expects single property array is in node.properties.a as String.
  3058. // TODO: optimize
  3059. node.properties.a = value.toString();
  3060. } else {
  3061. // node represents
  3062. // Version: 100
  3063. // of text format here.
  3064. properties[ node.name ] = value;
  3065. }
  3066. continue;
  3067. }
  3068. // special case: connections
  3069. if ( name === 'Connections' && node.name === 'C' ) {
  3070. var array = [];
  3071. // node.propertyList would be like
  3072. // ["OO", 111264976, 144038752, "d|x"] (?, from, to, additional values)
  3073. for ( var i = 1, il = node.propertyList.length; i < il; i ++ ) {
  3074. array[ i - 1 ] = node.propertyList[ i ];
  3075. }
  3076. if ( properties.connections === undefined ) {
  3077. properties.connections = [];
  3078. }
  3079. properties.connections.push( array );
  3080. continue;
  3081. }
  3082. // special case: child node is Properties\d+
  3083. if ( node.name.match( /^Properties\d+$/ ) ) {
  3084. // move child node's properties to this node.
  3085. var keys = Object.keys( node.properties );
  3086. for ( var i = 0, il = keys.length; i < il; i ++ ) {
  3087. var key = keys[ i ];
  3088. properties[ key ] = node.properties[ key ];
  3089. }
  3090. continue;
  3091. }
  3092. // special case: properties
  3093. if ( name.match( /^Properties\d+$/ ) && node.name === 'P' ) {
  3094. var innerPropName = node.propertyList[ 0 ];
  3095. var innerPropType1 = node.propertyList[ 1 ];
  3096. var innerPropType2 = node.propertyList[ 2 ];
  3097. var innerPropFlag = node.propertyList[ 3 ];
  3098. var innerPropValue;
  3099. if ( innerPropName.indexOf( 'Lcl ' ) === 0 ) innerPropName = innerPropName.replace( 'Lcl ', 'Lcl_' );
  3100. if ( innerPropType1.indexOf( 'Lcl ' ) === 0 ) innerPropType1 = innerPropType1.replace( 'Lcl ', 'Lcl_' );
  3101. if ( innerPropType1 === 'ColorRGB' || innerPropType1 === 'Vector' ||
  3102. innerPropType1 === 'Vector3D' || innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3103. innerPropValue = [
  3104. node.propertyList[ 4 ],
  3105. node.propertyList[ 5 ],
  3106. node.propertyList[ 6 ]
  3107. ];
  3108. } else {
  3109. innerPropValue = node.propertyList[ 4 ];
  3110. }
  3111. if ( innerPropType1.indexOf( 'Lcl_' ) === 0 ) {
  3112. innerPropValue = innerPropValue.toString();
  3113. }
  3114. // this will be copied to parent. see above.
  3115. properties[ innerPropName ] = {
  3116. 'type': innerPropType1,
  3117. 'type2': innerPropType2,
  3118. 'flag': innerPropFlag,
  3119. 'value': innerPropValue
  3120. };
  3121. continue;
  3122. }
  3123. // standard case
  3124. // follows TextParser's manner.
  3125. if ( subNodes[ node.name ] === undefined ) {
  3126. if ( typeof node.id === 'number' ) {
  3127. subNodes[ node.name ] = {};
  3128. subNodes[ node.name ][ node.id ] = node;
  3129. } else {
  3130. subNodes[ node.name ] = node;
  3131. }
  3132. } else {
  3133. if ( node.id === '' ) {
  3134. if ( ! Array.isArray( subNodes[ node.name ] ) ) {
  3135. subNodes[ node.name ] = [ subNodes[ node.name ] ];
  3136. }
  3137. subNodes[ node.name ].push( node );
  3138. } else {
  3139. if ( subNodes[ node.name ][ node.id ] === undefined ) {
  3140. subNodes[ node.name ][ node.id ] = node;
  3141. } else {
  3142. // conflict id. irregular?
  3143. if ( ! Array.isArray( subNodes[ node.name ][ node.id ] ) ) {
  3144. subNodes[ node.name ][ node.id ] = [ subNodes[ node.name ][ node.id ] ];
  3145. }
  3146. subNodes[ node.name ][ node.id ].push( node );
  3147. }
  3148. }
  3149. }
  3150. }
  3151. return {
  3152. singleProperty: isSingleProperty,
  3153. id: id,
  3154. attrName: attrName,
  3155. attrType: attrType,
  3156. name: name,
  3157. properties: properties,
  3158. propertyList: propertyList, // raw property list, would be used by parent
  3159. subNodes: subNodes
  3160. };
  3161. },
  3162. parseProperty: function ( reader ) {
  3163. var type = reader.getChar();
  3164. switch ( type ) {
  3165. case 'F':
  3166. return reader.getFloat32();
  3167. case 'D':
  3168. return reader.getFloat64();
  3169. case 'L':
  3170. return reader.getInt64();
  3171. case 'I':
  3172. return reader.getInt32();
  3173. case 'Y':
  3174. return reader.getInt16();
  3175. case 'C':
  3176. return reader.getBoolean();
  3177. case 'f':
  3178. case 'd':
  3179. case 'l':
  3180. case 'i':
  3181. case 'b':
  3182. var arrayLength = reader.getUint32();
  3183. var encoding = reader.getUint32(); // 0: non-compressed, 1: compressed
  3184. var compressedLength = reader.getUint32();
  3185. if ( encoding === 0 ) {
  3186. switch ( type ) {
  3187. case 'f':
  3188. return reader.getFloat32Array( arrayLength );
  3189. case 'd':
  3190. return reader.getFloat64Array( arrayLength );
  3191. case 'l':
  3192. return reader.getInt64Array( arrayLength );
  3193. case 'i':
  3194. return reader.getInt32Array( arrayLength );
  3195. case 'b':
  3196. return reader.getBooleanArray( arrayLength );
  3197. }
  3198. }
  3199. if ( window.Zlib === undefined ) {
  3200. throw new Error( 'THREE.FBXLoader: External library Inflate.min.js required, obtain or import from https://github.com/imaya/zlib.js' );
  3201. }
  3202. var inflate = new Zlib.Inflate( new Uint8Array( reader.getArrayBuffer( compressedLength ) ) );
  3203. var reader2 = new BinaryReader( inflate.decompress().buffer );
  3204. switch ( type ) {
  3205. case 'f':
  3206. return reader2.getFloat32Array( arrayLength );
  3207. case 'd':
  3208. return reader2.getFloat64Array( arrayLength );
  3209. case 'l':
  3210. return reader2.getInt64Array( arrayLength );
  3211. case 'i':
  3212. return reader2.getInt32Array( arrayLength );
  3213. case 'b':
  3214. return reader2.getBooleanArray( arrayLength );
  3215. }
  3216. case 'S':
  3217. var length = reader.getUint32();
  3218. return reader.getString( length );
  3219. case 'R':
  3220. var length = reader.getUint32();
  3221. return reader.getArrayBuffer( length );
  3222. default:
  3223. throw new Error( 'THREE.FBXLoader: Unknown property type ' + type );
  3224. }
  3225. }
  3226. } );
  3227. function BinaryReader( buffer, littleEndian ) {
  3228. this.dv = new DataView( buffer );
  3229. this.offset = 0;
  3230. this.littleEndian = ( littleEndian !== undefined ) ? littleEndian : true;
  3231. }
  3232. Object.assign( BinaryReader.prototype, {
  3233. getOffset: function () {
  3234. return this.offset;
  3235. },
  3236. size: function () {
  3237. return this.dv.buffer.byteLength;
  3238. },
  3239. skip: function ( length ) {
  3240. this.offset += length;
  3241. },
  3242. // seems like true/false representation depends on exporter.
  3243. // true: 1 or 'Y'(=0x59), false: 0 or 'T'(=0x54)
  3244. // then sees LSB.
  3245. getBoolean: function () {
  3246. return ( this.getUint8() & 1 ) === 1;
  3247. },
  3248. getBooleanArray: function ( size ) {
  3249. var a = [];
  3250. for ( var i = 0; i < size; i ++ ) {
  3251. a.push( this.getBoolean() );
  3252. }
  3253. return a;
  3254. },
  3255. getInt8: function () {
  3256. var value = this.dv.getInt8( this.offset );
  3257. this.offset += 1;
  3258. return value;
  3259. },
  3260. getInt8Array: function ( size ) {
  3261. var a = [];
  3262. for ( var i = 0; i < size; i ++ ) {
  3263. a.push( this.getInt8() );
  3264. }
  3265. return a;
  3266. },
  3267. getUint8: function () {
  3268. var value = this.dv.getUint8( this.offset );
  3269. this.offset += 1;
  3270. return value;
  3271. },
  3272. getUint8Array: function ( size ) {
  3273. var a = [];
  3274. for ( var i = 0; i < size; i ++ ) {
  3275. a.push( this.getUint8() );
  3276. }
  3277. return a;
  3278. },
  3279. getInt16: function () {
  3280. var value = this.dv.getInt16( this.offset, this.littleEndian );
  3281. this.offset += 2;
  3282. return value;
  3283. },
  3284. getInt16Array: function ( size ) {
  3285. var a = [];
  3286. for ( var i = 0; i < size; i ++ ) {
  3287. a.push( this.getInt16() );
  3288. }
  3289. return a;
  3290. },
  3291. getUint16: function () {
  3292. var value = this.dv.getUint16( this.offset, this.littleEndian );
  3293. this.offset += 2;
  3294. return value;
  3295. },
  3296. getUint16Array: function ( size ) {
  3297. var a = [];
  3298. for ( var i = 0; i < size; i ++ ) {
  3299. a.push( this.getUint16() );
  3300. }
  3301. return a;
  3302. },
  3303. getInt32: function () {
  3304. var value = this.dv.getInt32( this.offset, this.littleEndian );
  3305. this.offset += 4;
  3306. return value;
  3307. },
  3308. getInt32Array: function ( size ) {
  3309. var a = [];
  3310. for ( var i = 0; i < size; i ++ ) {
  3311. a.push( this.getInt32() );
  3312. }
  3313. return a;
  3314. },
  3315. getUint32: function () {
  3316. var value = this.dv.getUint32( this.offset, this.littleEndian );
  3317. this.offset += 4;
  3318. return value;
  3319. },
  3320. getUint32Array: function ( size ) {
  3321. var a = [];
  3322. for ( var i = 0; i < size; i ++ ) {
  3323. a.push( this.getUint32() );
  3324. }
  3325. return a;
  3326. },
  3327. // JavaScript doesn't support 64-bit integer so attempting to calculate by ourselves.
  3328. // 1 << 32 will return 1 so using multiply operation instead here.
  3329. // There'd be a possibility that this method returns wrong value if the value
  3330. // is out of the range between Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER.
  3331. // TODO: safely handle 64-bit integer
  3332. getInt64: function () {
  3333. var low, high;
  3334. if ( this.littleEndian ) {
  3335. low = this.getUint32();
  3336. high = this.getUint32();
  3337. } else {
  3338. high = this.getUint32();
  3339. low = this.getUint32();
  3340. }
  3341. // calculate negative value
  3342. if ( high & 0x80000000 ) {
  3343. high = ~high & 0xFFFFFFFF;
  3344. low = ~low & 0xFFFFFFFF;
  3345. if ( low === 0xFFFFFFFF ) high = ( high + 1 ) & 0xFFFFFFFF;
  3346. low = ( low + 1 ) & 0xFFFFFFFF;
  3347. return - ( high * 0x100000000 + low );
  3348. }
  3349. return high * 0x100000000 + low;
  3350. },
  3351. getInt64Array: function ( size ) {
  3352. var a = [];
  3353. for ( var i = 0; i < size; i ++ ) {
  3354. a.push( this.getInt64() );
  3355. }
  3356. return a;
  3357. },
  3358. // Note: see getInt64() comment
  3359. getUint64: function () {
  3360. var low, high;
  3361. if ( this.littleEndian ) {
  3362. low = this.getUint32();
  3363. high = this.getUint32();
  3364. } else {
  3365. high = this.getUint32();
  3366. low = this.getUint32();
  3367. }
  3368. return high * 0x100000000 + low;
  3369. },
  3370. getUint64Array: function ( size ) {
  3371. var a = [];
  3372. for ( var i = 0; i < size; i ++ ) {
  3373. a.push( this.getUint64() );
  3374. }
  3375. return a;
  3376. },
  3377. getFloat32: function () {
  3378. var value = this.dv.getFloat32( this.offset, this.littleEndian );
  3379. this.offset += 4;
  3380. return value;
  3381. },
  3382. getFloat32Array: function ( size ) {
  3383. var a = [];
  3384. for ( var i = 0; i < size; i ++ ) {
  3385. a.push( this.getFloat32() );
  3386. }
  3387. return a;
  3388. },
  3389. getFloat64: function () {
  3390. var value = this.dv.getFloat64( this.offset, this.littleEndian );
  3391. this.offset += 8;
  3392. return value;
  3393. },
  3394. getFloat64Array: function ( size ) {
  3395. var a = [];
  3396. for ( var i = 0; i < size; i ++ ) {
  3397. a.push( this.getFloat64() );
  3398. }
  3399. return a;
  3400. },
  3401. getArrayBuffer: function ( size ) {
  3402. var value = this.dv.buffer.slice( this.offset, this.offset + size );
  3403. this.offset += size;
  3404. return value;
  3405. },
  3406. getChar: function () {
  3407. return String.fromCharCode( this.getUint8() );
  3408. },
  3409. getString: function ( size ) {
  3410. var s = '';
  3411. while ( size > 0 ) {
  3412. var value = this.getUint8();
  3413. size--;
  3414. if ( value === 0 ) break;
  3415. s += String.fromCharCode( value );
  3416. }
  3417. this.skip( size );
  3418. return s;
  3419. }
  3420. } );
  3421. function FBXTree() {}
  3422. Object.assign( FBXTree.prototype, {
  3423. add: function ( key, val ) {
  3424. this[ key ] = val;
  3425. },
  3426. searchConnectionParent: function ( id ) {
  3427. if ( this.__cache_search_connection_parent === undefined ) {
  3428. this.__cache_search_connection_parent = [];
  3429. }
  3430. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  3431. return this.__cache_search_connection_parent[ id ];
  3432. } else {
  3433. this.__cache_search_connection_parent[ id ] = [];
  3434. }
  3435. var conns = this.Connections.properties.connections;
  3436. var results = [];
  3437. for ( var i = 0; i < conns.length; ++ i ) {
  3438. if ( conns[ i ][ 0 ] == id ) {
  3439. // 0 means scene root
  3440. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  3441. results.push( res );
  3442. }
  3443. }
  3444. if ( results.length > 0 ) {
  3445. append( this.__cache_search_connection_parent[ id ], results );
  3446. return results;
  3447. } else {
  3448. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  3449. return [ - 1 ];
  3450. }
  3451. },
  3452. searchConnectionChildren: function ( id ) {
  3453. if ( this.__cache_search_connection_children === undefined ) {
  3454. this.__cache_search_connection_children = [];
  3455. }
  3456. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  3457. return this.__cache_search_connection_children[ id ];
  3458. } else {
  3459. this.__cache_search_connection_children[ id ] = [];
  3460. }
  3461. var conns = this.Connections.properties.connections;
  3462. var res = [];
  3463. for ( var i = 0; i < conns.length; ++ i ) {
  3464. if ( conns[ i ][ 1 ] == id ) {
  3465. // 0 means scene root
  3466. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  3467. // there may more than one kid, then search to the end
  3468. }
  3469. }
  3470. if ( res.length > 0 ) {
  3471. append( this.__cache_search_connection_children[ id ], res );
  3472. return res;
  3473. } else {
  3474. this.__cache_search_connection_children[ id ] = [ ];
  3475. return [ ];
  3476. }
  3477. },
  3478. searchConnectionType: function ( id, to ) {
  3479. var key = id + ',' + to; // TODO: to hash
  3480. if ( this.__cache_search_connection_type === undefined ) {
  3481. this.__cache_search_connection_type = {};
  3482. }
  3483. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  3484. return this.__cache_search_connection_type[ key ];
  3485. } else {
  3486. this.__cache_search_connection_type[ key ] = '';
  3487. }
  3488. var conns = this.Connections.properties.connections;
  3489. for ( var i = 0; i < conns.length; ++ i ) {
  3490. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  3491. // 0 means scene root
  3492. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  3493. return conns[ i ][ 2 ];
  3494. }
  3495. }
  3496. this.__cache_search_connection_type[ id ] = null;
  3497. return null;
  3498. }
  3499. } );
  3500. /**
  3501. * @param {ArrayBuffer} buffer
  3502. * @returns {boolean}
  3503. */
  3504. function isFbxFormatBinary( buffer ) {
  3505. var CORRECT = 'Kaydara FBX Binary \0';
  3506. return buffer.byteLength >= CORRECT.length && CORRECT === convertArrayBufferToString( buffer, 0, CORRECT.length );
  3507. }
  3508. /**
  3509. * @returns {boolean}
  3510. */
  3511. function isFbxFormatASCII( text ) {
  3512. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  3513. var cursor = 0;
  3514. function read( offset ) {
  3515. var result = text[ offset - 1 ];
  3516. text = text.slice( cursor + offset );
  3517. cursor ++;
  3518. return result;
  3519. }
  3520. for ( var i = 0; i < CORRECT.length; ++ i ) {
  3521. var num = read( 1 );
  3522. if ( num === CORRECT[ i ] ) {
  3523. return false;
  3524. }
  3525. }
  3526. return true;
  3527. }
  3528. /**
  3529. * @returns {number}
  3530. */
  3531. function getFbxVersion( text ) {
  3532. var versionRegExp = /FBXVersion: (\d+)/;
  3533. var match = text.match( versionRegExp );
  3534. if ( match ) {
  3535. var version = parseInt( match[ 1 ] );
  3536. return version;
  3537. }
  3538. throw new Error( 'THREE.FBXLoader: Cannot find the version number for the file given.' );
  3539. }
  3540. /**
  3541. * Converts FBX ticks into real time seconds.
  3542. * @param {number} time - FBX tick timestamp to convert.
  3543. * @returns {number} - FBX tick in real world time.
  3544. */
  3545. function convertFBXTimeToSeconds( time ) {
  3546. // Constant is FBX ticks per second.
  3547. return time / 46186158000;
  3548. }
  3549. /**
  3550. * Parses comma separated list of float numbers and returns them in an array.
  3551. * @example
  3552. * // Returns [ 5.6, 9.4, 2.5, 1.4 ]
  3553. * parseFloatArray( "5.6,9.4,2.5,1.4" )
  3554. * @returns {number[]}
  3555. */
  3556. function parseFloatArray( string ) {
  3557. var array = string.split( ',' );
  3558. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3559. array[ i ] = parseFloat( array[ i ] );
  3560. }
  3561. return array;
  3562. }
  3563. /**
  3564. * Parses comma separated list of int numbers and returns them in an array.
  3565. * @example
  3566. * // Returns [ 5, 8, 2, 3 ]
  3567. * parseFloatArray( "5,8,2,3" )
  3568. * @returns {number[]}
  3569. */
  3570. function parseIntArray( string ) {
  3571. var array = string.split( ',' );
  3572. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3573. array[ i ] = parseInt( array[ i ] );
  3574. }
  3575. return array;
  3576. }
  3577. /**
  3578. * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
  3579. * @param {FBXVector3} property - Property to parse as Vector3.
  3580. * @returns {THREE.Vector3}
  3581. */
  3582. function parseVector3( property ) {
  3583. return new THREE.Vector3().fromArray( property.value );
  3584. }
  3585. /**
  3586. * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
  3587. * @param {FBXVector3} property - Property to parse as Color.
  3588. * @returns {THREE.Color}
  3589. */
  3590. function parseColor( property ) {
  3591. return new THREE.Color().fromArray( property.value );
  3592. }
  3593. function parseMatrixArray( floatString ) {
  3594. return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
  3595. }
  3596. /**
  3597. * Converts ArrayBuffer to String.
  3598. * @param {ArrayBuffer} buffer
  3599. * @param {number} from
  3600. * @param {number} to
  3601. * @returns {String}
  3602. */
  3603. function convertArrayBufferToString( buffer, from, to ) {
  3604. if ( from === undefined ) from = 0;
  3605. if ( to === undefined ) to = buffer.byteLength;
  3606. var array = new Uint8Array( buffer, from, to );
  3607. if ( window.TextDecoder !== undefined ) {
  3608. return new TextDecoder().decode( array );
  3609. }
  3610. var s = '';
  3611. for ( var i = 0, il = array.length; i < il; i ++ ) {
  3612. s += String.fromCharCode( array[ i ] );
  3613. }
  3614. return s;
  3615. }
  3616. /**
  3617. * Converts number from degrees into radians.
  3618. * @param {number} value
  3619. * @returns {number}
  3620. */
  3621. function degreeToRadian( value ) {
  3622. return value * DEG2RAD;
  3623. }
  3624. var DEG2RAD = Math.PI / 180;
  3625. //
  3626. function findIndex( array, func ) {
  3627. for ( var i = 0, l = array.length; i < l; i ++ ) {
  3628. if ( func( array[ i ] ) ) return i;
  3629. }
  3630. return -1;
  3631. }
  3632. function append( a, b ) {
  3633. for ( var i = 0, j = a.length, l = b.length; i < l; i ++, j ++ ) {
  3634. a[ j ] = b[ i ];
  3635. }
  3636. }
  3637. function slice( a, b, from, to ) {
  3638. for ( var i = from, j = 0; i < to; i ++, j ++ ) {
  3639. a[ j ] = b[ i ];
  3640. }
  3641. return a;
  3642. }
  3643. } )();