2
0

FBXLoader.js 100 KB

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