FBXLoader.js 95 KB

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