FBXLoader.js 91 KB

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