aframe-extras.loaders.js 119 KB

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