FBXLoader.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724
  1. /**
  2. * @author yamahigashi https://github.com/yamahigashi
  3. * @author Kyle-Larson https://github.com/Kyle-Larson
  4. *
  5. * This loader loads FBX file in *ASCII and version 7 format*.
  6. *
  7. * Support
  8. * - mesh
  9. * - skinning
  10. * - normal / uv
  11. * - material (Multi-Material too)
  12. * - textures (Must be in same directory)
  13. * - nurbs
  14. *
  15. * No Support
  16. * - morph
  17. */
  18. ( function () {
  19. THREE.FBXLoader = function ( manager ) {
  20. THREE.Loader.call( this );
  21. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  22. this.textureLoader = null;
  23. this.textureBasePath = null;
  24. };
  25. Object.assign( THREE.FBXLoader.prototype, THREE.Loader.prototype );
  26. THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
  27. Object.assign( THREE.FBXLoader.prototype, {
  28. load: function ( url, onLoad, onProgress, onError ) {
  29. var scope = this;
  30. var loader = new THREE.FileLoader( scope.manager );
  31. // loader.setCrossOrigin( this.crossOrigin );
  32. loader.load( url, function ( text ) {
  33. if ( ! scope.isFbxFormatASCII( text ) ) {
  34. console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' );
  35. } else if ( ! scope.isFbxVersionSupported( text ) ) {
  36. console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' );
  37. } else {
  38. scope.textureBasePath = scope.extractUrlBase( url );
  39. onLoad( scope.parse( text ) );
  40. }
  41. }, onProgress, onError );
  42. },
  43. setCrossOrigin: function ( value ) {
  44. this.crossOrigin = value;
  45. },
  46. isFbxFormatASCII: function ( body ) {
  47. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  48. var cursor = 0;
  49. var read = function ( offset ) {
  50. var result = body[ offset - 1 ];
  51. body = body.slice( cursor + offset );
  52. cursor ++;
  53. return result;
  54. };
  55. for ( var i = 0; i < CORRECT.length; ++ i ) {
  56. var num = read( 1 );
  57. if ( num == CORRECT[ i ] ) {
  58. return false;
  59. }
  60. }
  61. return true;
  62. },
  63. isFbxVersionSupported: function ( body ) {
  64. var versionExp = /FBXVersion: (\d+)/;
  65. var match = body.match( versionExp );
  66. if ( match ) {
  67. var version = parseInt( match[ 1 ] );
  68. console.log( 'FBXLoader: FBX version ' + version );
  69. return version >= 7000;
  70. }
  71. return false;
  72. },
  73. parse: function ( text ) {
  74. var scope = this;
  75. console.time( 'FBXLoader' );
  76. console.time( 'FBXLoader: TextParser' );
  77. var nodes = new FBXParser().parse( text );
  78. console.timeEnd( 'FBXLoader: TextParser' );
  79. console.time( 'FBXLoader: ObjectParser' );
  80. scope.hierarchy = ( new Bones() ).parseHierarchy( nodes );
  81. scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy );
  82. scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy );
  83. scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy );
  84. scope.materials = ( new Materials() ).parse( nodes, scope.hierarchy );
  85. scope.geometries = ( new Geometries() ).parse( nodes, scope.hierarchy );
  86. console.timeEnd( 'FBXLoader: ObjectParser' );
  87. this.texture_cache = {};
  88. this.material_cache = {};
  89. this.geometry_cache = {};
  90. console.time( 'FBXLoader: MeshParser' );
  91. var meshes = this.parseMeshes( nodes );
  92. console.timeEnd( 'FBXLoader: MeshParser' );
  93. var container = new THREE.Group();
  94. for ( var i = 0; i < meshes.length; ++ i ) {
  95. if ( meshes[ i ] === undefined ) {
  96. continue;
  97. }
  98. container.add( meshes[ i ] );
  99. }
  100. console.timeEnd( 'FBXLoader' );
  101. return container;
  102. },
  103. getTexture: function ( texNode ) {
  104. if ( ! ( texNode.id in this.texture_cache ) ) {
  105. if ( this.textureLoader === null ) {
  106. this.textureLoader = new THREE.TextureLoader();
  107. }
  108. this.texture_cache[ texNode.id ] = this.textureLoader.load( this.textureBasePath + '/' + texNode.fileName );
  109. }
  110. return this.texture_cache[ texNode.id ];
  111. },
  112. getMaterial: function ( matNode, nodes ) {
  113. if ( ! ( matNode.id in this.material_cache ) ) {
  114. // TODO:
  115. // Cannot find a list of possible ShadingModel values.
  116. // If someone finds a list, please add additional cases
  117. // and map to appropriate materials.
  118. var tmpMat;
  119. switch ( matNode.type ) {
  120. case "phong":
  121. tmpMat = new THREE.MeshPhongMaterial();
  122. break;
  123. case "lambert":
  124. tmpMat = new THREE.MeshLambertMaterial();
  125. break;
  126. default:
  127. console.warn( "No implementation given for material type " + matNode.type + " in FBXLoader.js. Defaulting to basic material" );
  128. tmpMat = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  129. break;
  130. }
  131. var children = nodes.searchConnectionChildren( matNode.id );
  132. for ( var i = 0; i < children.length; ++ i ) {
  133. var type = nodes.searchConnectionType( children[ i ], matNode.id );
  134. switch ( type ) {
  135. case " \"AmbientColor":
  136. //TODO: Support AmbientColor textures
  137. break;
  138. case " \"DiffuseColor":
  139. matNode.parameters.map = this.getTexture( this.textures.textures[ children[ i ] ] );
  140. break;
  141. default:
  142. console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
  143. break;
  144. }
  145. }
  146. tmpMat.setValues( matNode.parameters );
  147. this.material_cache[ matNode.id ] = tmpMat;
  148. }
  149. return this.material_cache[ matNode.id ];
  150. },
  151. getGeometry: function ( geoNode ) {
  152. if ( ! ( geoNode.id in this.geometry_cache ) ) {
  153. var tmpGeo = new THREE.BufferGeometry();
  154. tmpGeo.name = geoNode.name;
  155. tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.positionBuffer ), 3 ) );
  156. if ( geoNode.normalBuffer !== undefined && geoNode.normalBuffer.length > 0 ) {
  157. tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normalBuffer ), 3 ) );
  158. }
  159. if ( geoNode.uvBuffer !== undefined && geoNode.uvBuffer.length > 0 ) {
  160. tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvBuffer ), 2 ) );
  161. }
  162. tmpGeo.verticesNeedUpdate = true;
  163. tmpGeo.computeBoundingSphere();
  164. tmpGeo.computeBoundingBox();
  165. //Material groupings
  166. if ( geoNode.materialBuffer.length > 1 ) {
  167. tmpGeo.groups = [];
  168. for ( var i = 0, prevIndex = - 1; i < geoNode.materialBuffer.length; ++ i ) {
  169. if ( geoNode.materialBuffer[ i ] !== prevIndex ) {
  170. tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialBuffer[ i ] } );
  171. prevIndex = geoNode.materialBuffer[ i ];
  172. }
  173. tmpGeo.groups[ tmpGeo.groups.length - 1 ].count += 3;
  174. }
  175. }
  176. this.geometry_cache[ geoNode.id ] = tmpGeo;
  177. this.geometry_cache[ geoNode.id ].bones = geoNode.bones;
  178. this.geometry_cache[ geoNode.id ].skinIndices = this.weights.skinIndices;
  179. this.geometry_cache[ geoNode.id ].skinWeights = this.weights.skinWeights;
  180. }
  181. return this.geometry_cache[ geoNode.id ];
  182. },
  183. parseMeshes: function ( node ) {
  184. var modelNode = node.Objects.subNodes.Model;
  185. var meshes = [];
  186. for ( var ID in modelNode ) {
  187. if ( modelNode[ ID ].attrType === 'Mesh' ) {
  188. //Parse Mesh
  189. meshes.push( this.parseMesh( modelNode[ ID ], node ) );
  190. } else if ( modelNode[ ID ].attrType === 'NurbsCurve' ) {
  191. //Parse NURBS
  192. meshes.push( this.parseNURBS( modelNode[ ID ], node ) );
  193. }
  194. }
  195. return meshes;
  196. },
  197. parseFloatList: function ( floatList ) {
  198. return floatList.split( ',' ).map( function ( number ) {
  199. return parseFloat( number );
  200. } );
  201. },
  202. parseNURBS: function ( meshNode, FBXNodes ) {
  203. if ( THREE.NURBSCurve === undefined ) {
  204. console.error( "THREE.FBXLoader relies on THREE.NURBSCurve" );
  205. return;
  206. }
  207. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  208. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  209. var nurbsInfo;
  210. for ( var i = 0; i < children.length; ++ i ) {
  211. if ( children[ i ] in geoNodes ) {
  212. nurbsInfo = geoNodes[ children[ i ] ];
  213. break;
  214. }
  215. }
  216. if ( nurbsInfo === undefined ) {
  217. return;
  218. }
  219. var order = parseInt( nurbsInfo.properties.Order );
  220. if ( isNaN( order ) ) {
  221. console.error( "Invalid Order: `" + nurbsInfo.properties.Order + "` (should be an integer)" );
  222. return;
  223. }
  224. var knots = this.parseFloatList( nurbsInfo.subNodes.KnotVector.properties.a );
  225. var controlPoints = [];
  226. var pointsValues = this.parseFloatList( nurbsInfo.subNodes.Points.properties.a );
  227. for ( var i = 0; i < pointsValues.length; i += 4 ) {
  228. // NURBSCurve recreates a Vector4, so no need to construct it twice
  229. controlPoints.push( { x: pointsValues[ i ], y: pointsValues[ i + 1 ], z: pointsValues[ i + 2 ], w: pointsValues[ i + 3 ] } );
  230. }
  231. if ( nurbsInfo.properties.Form == "Closed" ) {
  232. controlPoints.push( controlPoints[ 0 ] );
  233. }
  234. var curve = new THREE.NURBSCurve( order - 1, knots, controlPoints );
  235. // Pre-generate a geometry
  236. var geometry = new THREE.Geometry();
  237. geometry.vertices = curve.getPoints( controlPoints.length * 1.5 );
  238. var mesh = new THREE.Line( geometry );
  239. // Store the THREE.NURBSCurve class so the user can recreate a new geometry with a different number of points
  240. mesh.userData.curve = curve;
  241. return mesh;
  242. },
  243. parseMesh: function ( meshNode, FBXNodes ) {
  244. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  245. var matNodes = FBXNodes.Objects.subNodes.Material;
  246. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  247. var geometry;
  248. var materials = [];
  249. var material;
  250. var mesh;
  251. for ( var i = 0; i < children.length; ++ i ) {
  252. if ( children[ i ] in geoNodes ) {
  253. geometry = this.getGeometry( this.geometries.geometries[ children[ i ] ] );
  254. continue;
  255. }
  256. if ( children[ i ] in matNodes ) {
  257. materials.push( this.getMaterial( this.materials.materials[ children[ i ] ], FBXNodes ) );
  258. continue;
  259. }
  260. }
  261. if ( materials.length > 1 ) {
  262. material = new THREE.MultiMaterial( materials );
  263. //material = materials[ 0 ];
  264. } else {
  265. material = materials[ 0 ];
  266. }
  267. if ( geometry.bones !== undefined && geometry.skinWeights !== undefined && geometry.skinWeights.length > 0 ) {
  268. if ( material instanceof THREE.MultiMaterial ) {
  269. for ( var i = 0; i < material.materials.length; ++ i ) {
  270. material.materials[ i ].skinning = true;
  271. }
  272. } else {
  273. material.skinning = true;
  274. }
  275. mesh = new THREE.SkinnedMesh( geometry, material );
  276. } else {
  277. mesh = new THREE.Mesh( geometry, material );
  278. }
  279. if ( this.animations !== undefined ) {
  280. this.addAnimation( mesh, this.weights.matrices, this.animations );
  281. }
  282. return mesh;
  283. },
  284. addAnimation: function ( mesh, matrices, animations ) {
  285. for ( var key in animations.stacks ) {
  286. var animationData = {
  287. name: animations.stacks[ key ].name,
  288. fps: 30,
  289. length: animations.stacks[ key ].length,
  290. hierarchy: []
  291. };
  292. for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) {
  293. var name = mesh.geometry.bones[ i ].name;
  294. name = name.replace( /.*:/, '' );
  295. animationData.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } );
  296. }
  297. function hasCurve( animNode, attr ) {
  298. if ( animNode === undefined ) {
  299. return false;
  300. }
  301. var attrNode;
  302. switch ( attr ) {
  303. case 'S':
  304. if ( ! ( animNode.S ) ) {
  305. return false;
  306. }
  307. attrNode = animNode.S;
  308. break;
  309. case 'R':
  310. if ( ! ( animNode.R ) ) {
  311. return false;
  312. }
  313. attrNode = animNode.R;
  314. break;
  315. case 'T':
  316. if ( ! ( animNode.T ) ) {
  317. return false;
  318. }
  319. attrNode = animNode.T;
  320. break;
  321. }
  322. if ( attrNode.curves.x === undefined ) {
  323. return false;
  324. }
  325. if ( attrNode.curves.y === undefined ) {
  326. return false;
  327. }
  328. if ( attrNode.curves.z === undefined ) {
  329. return false;
  330. }
  331. return true;
  332. }
  333. function hasKeyOnFrame( attrNode, frame ) {
  334. var x = isKeyExistOnFrame( attrNode.curves.x, frame );
  335. var y = isKeyExistOnFrame( attrNode.curves.y, frame );
  336. var z = isKeyExistOnFrame( attrNode.curves.z, frame );
  337. return x && y && z;
  338. }
  339. function isKeyExistOnFrame( curve, frame ) {
  340. var value = curve.values[ frame ];
  341. return value !== undefined;
  342. }
  343. function genKey( animNode, bone ) {
  344. // key initialize with its bone's bind pose at first
  345. var key = {};
  346. key.time = frame / animations.fps; // TODO:
  347. key.pos = bone.pos;
  348. key.rot = bone.rotq;
  349. key.scl = bone.scl;
  350. if ( animNode === undefined ) {
  351. return key;
  352. }
  353. try {
  354. if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) {
  355. var pos = new THREE.Vector3(
  356. animNode.T.curves.x.values[ frame ],
  357. animNode.T.curves.y.values[ frame ],
  358. animNode.T.curves.z.values[ frame ] );
  359. key.pos = [ pos.x, pos.y, pos.z ];
  360. }
  361. if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) {
  362. var rx = degToRad( animNode.R.curves.x.values[ frame ] );
  363. var ry = degToRad( animNode.R.curves.y.values[ frame ] );
  364. var rz = degToRad( animNode.R.curves.z.values[ frame ] );
  365. var eul = new THREE.Vector3( rx, ry, rz );
  366. var rot = quatFromVec( eul.x, eul.y, eul.z );
  367. key.rot = [ rot.x, rot.y, rot.z, rot.w ];
  368. }
  369. if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) {
  370. var scl = new THREE.Vector3(
  371. animNode.S.curves.x.values[ frame ],
  372. animNode.S.curves.y.values[ frame ],
  373. animNode.S.curves.z.values[ frame ] );
  374. key.scl = [ scl.x, scl.y, scl.z ];
  375. }
  376. } catch ( e ) {
  377. // curve is not full plotted
  378. console.log( bone );
  379. console.log( e );
  380. }
  381. return key;
  382. }
  383. var bones = mesh.geometry.bones;
  384. for ( var frame = 0; frame < animations.stacks[ key ].frames; frame ++ ) {
  385. for ( i = 0; i < bones.length; i ++ ) {
  386. var bone = bones[ i ];
  387. var animNode = animations.stacks[ key ].layers[ 0 ][ i ];
  388. for ( var j = 0; j < animationData.hierarchy.length; j ++ ) {
  389. if ( animationData.hierarchy[ j ].name === bone.name ) {
  390. animationData.hierarchy[ j ].keys.push( genKey( animNode, bone ) );
  391. }
  392. }
  393. }
  394. }
  395. if ( mesh.geometry.animations === undefined ) {
  396. mesh.geometry.animations = [];
  397. }
  398. mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationData, mesh.geometry.bones ) );
  399. }
  400. },
  401. loadFile: function ( url, onLoad, onProgress, onError, responseType ) {
  402. var loader = new THREE.FileLoader( this.manager );
  403. loader.setResponseType( responseType );
  404. var request = loader.load( url, onLoad, onProgress, onError );
  405. return request;
  406. },
  407. loadFileAsBuffer: function ( url, onLoad, onProgress, onError ) {
  408. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  409. },
  410. loadFileAsText: function ( url, onLoad, onProgress, onError ) {
  411. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  412. }
  413. } );
  414. /* ----------------------------------------------------------------- */
  415. function FBXNodes() {}
  416. Object.assign( FBXNodes.prototype, {
  417. add: function ( key, val ) {
  418. this[ key ] = val;
  419. },
  420. searchConnectionParent: function ( id ) {
  421. if ( this.__cache_search_connection_parent === undefined ) {
  422. this.__cache_search_connection_parent = [];
  423. }
  424. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  425. return this.__cache_search_connection_parent[ id ];
  426. } else {
  427. this.__cache_search_connection_parent[ id ] = [];
  428. }
  429. var conns = this.Connections.properties.connections;
  430. var results = [];
  431. for ( var i = 0; i < conns.length; ++ i ) {
  432. if ( conns[ i ][ 0 ] == id ) {
  433. // 0 means scene root
  434. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  435. results.push( res );
  436. }
  437. }
  438. if ( results.length > 0 ) {
  439. this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
  440. return results;
  441. } else {
  442. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  443. return [ - 1 ];
  444. }
  445. },
  446. searchConnectionChildren: function ( id ) {
  447. if ( this.__cache_search_connection_children === undefined ) {
  448. this.__cache_search_connection_children = [];
  449. }
  450. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  451. return this.__cache_search_connection_children[ id ];
  452. } else {
  453. this.__cache_search_connection_children[ id ] = [];
  454. }
  455. var conns = this.Connections.properties.connections;
  456. var res = [];
  457. for ( var i = 0; i < conns.length; ++ i ) {
  458. if ( conns[ i ][ 1 ] == id ) {
  459. // 0 means scene root
  460. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  461. // there may more than one kid, then search to the end
  462. }
  463. }
  464. if ( res.length > 0 ) {
  465. this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
  466. return res;
  467. } else {
  468. this.__cache_search_connection_children[ id ] = [ ];
  469. return [ ];
  470. }
  471. },
  472. searchConnectionType: function ( id, to ) {
  473. var key = id + ',' + to; // TODO: to hash
  474. if ( this.__cache_search_connection_type === undefined ) {
  475. this.__cache_search_connection_type = {};
  476. }
  477. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  478. return this.__cache_search_connection_type[ key ];
  479. } else {
  480. this.__cache_search_connection_type[ key ] = '';
  481. }
  482. var conns = this.Connections.properties.connections;
  483. for ( var i = 0; i < conns.length; ++ i ) {
  484. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  485. // 0 means scene root
  486. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  487. return conns[ i ][ 2 ];
  488. }
  489. }
  490. this.__cache_search_connection_type[ id ] = null;
  491. return null;
  492. }
  493. } );
  494. function FBXParser() {}
  495. Object.assign( FBXParser.prototype, {
  496. getPrevNode: function () {
  497. return this.nodeStack[ this.currentIndent - 2 ];
  498. },
  499. getCurrentNode: function () {
  500. return this.nodeStack[ this.currentIndent - 1 ];
  501. },
  502. getCurrentProp: function () {
  503. return this.currentProp;
  504. },
  505. pushStack: function ( node ) {
  506. this.nodeStack.push( node );
  507. this.currentIndent += 1;
  508. },
  509. popStack: function () {
  510. this.nodeStack.pop();
  511. this.currentIndent -= 1;
  512. },
  513. setCurrentProp: function ( val, name ) {
  514. this.currentProp = val;
  515. this.currentPropName = name;
  516. },
  517. // ----------parse ---------------------------------------------------
  518. parse: function ( text ) {
  519. this.currentIndent = 0;
  520. this.allNodes = new FBXNodes();
  521. this.nodeStack = [];
  522. this.currentProp = [];
  523. this.currentPropName = '';
  524. var split = text.split( "\n" );
  525. for ( var line in split ) {
  526. var l = split[ line ];
  527. // short cut
  528. if ( l.match( /^[\s\t]*;/ ) ) {
  529. continue;
  530. } // skip comment line
  531. if ( l.match( /^[\s\t]*$/ ) ) {
  532. continue;
  533. } // skip empty line
  534. // beginning of node
  535. var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
  536. var match = l.match( beginningOfNodeExp );
  537. if ( match ) {
  538. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
  539. var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
  540. return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
  541. } );
  542. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  543. continue;
  544. }
  545. // node's property
  546. var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
  547. var match = l.match( propExp );
  548. if ( match ) {
  549. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  550. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  551. this.parseNodeProperty( l, propName, propValue );
  552. continue;
  553. }
  554. // end of node
  555. var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
  556. if ( l.match( endOfNodeExp ) ) {
  557. this.nodeEnd();
  558. continue;
  559. }
  560. // for special case,
  561. //
  562. // Vertices: *8670 {
  563. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  564. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  565. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  566. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  567. //
  568. // these case the lines must contiue with previous line
  569. if ( l.match( /^[^\s\t}]/ ) ) {
  570. this.parseNodePropertyContinued( l );
  571. }
  572. }
  573. return this.allNodes;
  574. },
  575. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  576. // var nodeName = match[1];
  577. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  578. var attrs = this.parseNodeAttr( nodeAttrs );
  579. var currentNode = this.getCurrentNode();
  580. // a top node
  581. if ( this.currentIndent === 0 ) {
  582. this.allNodes.add( nodeName, node );
  583. } else {
  584. // a subnode
  585. // already exists subnode, then append it
  586. if ( nodeName in currentNode.subNodes ) {
  587. var tmp = currentNode.subNodes[ nodeName ];
  588. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  589. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  590. if ( attrs.id === '' ) {
  591. currentNode.subNodes[ nodeName ] = [];
  592. currentNode.subNodes[ nodeName ].push( tmp );
  593. } else {
  594. currentNode.subNodes[ nodeName ] = {};
  595. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  596. }
  597. }
  598. if ( attrs.id === '' ) {
  599. currentNode.subNodes[ nodeName ].push( node );
  600. } else {
  601. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  602. }
  603. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  604. currentNode.subNodes[ nodeName ] = {};
  605. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  606. } else {
  607. currentNode.subNodes[ nodeName ] = node;
  608. }
  609. }
  610. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  611. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  612. if ( nodeAttrs ) {
  613. node.id = attrs.id;
  614. node.attrName = attrs.name;
  615. node.attrType = attrs.type;
  616. }
  617. this.pushStack( node );
  618. },
  619. parseNodeAttr: function ( attrs ) {
  620. var id = attrs[ 0 ];
  621. if ( attrs[ 0 ] !== "" ) {
  622. id = parseInt( attrs[ 0 ] );
  623. if ( isNaN( id ) ) {
  624. // PolygonVertexIndex: *16380 {
  625. id = attrs[ 0 ];
  626. }
  627. }
  628. var name;
  629. var type;
  630. if ( attrs.length > 1 ) {
  631. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  632. type = attrs[ 2 ];
  633. }
  634. return { id: id, name: name || '', type: type || '' };
  635. },
  636. parseNodeProperty: function ( line, propName, propValue ) {
  637. var currentNode = this.getCurrentNode();
  638. var parentName = currentNode.name;
  639. // special case parent node's is like "Properties70"
  640. // these chilren nodes must treat with careful
  641. if ( parentName !== undefined ) {
  642. var propMatch = parentName.match( /Properties(\d)+/ );
  643. if ( propMatch ) {
  644. this.parseNodeSpecialProperty( line, propName, propValue );
  645. return;
  646. }
  647. }
  648. // special case Connections
  649. if ( propName == 'C' ) {
  650. var connProps = propValue.split( ',' ).slice( 1 );
  651. var from = parseInt( connProps[ 0 ] );
  652. var to = parseInt( connProps[ 1 ] );
  653. var rest = propValue.split( ',' ).slice( 3 );
  654. propName = 'connections';
  655. propValue = [ from, to ];
  656. propValue = propValue.concat( rest );
  657. if ( currentNode.properties[ propName ] === undefined ) {
  658. currentNode.properties[ propName ] = [];
  659. }
  660. }
  661. // special case Connections
  662. if ( propName == 'Node' ) {
  663. var id = parseInt( propValue );
  664. currentNode.properties.id = id;
  665. currentNode.id = id;
  666. }
  667. // already exists in properties, then append this
  668. if ( propName in currentNode.properties ) {
  669. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  670. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  671. currentNode.properties[ propName ].push( propValue );
  672. } else {
  673. currentNode.properties[ propName ] += propValue;
  674. }
  675. } else {
  676. // console.log( propName + ": " + propValue );
  677. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  678. currentNode.properties[ propName ].push( propValue );
  679. } else {
  680. currentNode.properties[ propName ] = propValue;
  681. }
  682. }
  683. this.setCurrentProp( currentNode.properties, propName );
  684. },
  685. // TODO:
  686. parseNodePropertyContinued: function ( line ) {
  687. this.currentProp[ this.currentPropName ] += line;
  688. },
  689. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  690. // split this
  691. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  692. // into array like below
  693. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  694. var props = propValue.split( '",' ).map( function ( element ) {
  695. return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  696. } );
  697. var innerPropName = props[ 0 ];
  698. var innerPropType1 = props[ 1 ];
  699. var innerPropType2 = props[ 2 ];
  700. var innerPropFlag = props[ 3 ];
  701. var innerPropValue = props[ 4 ];
  702. /*
  703. if ( innerPropValue === undefined ) {
  704. innerPropValue = props[3];
  705. }
  706. */
  707. // cast value in its type
  708. switch ( innerPropType1 ) {
  709. case "int":
  710. innerPropValue = parseInt( innerPropValue );
  711. break;
  712. case "double":
  713. innerPropValue = parseFloat( innerPropValue );
  714. break;
  715. case "ColorRGB":
  716. case "Vector3D":
  717. var tmp = innerPropValue.split( ',' );
  718. innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
  719. break;
  720. }
  721. // CAUTION: these props must append to parent's parent
  722. this.getPrevNode().properties[ innerPropName ] = {
  723. 'type': innerPropType1,
  724. 'type2': innerPropType2,
  725. 'flag': innerPropFlag,
  726. 'value': innerPropValue
  727. };
  728. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  729. },
  730. nodeEnd: function () {
  731. this.popStack();
  732. },
  733. /* ---------------------------------------------------------------- */
  734. /* util */
  735. isFlattenNode: function ( node ) {
  736. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  737. }
  738. } );
  739. // generate skinIndices, skinWeights
  740. // @skinIndices: per vertex data, this represents the bone indexes affects that vertex
  741. // @skinWeights: per vertex data, this represents the Weight Values affects that vertex
  742. // @matrices: per `bones` data
  743. function Weights() {
  744. this.skinIndices = [];
  745. this.skinWeights = [];
  746. this.matrices = [];
  747. }
  748. Weights.prototype.parseCluster = function ( node, id, entry ) {
  749. var _p = node.searchConnectionParent( id );
  750. var _indices = parseArrayToInt( entry.subNodes.Indexes.properties.a );
  751. var _weights = parseArrayToFloat( entry.subNodes.Weights.properties.a );
  752. var _transform = parseArrayToMatrix( entry.subNodes.Transform.properties.a );
  753. var _link = parseArrayToMatrix( entry.subNodes.TransformLink.properties.a );
  754. return {
  755. 'parent': _p,
  756. 'id': parseInt( id ),
  757. 'indices': _indices,
  758. 'weights': _weights,
  759. 'transform': _transform,
  760. 'transformlink': _link,
  761. 'linkMode': entry.properties.Mode
  762. };
  763. };
  764. Weights.prototype.parse = function ( node, bones ) {
  765. this.skinIndices = [];
  766. this.skinWeights = [];
  767. this.matrices = [];
  768. var deformers = node.Objects.subNodes.Deformer;
  769. var clusters = {};
  770. for ( var id in deformers ) {
  771. if ( deformers[ id ].attrType === 'Cluster' ) {
  772. if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) {
  773. continue;
  774. }
  775. //clusters.push( this.parseCluster( node, id, deformers[id] ) );
  776. var cluster = this.parseCluster( node, id, deformers[ id ] );
  777. var boneId = node.searchConnectionChildren( cluster.id )[ 0 ];
  778. clusters[ boneId ] = cluster;
  779. }
  780. }
  781. // this clusters is per Bone data, thus we make this into per vertex data
  782. var weights = [];
  783. var hi = bones.hierarchy;
  784. for ( var b = 0; b < hi.length; ++ b ) {
  785. var bid = hi[ b ].internalId;
  786. if ( clusters[ bid ] === undefined ) {
  787. //console.log( bid );
  788. this.matrices.push( new THREE.Matrix4() );
  789. continue;
  790. }
  791. var clst = clusters[ bid ];
  792. // store transform matrix per bones
  793. this.matrices.push( clst.transform );
  794. //this.matrices.push( clst.transformlink );
  795. for ( var v = 0; v < clst.indices.length; ++ v ) {
  796. if ( weights[ clst.indices[ v ] ] === undefined ) {
  797. weights[ clst.indices[ v ] ] = {};
  798. weights[ clst.indices[ v ] ].joint = [];
  799. weights[ clst.indices[ v ] ].weight = [];
  800. }
  801. // indices
  802. var affect = node.searchConnectionChildren( clst.id );
  803. if ( affect.length > 1 ) {
  804. console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect );
  805. }
  806. weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) );
  807. // weight value
  808. weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] );
  809. }
  810. }
  811. // normalize the skin weights
  812. // TODO - this might be a good place to choose greatest 4 weights
  813. for ( var i = 0; i < weights.length; i ++ ) {
  814. if ( weights[ i ] === undefined ) {
  815. this.skinIndices.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  816. this.skinWeights.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  817. continue;
  818. }
  819. var indicies = new THREE.Vector4(
  820. weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0,
  821. weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0,
  822. weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0,
  823. weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 );
  824. var weight = new THREE.Vector4(
  825. weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0,
  826. weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0,
  827. weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0,
  828. weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 );
  829. this.skinIndices.push( indicies );
  830. this.skinWeights.push( weight );
  831. }
  832. //console.log( this );
  833. return this;
  834. };
  835. function Bones() {
  836. // returns bones hierarchy tree.
  837. // [
  838. // {
  839. // "parent": id,
  840. // "name": name,
  841. // "pos": pos,
  842. // "rotq": quat
  843. // },
  844. // ...
  845. // {},
  846. // ...
  847. // ]
  848. //
  849. /* sample response
  850. "bones" : [
  851. {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]},
  852. {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]},
  853. {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]},
  854. {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]},
  855. {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]},
  856. {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  857. {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]},
  858. {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]},
  859. {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]},
  860. {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  861. {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]},
  862. {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]},
  863. {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]},
  864. {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]},
  865. {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]},
  866. {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]},
  867. {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]},
  868. {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]},
  869. {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]},
  870. {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]},
  871. {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]},
  872. {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]},
  873. {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]},
  874. ...
  875. {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]},
  876. {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]},
  877. {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]},
  878. {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]}
  879. ]
  880. */
  881. this.hierarchy = [];
  882. }
  883. Bones.prototype.parseHierarchy = function ( node ) {
  884. var objects = node.Objects;
  885. var models = objects.subNodes.Model;
  886. var bones = [];
  887. for ( var id in models ) {
  888. if ( models[ id ].attrType === undefined ) {
  889. continue;
  890. }
  891. bones.push( models[ id ] );
  892. }
  893. this.hierarchy = [];
  894. for ( var i = 0; i < bones.length; ++ i ) {
  895. var bone = bones[ i ];
  896. var p = node.searchConnectionParent( bone.id )[ 0 ];
  897. var t = [ 0.0, 0.0, 0.0 ];
  898. var r = [ 0.0, 0.0, 0.0, 1.0 ];
  899. var s = [ 1.0, 1.0, 1.0 ];
  900. if ( 'Lcl_Translation' in bone.properties ) {
  901. t = parseArrayToFloat( bone.properties.Lcl_Translation.value );
  902. }
  903. if ( 'Lcl_Rotation' in bone.properties ) {
  904. r = parseArrayToRadians( bone.properties.Lcl_Rotation.value );
  905. var q = new THREE.Quaternion();
  906. q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) );
  907. r = [ q.x, q.y, q.z, q.w ];
  908. }
  909. if ( 'Lcl_Scaling' in bone.properties ) {
  910. s = parseArrayToFloat( bone.properties.Lcl_Scaling.value );
  911. }
  912. // replace unsafe character
  913. var name = bone.attrName;
  914. name = name.replace( /:/, '' );
  915. name = name.replace( /_/, '' );
  916. name = name.replace( /-/, '' );
  917. this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } );
  918. }
  919. this.reindexParentId();
  920. this.restoreBindPose( node );
  921. return this;
  922. };
  923. Bones.prototype.reindexParentId = function () {
  924. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  925. for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) {
  926. if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) {
  927. this.hierarchy[ h ].parent = ii;
  928. break;
  929. }
  930. }
  931. }
  932. };
  933. Bones.prototype.restoreBindPose = function ( node ) {
  934. var bindPoseNode = node.Objects.subNodes.Pose;
  935. if ( bindPoseNode === undefined ) {
  936. return;
  937. }
  938. for ( var key in bindPoseNode ) {
  939. if ( bindPoseNode[ key ].attrType === 'BindPose' ) {
  940. bindPoseNode = bindPoseNode[ key ];
  941. break;
  942. }
  943. }
  944. var poseNode = bindPoseNode.subNodes.PoseNode;
  945. var localMatrices = {}; // store local matrices, modified later( initialy world space )
  946. var worldMatrices = {}; // store world matrices
  947. for ( var i = 0; i < poseNode.length; ++ i ) {
  948. var rawMatLcl = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  949. var rawMatWrd = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  950. localMatrices[ poseNode[ i ].id ] = rawMatLcl;
  951. worldMatrices[ poseNode[ i ].id ] = rawMatWrd;
  952. }
  953. for ( var h = 0; h < this.hierarchy.length; ++ h ) {
  954. var bone = this.hierarchy[ h ];
  955. var inId = bone.internalId;
  956. if ( worldMatrices[ inId ] === undefined ) {
  957. // has no bind pose node, possibly be mesh
  958. // console.log( bone );
  959. continue;
  960. }
  961. var t = new THREE.Vector3( 0, 0, 0 );
  962. var r = new THREE.Quaternion();
  963. var s = new THREE.Vector3( 1, 1, 1 );
  964. var parentId;
  965. var parentNodes = node.searchConnectionParent( inId );
  966. for ( var pn = 0; pn < parentNodes.length; ++ pn ) {
  967. if ( this.isBoneNode( parentNodes[ pn ] ) ) {
  968. parentId = parentNodes[ pn ];
  969. break;
  970. }
  971. }
  972. if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) {
  973. // convert world space matrix into local space
  974. var inv = new THREE.Matrix4();
  975. inv.getInverse( worldMatrices[ parentId ] );
  976. inv.multiply( localMatrices[ inId ] );
  977. localMatrices[ inId ] = inv;
  978. } else {
  979. //console.log( bone );
  980. }
  981. localMatrices[ inId ].decompose( t, r, s );
  982. bone.pos = [ t.x, t.y, t.z ];
  983. bone.rotq = [ r.x, r.y, r.z, r.w ];
  984. bone.scl = [ s.x, s.y, s.z ];
  985. }
  986. };
  987. Bones.prototype.searchRealId = function ( internalId ) {
  988. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  989. if ( internalId == this.hierarchy[ h ].internalId ) {
  990. return h;
  991. }
  992. }
  993. // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId);
  994. return - 1;
  995. };
  996. Bones.prototype.getByInternalId = function ( internalId ) {
  997. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  998. if ( internalId == this.hierarchy[ h ].internalId ) {
  999. return this.hierarchy[ h ];
  1000. }
  1001. }
  1002. return null;
  1003. };
  1004. Bones.prototype.isBoneNode = function ( id ) {
  1005. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1006. if ( id === this.hierarchy[ i ].internalId ) {
  1007. return true;
  1008. }
  1009. }
  1010. return false;
  1011. };
  1012. Bones.prototype.getBoneIdfromInternalId = function ( node, id ) {
  1013. if ( node.__cache_get_boneid_from_internalid === undefined ) {
  1014. node.__cache_get_boneid_from_internalid = [];
  1015. }
  1016. if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) {
  1017. return node.__cache_get_boneid_from_internalid[ id ];
  1018. }
  1019. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1020. if ( this.hierarchy[ i ].internalId == id ) {
  1021. node.__cache_get_boneid_from_internalid[ id ] = i;
  1022. return i;
  1023. }
  1024. }
  1025. // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' );
  1026. return - 1;
  1027. };
  1028. function Geometries() {
  1029. this.geometries = {};
  1030. }
  1031. Object.assign( Geometries.prototype, {
  1032. parse: function ( FBXNodes, hierarchy ) {
  1033. if ( ! ( 'Geometry' in FBXNodes.Objects.subNodes ) ) {
  1034. return this;
  1035. }
  1036. for ( var geo in FBXNodes.Objects.subNodes.Geometry ) {
  1037. if ( FBXNodes.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) {
  1038. this.geometries[ geo ] = ( new Geometry() ).parse( FBXNodes.Objects.subNodes.Geometry[ geo ] );
  1039. this.geometries[ geo ].addBones( hierarchy.hierarchy );
  1040. }
  1041. }
  1042. return this;
  1043. }
  1044. } );
  1045. function Geometry() {
  1046. this.fbxNode = null;
  1047. this.name = '';
  1048. this.fbxID = - 1;
  1049. this.positionBuffer = [];
  1050. this.normalBuffer = [];
  1051. this.uvBuffer = [];
  1052. this.materialBuffer = [];
  1053. this.bones = [];
  1054. }
  1055. Object.assign( Geometry.prototype, {
  1056. parse: function ( geoNode ) {
  1057. this.fbxNode = geoNode;
  1058. this.name = geoNode.attrName;
  1059. this.fbxID = geoNode.id;
  1060. var vertexInfo = getVertices( geoNode );
  1061. if ( vertexInfo.buffer.length > 0 ) {
  1062. console.log( 'FBXLoader: Geometry for ID: ' + geoNode.id + ' has no vertices.' );
  1063. return;
  1064. }
  1065. var uvInfo = getUVs( geoNode );
  1066. var normalInfo = getNormals( geoNode );
  1067. var materialInfo = getMaterials( geoNode );
  1068. //Now lets create the non-indexed buffers.
  1069. var vertexBuffer = [];
  1070. var normalBuffer = [];
  1071. var uvBuffer = [];
  1072. var materialBuffer = [];
  1073. for ( var faceIndex = 0; faceIndex < vertexInfo.verticesPerFace.length; ++ faceIndex ) {
  1074. for ( var polygonVertexIndex = 0; polygonVertexIndex < vertexInfo.verticesPerFace[ faceIndex ]; ++ polygonVertexIndex ) {
  1075. var vertex;
  1076. if ( polygonVertexIndex > 2 ) {
  1077. //Add material for previous Tri before beginning new tri.
  1078. materialBuffer.push( getData( polygonVertexIndex, faceIndex, 1, vertexInfo.verticesPerFace, materialInfo ) );
  1079. //Re-add vertex 0 and n-1 to triangulate mesh.
  1080. vertex = getVertex( 0, faceIndex, vertexInfo, normalInfo, uvInfo );
  1081. vertexBuffer.push( vertex.position );
  1082. normalBuffer.push( vertex.normal );
  1083. uvBuffer.push( vertex.uv );
  1084. vertex = getVertex( polygonVertexIndex - 1, faceIndex, vertexInfo, normalInfo, uvInfo );
  1085. vertexBuffer.push( vertex.position );
  1086. normalBuffer.push( vertex.normal );
  1087. uvBuffer.push( vertex.uv );
  1088. }
  1089. vertex = getVertex( polygonVertexIndex, faceIndex, vertexInfo, normalInfo, uvInfo );
  1090. vertexBuffer.push( vertex.position );
  1091. normalBuffer.push( vertex.normal );
  1092. uvBuffer.push( vertex.uv );
  1093. }
  1094. materialBuffer.push( getData( 0, faceIndex, 1, vertexInfo.verticesPerFace, materialInfo ) );
  1095. }
  1096. this.positionBuffer = vertexBuffer;
  1097. this.normalBuffer = normalBuffer;
  1098. this.uvBuffer = uvBuffer;
  1099. this.materialBuffer = materialBuffer;
  1100. /**
  1101. * Pushes vertex data into appropriate buffers based on given info.
  1102. * @param {number} polyVertexIndex - Index of vertex within polygon.
  1103. * @param {number} polyIndex - Index of polygon within geometry.
  1104. * @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string, maxNGon: number, verticesPerFace: number[]}} positionInfo
  1105. * @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} normalInfo
  1106. * @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} uvInfo
  1107. * @returns {{ position: number[], normal: number[], uv: number[] }}
  1108. */
  1109. function getVertex( polyVertexIndex, polyIndex, positionInfo, normalInfo, uvInfo ) {
  1110. /**
  1111. * Describes which vertex index we are looking at.
  1112. */
  1113. var positionIndexIndex = 0;
  1114. for ( var i = 0; i < polyIndex; ++ i ) {
  1115. positionIndexIndex += positionInfo.verticesPerFace[ i ];
  1116. }
  1117. var positionIndex = positionInfo.indices[ positionIndexIndex ];
  1118. var position = [
  1119. positionInfo.buffer[ ( positionIndex * 3 ) ],
  1120. positionInfo.buffer[ ( positionIndex * 3 ) + 1 ],
  1121. positionInfo.buffer[ ( positionIndex * 3 ) + 2 ] ];
  1122. var normal = getData( polyVertexIndex, polyIndex, 3, positionInfo.verticesPerFace, normalInfo );
  1123. var uvs = getData( polyVertexIndex, polyIndex, 2, positionInfo.verticesPerFace, uvInfo );
  1124. return {
  1125. position: position,
  1126. normal: normal,
  1127. uv: uvs
  1128. };
  1129. }
  1130. /**
  1131. * Grabs data based on mapping and reference type of data and returns data buffer.
  1132. * @param {number} polyVertexIndex - Index of vertex within polygon.
  1133. * @param {number} polyIndex - Index of polygon within geometry.
  1134. * @param {number} dataSize - Number of data values per vertex for this type of data.
  1135. * @param {number[]} verticesPerFace - Number of vertices per polygon face.
  1136. * @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object holding info for data.
  1137. * @returns {number[]}
  1138. */
  1139. function getData( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
  1140. var GetData = {
  1141. ByPolygonVertex: {
  1142. /**
  1143. * Grabs data mapped by polygon vertex and referenced directly and returns the data for
  1144. * the specific instance based on the polygon vertex index and polygon index.
  1145. * @param {number} polyVertexIndex - Index of vertex within polygon.
  1146. * @param {number} polyIndex - Index of polygon within geometry.
  1147. * @param {number} dataSize - Number of data values per vertex for given data type.
  1148. * @param {number[]} verticesPerFace - Number of polygon vertices per face.
  1149. * @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
  1150. * @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
  1151. */
  1152. Direct: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
  1153. var dataIndex = 0;
  1154. for ( var i = 0; i < polyIndex; ++ i ) {
  1155. dataIndex += verticesPerFace[ i ];
  1156. }
  1157. dataIndex += polyVertexIndex;
  1158. var returnBuffer = [];
  1159. for ( var i = 0; i < dataSize; ++ i ) {
  1160. returnBuffer.push( infoObject.buffer[ ( dataIndex * dataSize ) + i ] );
  1161. }
  1162. return returnBuffer;
  1163. },
  1164. /**
  1165. * Grabs data mapped by polygon vertex and referenced via index buffer and returns the data for
  1166. * the specific instance based on the polygon vertex index and polygon index.
  1167. * @param {number} polyVertexIndex - Index of vertex within polygon.
  1168. * @param {number} polyIndex - Index of polygon within geometry.
  1169. * @param {number} dataSize - Number of data values per vertex for given data type.
  1170. * @param {number[]} verticesPerFace - Number of polygon vertices per face.
  1171. * @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
  1172. * @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
  1173. */
  1174. IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
  1175. var dataIndexIndex = 0;
  1176. for ( var i = 0; i < polyIndex; ++ i ) {
  1177. dataIndexIndex += verticesPerFace[ i ];
  1178. }
  1179. dataIndexIndex += polyVertexIndex;
  1180. var dataIndex = infoObject.indices[ dataIndexIndex ];
  1181. var returnBuffer = [];
  1182. for ( var i = 0; i < dataSize; ++ i ) {
  1183. returnBuffer.push( infoObject.buffer[ ( dataIndex * dataSize ) + i ] );
  1184. }
  1185. return returnBuffer;
  1186. }
  1187. },
  1188. ByPolygon: {
  1189. /**
  1190. * Grabs data mapped by polygon and referenced directly and returns the data for
  1191. * the specific instance based on the polygon index.
  1192. * @param {number} polyVertexIndex - Index of vertex within polygon (Ignored for this function).
  1193. * @param {number} polyIndex - Index of polygon within geometry.
  1194. * @param {number} dataSize - Number of data values per vertex for given data type.
  1195. * @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored for this function).
  1196. * @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
  1197. * @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
  1198. */
  1199. Direct: function ( polyVertexIndex, polyIndex, dataSize, vericesPerFace, infoObject ) {
  1200. var returnBuffer = [];
  1201. for ( var i = 0; i < dataSize; ++ i ) {
  1202. returnBuffer.push( infoObject.buffer[ ( polyIndex * dataSize ) + i ] );
  1203. }
  1204. return returnBuffer;
  1205. },
  1206. /**
  1207. * Grabs data mapped by polygon and referenced via index buffer and returns the data for
  1208. * the specific instance based on the polygon index.
  1209. * @param {number} polyVertexIndex - Index of vertex within polygon (Ignored for this function).
  1210. * @param {number} polyIndex - Index of polygon within geometry.
  1211. * @param {number} dataSize - Number of data values per vertex for given data type.
  1212. * @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored for this function).
  1213. * @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
  1214. * @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
  1215. */
  1216. IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
  1217. var index = infoObject.indices[ polyIndex ];
  1218. var returnBuffer = [];
  1219. for ( var i = 0; i < dataSize; ++ i ) {
  1220. returnBuffer.push( infoObject.buffer[ ( index * dataSize ) + i ] );
  1221. }
  1222. return returnBuffer;
  1223. }
  1224. },
  1225. AllSame: {
  1226. /**
  1227. * Grabs data mapped all the same and referenced via index buffer and returns the data for
  1228. * the specific instance based on the polygon vertex index and polygon index.
  1229. * @param {number} polyVertexIndex - Index of vertex within polygon (Ignored in this function).
  1230. * @param {number} polyIndex - Index of polygon within geometry (Ignored in this function).
  1231. * @param {number} dataSize - Number of data values per vertex for given data type.
  1232. * @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored in this function).
  1233. * @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
  1234. * @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
  1235. */
  1236. IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
  1237. var returnBuffer;
  1238. for ( var i = 0; i < dataSize; ++ i ) {
  1239. returnBuffer.push( infoObject.buffer[ ( infoObject.indices[ 0 ] * dataSize ) + i ] );
  1240. }
  1241. return returnBuffer;
  1242. }
  1243. }
  1244. };
  1245. return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject );
  1246. }
  1247. /**
  1248. * Extracts vertex array and returns array of floats
  1249. * representing vertex position data.
  1250. * @param {Object} geoNode - Parsed FBX node for geometry.
  1251. * @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string, maxNGon: number, verticesPerFace: number[]}}
  1252. */
  1253. function getVertices( geoNode ) {
  1254. if ( geoNode.subNodes.Vertices === undefined ) {
  1255. console.warn( 'Geo Node ' + geoNode.attrName + "(" + geoNode.id + ") does not define vertices." );
  1256. return {
  1257. buffer: [],
  1258. indices: [],
  1259. mappingType: 'ByPolygonVertex',
  1260. referenceType: 'IndexToDirect',
  1261. maxNGon: 3,
  1262. verticesPerFace: []
  1263. };
  1264. }
  1265. var buffer = parseArrayToFloat( geoNode.subNodes.Vertices.properties.a );
  1266. var indices = parseArrayToInt( geoNode.subNodes.PolygonVertexIndex.properties.a );
  1267. var currentNumVerticesThisFace = 1;
  1268. var maxVerticesOnAFace = 0;
  1269. var verticesPerFace = [];
  1270. // The indices that make up the polygon are in order. A negative index means
  1271. // that it's the last index of the polygon. That index needs to be made positive
  1272. // and subtract 1 from it.
  1273. for ( var i = 0; i < indices.length; ++ i ) {
  1274. var index = indices[ i ];
  1275. if ( index < 0 ) {
  1276. if ( currentNumVerticesThisFace > maxVerticesOnAFace ) {
  1277. maxVerticesOnAFace = currentNumVerticesThisFace;
  1278. }
  1279. indices[ i ] = index ^ - 1;
  1280. verticesPerFace.push( currentNumVerticesThisFace );
  1281. currentNumVerticesThisFace = 1;
  1282. } else {
  1283. currentNumVerticesThisFace ++;
  1284. }
  1285. }
  1286. if ( maxVerticesOnAFace === 0 ) {
  1287. console.warn( 'FBXLoader: Max vertices on a face not found: ' + geoNode.attrName );
  1288. maxVerticesOnAFace = 3;
  1289. }
  1290. return {
  1291. buffer: buffer,
  1292. indices: indices,
  1293. mappingType: 'ByPolygonVertex',
  1294. referenceType: 'IndexToDirect',
  1295. maxNGon: maxVerticesOnAFace,
  1296. verticesPerFace: verticesPerFace
  1297. };
  1298. }
  1299. /**
  1300. * Extracts UV information and returns object describing UVs.
  1301. * @param {Object} geoNode - Parsed FBX node for geometry.
  1302. * @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  1303. */
  1304. function getUVs( geoNode ) {
  1305. if ( ! ( 'LayerElementUV' in geoNode.subNodes ) ) {
  1306. // No UVs defined. Nothing to do here.
  1307. return {
  1308. buffer: [],
  1309. indices: [],
  1310. mappingType: 'AllSame',
  1311. referenceType: 'IndexToDirect'
  1312. };
  1313. }
  1314. var UVNode = geoNode.subNodes.LayerElementUV;
  1315. if ( UVNode === undefined ) {
  1316. // No UV information.
  1317. return [];
  1318. }
  1319. for ( var node in UVNode ) {
  1320. if ( node.match( /^\d+$/ ) ) {
  1321. console.warn( 'multi UV is not supported.' );
  1322. UVNode = UVNode[ node ];
  1323. break;
  1324. }
  1325. }
  1326. var rawUVBuffer = UVNode.subNodes.UV.properties.a;
  1327. var mappingType = UVNode.properties.MappingInformationType;
  1328. var refType = UVNode.properties.ReferenceInformationType;
  1329. var UVBuffer = parseArrayToFloat( rawUVBuffer );
  1330. var IndexBuffer = [];
  1331. if ( mappingType === 'IndexToDirect' ) {
  1332. var rawIndexBuffer = UVNode.subNodes.UVIndex.properties.a;
  1333. IndexBuffer = parseArrayToInt( rawIndexBuffer );
  1334. }
  1335. return {
  1336. buffer: UVBuffer,
  1337. indices: IndexBuffer,
  1338. mappingType: mappingType,
  1339. referenceType: refType
  1340. };
  1341. }
  1342. /**
  1343. * Extracts normal information and returns object describing normals.
  1344. * @param {Object} geoNode - Parsed FBX node for geometry.
  1345. * @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string}}
  1346. */
  1347. function getNormals( geoNode ) {
  1348. var NormalNode = geoNode.subNodes.LayerElementNormal;
  1349. if ( NormalNode === undefined ) {
  1350. console.warn( 'Node: ' + geoNode.attrName + "(" + geoNode.id + ") does not have Normals defined." );
  1351. return {
  1352. buffer: [],
  1353. indices: [],
  1354. mappingType: 'AllSame',
  1355. referenceType: 'IndexToDirect'
  1356. };
  1357. }
  1358. var mappingType = NormalNode.properties.MappingInformationType;
  1359. var referenceType = NormalNode.properties.ReferenceInformationType;
  1360. var normalBuffer = parseArrayToFloat( NormalNode.subNodes.Normals.properties.a );
  1361. var indexBuffer = [];
  1362. if ( referenceType === 'IndexToDirect' ) {
  1363. var rawIndexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
  1364. indexBuffer = parseArrayToInt( rawIndexBuffer );
  1365. }
  1366. return {
  1367. buffer: normalBuffer,
  1368. indices: indexBuffer,
  1369. mappingType: mappingType,
  1370. referenceType: referenceType
  1371. };
  1372. }
  1373. /**
  1374. * Extracts material index information and returns object describing material assignment.
  1375. * @param {Object} geoNode - Parsed FBX node for geometry.
  1376. * @returns {{buffer: number[], mappingType: string, referenceType: string}}
  1377. */
  1378. function getMaterials( geoNode ) {
  1379. if ( ! ( 'LayerElementMaterial' in geoNode.subNodes ) ) {
  1380. // No material info.
  1381. return {
  1382. buffer: [ 0 ],
  1383. indices: [ 0 ],
  1384. mappingType: 'AllSame',
  1385. referenceType: 'IndexToDirect'
  1386. };
  1387. }
  1388. var indexNode = geoNode.subNodes.LayerElementMaterial;
  1389. var mapType = indexNode.properties.MappingInformationType;
  1390. var refType = indexNode.properties.ReferenceInformationType;
  1391. var matBuffer = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
  1392. var matIndexes = [];
  1393. matBuffer.forEach( function ( materialIndex, index ) {
  1394. matIndexes.push( index );
  1395. } );
  1396. return {
  1397. buffer: matBuffer,
  1398. indices: matIndexes,
  1399. mappingType: mapType,
  1400. referenceType: refType
  1401. };
  1402. }
  1403. },
  1404. addBones: function ( bones ) {
  1405. this.bones = bones;
  1406. }
  1407. } );
  1408. /**
  1409. Geometry.prototype.parse = function ( geoNode ) {
  1410. this.node = geoNode;
  1411. this.name = geoNode.attrName;
  1412. this.id = geoNode.id;
  1413. this.vertices = this.getVertices();
  1414. if ( this.vertices === undefined ) {
  1415. console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id );
  1416. return;
  1417. }
  1418. this.indices = this.getPolygonVertexIndices();
  1419. this.uvs = ( new UV() ).parse( this.node, this );
  1420. this.normals = ( new Normal() ).parse( this.node, this );
  1421. this.materialIndices = ( new MaterialIndex() ).parse( this.node );
  1422. if ( this.getPolygonTopologyMax() > 3 ) {
  1423. var indexInfo = this.convertPolyIndicesToTri(
  1424. this.indices,
  1425. this.materialIndices,
  1426. this.getPolygonTopologyArray() );
  1427. this.indices = indexInfo.res;
  1428. this.materialIndices = indexInfo.materialIndices;
  1429. this.polyIndices = indexInfo.polyIndices;
  1430. }
  1431. return this;
  1432. };
  1433. Geometry.prototype.getVertices = function () {
  1434. if ( this.node.__cache_vertices ) {
  1435. return this.node.__cache_vertices;
  1436. }
  1437. if ( this.node.subNodes.Vertices === undefined ) {
  1438. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" );
  1439. this.node.__cache_vertices = undefined;
  1440. return null;
  1441. }
  1442. var rawTextVert = this.node.subNodes.Vertices.properties.a;
  1443. var vertices = rawTextVert.split( ',' ).map( function ( element ) {
  1444. return parseFloat( element );
  1445. } );
  1446. this.node.__cache_vertices = vertices;
  1447. return this.node.__cache_vertices;
  1448. };
  1449. Geometry.prototype.getPolygonVertexIndices = function () {
  1450. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1451. return this.node.__cache_indices;
  1452. }
  1453. if ( this.node.subNodes === undefined ) {
  1454. console.error( 'this.node.subNodes undefined' );
  1455. console.log( this.node );
  1456. return;
  1457. }
  1458. if ( this.node.subNodes.PolygonVertexIndex === undefined ) {
  1459. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " );
  1460. this.node.__cache_indices = undefined;
  1461. return;
  1462. }
  1463. var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a;
  1464. var indices = rawTextIndices.split( ',' );
  1465. var currentTopo = 1;
  1466. var topologyN = null;
  1467. var topologyArr = [];
  1468. // The indices that make up the polygon are in order and a negative index
  1469. // means that it’s the last index of the polygon. That index needs
  1470. // to be made positive and then you have to subtract 1 from it!
  1471. for ( var i = 0; i < indices.length; ++ i ) {
  1472. var tmpI = parseInt( indices[ i ] );
  1473. // found n
  1474. if ( tmpI < 0 ) {
  1475. if ( currentTopo > topologyN ) {
  1476. topologyN = currentTopo;
  1477. }
  1478. indices[ i ] = tmpI ^ - 1;
  1479. topologyArr.push( currentTopo );
  1480. currentTopo = 1;
  1481. } else {
  1482. indices[ i ] = tmpI;
  1483. currentTopo ++;
  1484. }
  1485. }
  1486. if ( topologyN === null ) {
  1487. console.warn( "FBXLoader: topology N not found: " + this.node.attrName );
  1488. console.warn( this.node );
  1489. topologyN = 3;
  1490. }
  1491. this.node.__cache_poly_topology_max = topologyN;
  1492. this.node.__cache_poly_topology_arr = topologyArr;
  1493. this.node.__cache_indices = indices;
  1494. return this.node.__cache_indices;
  1495. };
  1496. Geometry.prototype.getPolygonTopologyMax = function () {
  1497. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1498. return this.node.__cache_poly_topology_max;
  1499. }
  1500. this.getPolygonVertexIndices( this.node );
  1501. return this.node.__cache_poly_topology_max;
  1502. };
  1503. Geometry.prototype.getPolygonTopologyArray = function () {
  1504. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1505. return this.node.__cache_poly_topology_arr;
  1506. }
  1507. this.getPolygonVertexIndices( this.node );
  1508. return this.node.__cache_poly_topology_arr;
  1509. };
  1510. // a - d
  1511. // | |
  1512. // b - c
  1513. //
  1514. // [( a, b, c, d ) ...........
  1515. // [( a, b, c ), (a, c, d )....
  1516. // Also keep track of original poly index.
  1517. Geometry.prototype.convertPolyIndicesToTri = function ( indices, materialIndices, strides ) {
  1518. var res = [];
  1519. var i = 0;
  1520. var currentPolyNum = 0;
  1521. var currentStride = 0;
  1522. var polyIndices = [];
  1523. while ( i < indices.length ) {
  1524. currentStride = strides[ currentPolyNum ];
  1525. // CAUTIN: NG over 6gon
  1526. for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) {
  1527. res.push( indices[ i ] );
  1528. res.push( indices[ i + ( currentStride - 2 - j ) ] );
  1529. res.push( indices[ i + ( currentStride - 1 - j ) ] );
  1530. polyIndices.push( currentPolyNum );
  1531. }
  1532. currentPolyNum ++;
  1533. i += currentStride;
  1534. }
  1535. var newMaterialIndices = [ materialIndices[ 0 ] ];
  1536. if ( materialIndices.length > 1 ) {
  1537. for ( var i = 0; i < polyIndices.length; ++ i ) {
  1538. newMaterialIndices[ i ] = materialIndices[ polyIndices[ i ] ];
  1539. }
  1540. }
  1541. return {
  1542. res: res,
  1543. materialIndices: newMaterialIndices,
  1544. polyIndices: polyIndices };
  1545. };
  1546. Geometry.prototype.addBones = function ( bones ) {
  1547. this.bones = bones;
  1548. };
  1549. function UV() {
  1550. this.uv = null;
  1551. this.map = null;
  1552. this.ref = null;
  1553. this.node = null;
  1554. this.index = null;
  1555. }
  1556. UV.prototype.getUV = function ( node ) {
  1557. if ( this.node && this.uv && this.map && this.ref ) {
  1558. return this.uv;
  1559. } else {
  1560. return this._parseText( node );
  1561. }
  1562. };
  1563. UV.prototype.getMap = function ( node ) {
  1564. if ( this.node && this.uv && this.map && this.ref ) {
  1565. return this.map;
  1566. } else {
  1567. this._parseText( node );
  1568. return this.map;
  1569. }
  1570. };
  1571. UV.prototype.getRef = function ( node ) {
  1572. if ( this.node && this.uv && this.map && this.ref ) {
  1573. return this.ref;
  1574. } else {
  1575. this._parseText( node );
  1576. return this.ref;
  1577. }
  1578. };
  1579. UV.prototype.getIndex = function ( node ) {
  1580. if ( this.node && this.uv && this.map && this.ref ) {
  1581. return this.index;
  1582. } else {
  1583. this._parseText( node );
  1584. return this.index;
  1585. }
  1586. };
  1587. UV.prototype.getNode = function ( topnode ) {
  1588. if ( this.node !== null ) {
  1589. return this.node;
  1590. }
  1591. this.node = topnode.subNodes.LayerElementUV;
  1592. return this.node;
  1593. };
  1594. UV.prototype._parseText = function ( node ) {
  1595. var uvNode = this.getNode( node )[ 0 ];
  1596. if ( uvNode === undefined ) {
  1597. // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." );
  1598. return [];
  1599. }
  1600. var count = 0;
  1601. for ( var n in uvNode ) {
  1602. if ( n.match( /^\d+$/ ) ) {
  1603. count ++;
  1604. }
  1605. }
  1606. if ( count > 0 ) {
  1607. console.warn( 'multi uv not supported' );
  1608. uvNode = uvNode[ n ];
  1609. }
  1610. var uvIndex = uvNode.subNodes.UVIndex.properties.a;
  1611. var uvs = uvNode.subNodes.UV.properties.a;
  1612. var uvMap = uvNode.properties.MappingInformationType;
  1613. var uvRef = uvNode.properties.ReferenceInformationType;
  1614. this.uv = parseArrayToFloat( uvs );
  1615. this.index = parseArrayToInt( uvIndex );
  1616. this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER
  1617. this.ref = uvRef;
  1618. return this.uv;
  1619. };
  1620. UV.prototype.parse = function ( node, geo ) {
  1621. if ( ! ( 'LayerElementUV' in node.subNodes ) ) {
  1622. return;
  1623. }
  1624. this.uvNode = this.getNode( node );
  1625. this.uv = this.getUV( node );
  1626. var mappingType = this.getMap( node );
  1627. var refType = this.getRef( node );
  1628. var indices = this.getIndex( node );
  1629. var strides = geo.getPolygonTopologyArray();
  1630. // it means that there is a normal for every vertex of every polygon of the model.
  1631. // For example, if the models has 8 vertices that make up four quads, then there
  1632. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1633. // that generally a game engine needs the vertices to have only one normal defined.
  1634. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1635. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1636. //if ( mappingType == "ByPolygonVertex" ){
  1637. switch ( mappingType ) {
  1638. case "ByPolygonVertex":
  1639. switch ( refType ) {
  1640. // Direct
  1641. // The this.uv are in order.
  1642. case "Direct":
  1643. this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 );
  1644. break;
  1645. // IndexToDirect
  1646. // The order of the this.uv is given by the uvsIndex property.
  1647. case "IndexToDirect":
  1648. this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices );
  1649. break;
  1650. }
  1651. // convert from by polygon(vert) data into by verts data
  1652. this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 );
  1653. break;
  1654. case "ByPolygon":
  1655. switch ( refType ) {
  1656. // Direct
  1657. // The this.uv are in order.
  1658. case "Direct":
  1659. this.uv = this.parseUV_ByPolygon_Direct();
  1660. break;
  1661. // IndexToDirect
  1662. // The order of the this.uv is given by the uvsIndex property.
  1663. case "IndexToDirect":
  1664. this.uv = this.parseUV_ByPolygon_IndexToDirect();
  1665. break;
  1666. }
  1667. break;
  1668. }
  1669. return this.uv;
  1670. };
  1671. UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1672. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1673. };
  1674. UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) {
  1675. return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 );
  1676. };
  1677. UV.prototype.parseUV_ByPolygon_Direct = function ( node ) {
  1678. console.warn( "not implemented" );
  1679. return node;
  1680. };
  1681. UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) {
  1682. console.warn( "not implemented" );
  1683. return node;
  1684. };
  1685. UV.prototype.parseUV_ByVertex_Direct = function ( node ) {
  1686. console.warn( "not implemented" );
  1687. return node;
  1688. };
  1689. function Normal() {
  1690. this.normal = null;
  1691. this.map = null;
  1692. this.ref = null;
  1693. this.node = null;
  1694. this.index = null;
  1695. }
  1696. Normal.prototype.getNormal = function ( node ) {
  1697. if ( this.node && this.normal && this.map && this.ref ) {
  1698. return this.normal;
  1699. } else {
  1700. this._parseText( node );
  1701. return this.normal;
  1702. }
  1703. };
  1704. // mappingType: possible variant
  1705. // ByPolygon
  1706. // ByPolygonVertex
  1707. // ByVertex (or also ByVertice, as the Blender exporter writes)
  1708. // ByEdge
  1709. // AllSame
  1710. // var mappingType = node.properties.MappingInformationType;
  1711. Normal.prototype.getMap = function ( node ) {
  1712. if ( this.node && this.normal && this.map && this.ref ) {
  1713. return this.map;
  1714. } else {
  1715. this._parseText( node );
  1716. return this.map;
  1717. }
  1718. };
  1719. // refType: possible variants
  1720. // Direct
  1721. // IndexToDirect (or Index for older versions)
  1722. // var refType = node.properties.ReferenceInformationType;
  1723. Normal.prototype.getRef = function ( node ) {
  1724. if ( this.node && this.normal && this.map && this.ref ) {
  1725. return this.ref;
  1726. } else {
  1727. this._parseText( node );
  1728. return this.ref;
  1729. }
  1730. };
  1731. Normal.prototype.getNode = function ( node ) {
  1732. if ( this.node ) {
  1733. return this.node;
  1734. }
  1735. this.node = node.subNodes.LayerElementNormal;
  1736. return this.node;
  1737. };
  1738. Normal.prototype._parseText = function ( node ) {
  1739. var normalNode = this.getNode( node )[ 0 ];
  1740. if ( normalNode === undefined ) {
  1741. console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" );
  1742. return;
  1743. }
  1744. var mappingType = normalNode.properties.MappingInformationType;
  1745. var refType = normalNode.properties.ReferenceInformationType;
  1746. var rawTextNormals = normalNode.subNodes.Normals.properties.a;
  1747. this.normal = parseArrayToFloat( rawTextNormals );
  1748. // TODO: normalize notation shaking, vertex / vertice... blender...
  1749. this.map = mappingType;
  1750. this.ref = refType;
  1751. };
  1752. Normal.prototype.parse = function ( topnode, geo ) {
  1753. var normals = this.getNormal( topnode );
  1754. //var normalNode = this.getNode( topnode );
  1755. var mappingType = this.getMap( topnode );
  1756. var refType = this.getRef( topnode );
  1757. var indices = geo.getPolygonVertexIndices( topnode );
  1758. var strides = geo.getPolygonTopologyArray( topnode );
  1759. // it means that there is a normal for every vertex of every polygon of the model.
  1760. // For example, if the models has 8 vertices that make up four quads, then there
  1761. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1762. // that generally a game engine needs the vertices to have only one normal defined.
  1763. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1764. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1765. //if ( mappingType == "ByPolygonVertex" ){
  1766. switch ( mappingType ) {
  1767. case "ByPolygonVertex":
  1768. switch ( refType ) {
  1769. // Direct
  1770. // The normals are in order.
  1771. case "Direct":
  1772. normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 );
  1773. break;
  1774. // IndexToDirect
  1775. // The order of the normals is given by the NormalsIndex property.
  1776. case "IndexToDirect":
  1777. normals = this.parseNormal_ByPolygonVertex_IndexToDirect();
  1778. break;
  1779. }
  1780. break;
  1781. case "ByPolygon":
  1782. switch ( refType ) {
  1783. // Direct
  1784. // The normals are in order.
  1785. case "Direct":
  1786. normals = this.parseNormal_ByPolygon_Direct();
  1787. break;
  1788. // IndexToDirect
  1789. // The order of the normals is given by the NormalsIndex property.
  1790. case "IndexToDirect":
  1791. normals = this.parseNormal_ByPolygon_IndexToDirect();
  1792. break;
  1793. }
  1794. break;
  1795. }
  1796. return normals;
  1797. };
  1798. Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1799. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1800. };
  1801. Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) {
  1802. console.warn( "not implemented" );
  1803. return node;
  1804. };
  1805. Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) {
  1806. console.warn( "not implemented" );
  1807. return node;
  1808. };
  1809. Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) {
  1810. console.warn( "not implemented" );
  1811. return node;
  1812. };
  1813. Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) {
  1814. console.warn( "not implemented" );
  1815. return node;
  1816. };
  1817. function MaterialIndex() {
  1818. this.indexBuffer = [];
  1819. }
  1820. Object.assign( MaterialIndex.prototype, {
  1821. parse: function ( node ) {
  1822. if ( ! ( 'LayerElementMaterial' in node.subNodes ) ) {
  1823. return;
  1824. }
  1825. var indexNode = node.subNodes.LayerElementMaterial[ 0 ];
  1826. var mappingType = indexNode.properties.MappingInformationType;
  1827. var refType = indexNode.properties.ReferenceInformationType;
  1828. var indices = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
  1829. // it means that there is a normal for every vertex of every polygon of the model.
  1830. // For example, if the models has 8 vertices that make up four quads, then there
  1831. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1832. // that generally a game engine needs the vertices to have only one normal defined.
  1833. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1834. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1835. //if ( mappingType == "ByPolygonVertex" ){
  1836. switch ( mappingType ) {
  1837. case "ByPolygon":
  1838. switch ( refType ) {
  1839. // Direct
  1840. // The material indices are in order.
  1841. case "IndexToDirect":
  1842. this.indexBuffer = this.parse_ByPolygon_IndexToDirect( indices );
  1843. break;
  1844. default:
  1845. this.indexBuffer = [ 0 ];
  1846. break;
  1847. }
  1848. break;
  1849. default:
  1850. this.indexBuffer = [ 0 ];
  1851. break;
  1852. }
  1853. return this.indexBuffer;
  1854. },
  1855. parse_ByPolygon_IndexToDirect: function ( indices ) {
  1856. return indices;
  1857. },
  1858. } );
  1859. */
  1860. function AnimationCurve() {
  1861. this.version = null;
  1862. this.id = null;
  1863. this.internalId = null;
  1864. this.times = null;
  1865. this.values = null;
  1866. this.attrFlag = null; // tangeant
  1867. this.attrData = null; // slope, weight
  1868. }
  1869. AnimationCurve.prototype.fromNode = function ( curveNode ) {
  1870. this.id = curveNode.id;
  1871. this.internalId = curveNode.id;
  1872. this.times = curveNode.subNodes.KeyTime.properties.a;
  1873. this.values = curveNode.subNodes.KeyValueFloat.properties.a;
  1874. this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a;
  1875. this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a;
  1876. this.times = parseArrayToFloat( this.times );
  1877. this.values = parseArrayToFloat( this.values );
  1878. this.attrData = parseArrayToFloat( this.attrData );
  1879. this.attrFlag = parseArrayToInt( this.attrFlag );
  1880. this.times = this.times.map( function ( element ) {
  1881. return FBXTimeToSeconds( element );
  1882. } );
  1883. return this;
  1884. };
  1885. AnimationCurve.prototype.getLength = function () {
  1886. return this.times[ this.times.length - 1 ];
  1887. };
  1888. function AnimationNode() {
  1889. this.id = null;
  1890. this.attr = null; // S, R, T
  1891. this.attrX = false;
  1892. this.attrY = false;
  1893. this.attrZ = false;
  1894. this.internalId = null;
  1895. this.containerInternalId = null; // bone, null etc Id
  1896. this.containerBoneId = null; // bone, null etc Id
  1897. this.curveIdx = null; // AnimationCurve's indices
  1898. this.curves = {}; // AnimationCurve refs
  1899. }
  1900. AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) {
  1901. this.id = node.id;
  1902. this.attr = node.attrName;
  1903. this.internalId = node.id;
  1904. if ( this.attr.match( /S|R|T/ ) ) {
  1905. for ( var attrKey in node.properties ) {
  1906. if ( attrKey.match( /X/ ) ) {
  1907. this.attrX = true;
  1908. }
  1909. if ( attrKey.match( /Y/ ) ) {
  1910. this.attrY = true;
  1911. }
  1912. if ( attrKey.match( /Z/ ) ) {
  1913. this.attrZ = true;
  1914. }
  1915. }
  1916. } else {
  1917. // may be deform percent nodes
  1918. return null;
  1919. }
  1920. this.containerIndices = allNodes.searchConnectionParent( this.id );
  1921. this.curveIdx = allNodes.searchConnectionChildren( this.id );
  1922. for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) {
  1923. var boneId = bones.searchRealId( this.containerIndices[ i ] );
  1924. if ( boneId >= 0 ) {
  1925. this.containerBoneId = boneId;
  1926. this.containerId = this.containerIndices[ i ];
  1927. }
  1928. if ( boneId >= 0 ) {
  1929. break;
  1930. }
  1931. }
  1932. // this.containerBoneId = bones.searchRealId( this.containerIndices );
  1933. return this;
  1934. };
  1935. AnimationNode.prototype.setCurve = function ( curve ) {
  1936. this.curves.push( curve );
  1937. };
  1938. function Animation() {
  1939. this.curves = {};
  1940. this.length = 0.0;
  1941. this.fps = 30.0;
  1942. this.frames = 0.0;
  1943. }
  1944. Animation.prototype.parse = function ( node, bones ) {
  1945. var rawNodes = node.Objects.subNodes.AnimationCurveNode;
  1946. var rawCurves = node.Objects.subNodes.AnimationCurve;
  1947. var rawLayers = node.Objects.subNodes.AnimationLayer;
  1948. var rawStacks = node.Objects.subNodes.AnimationStack;
  1949. // first: expand AnimationCurveNode into curve nodes
  1950. var curveNodes = [];
  1951. for ( var key in rawNodes ) {
  1952. if ( key.match( /\d+/ ) ) {
  1953. var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones );
  1954. curveNodes.push( a );
  1955. }
  1956. }
  1957. // second: gen dict, mapped by internalId
  1958. var tmp = {};
  1959. for ( var i = 0; i < curveNodes.length; ++ i ) {
  1960. if ( curveNodes[ i ] === null ) {
  1961. continue;
  1962. }
  1963. tmp[ curveNodes[ i ].id ] = curveNodes[ i ];
  1964. }
  1965. // third: insert curves into the dict
  1966. var ac = [];
  1967. for ( key in rawCurves ) {
  1968. if ( key.match( /\d+/ ) ) {
  1969. var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] );
  1970. ac.push( c );
  1971. var parentId = node.searchConnectionParent( c.id )[ 0 ];
  1972. var axis = node.searchConnectionType( c.id, parentId );
  1973. if ( axis.match( /X/ ) ) {
  1974. axis = 'x';
  1975. } else if ( axis.match( /Y/ ) ) {
  1976. axis = 'y';
  1977. } else if ( axis.match( /Z/ ) ) {
  1978. axis = 'z';
  1979. } else {
  1980. continue;
  1981. }
  1982. tmp[ parentId ].curves[ axis ] = c;
  1983. }
  1984. }
  1985. // forth:
  1986. for ( var t in tmp ) {
  1987. var id = tmp[ t ].containerBoneId;
  1988. if ( this.curves[ id ] === undefined ) {
  1989. this.curves[ id ] = {
  1990. T: null,
  1991. R: null,
  1992. S: null
  1993. };
  1994. }
  1995. this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ];
  1996. }
  1997. //Layers
  1998. this.layers = {};
  1999. for ( var key in rawLayers ) {
  2000. var layer = [];
  2001. var children = node.searchConnectionChildren( key );
  2002. for ( var i = 0; i < children.length; ++ i ) {
  2003. //Skip lockInfluenceWeights
  2004. if ( tmp[ children[ i ] ] ) {
  2005. if ( layer[ tmp[ children[ i ] ].containerBoneId ] === undefined ) {
  2006. layer[ tmp[ children[ i ] ].containerBoneId ] = {
  2007. T: null,
  2008. R: null,
  2009. S: null
  2010. };
  2011. }
  2012. layer[ tmp[ children[ i ] ].containerBoneId ][ tmp[ children[ i ] ].attr ] = tmp[ children[ i ] ];
  2013. }
  2014. }
  2015. this.layers[ key ] = layer;
  2016. }
  2017. //Takes
  2018. this.stacks = {};
  2019. for ( var key in rawStacks ) {
  2020. var layers = [];
  2021. var children = node.searchConnectionChildren( key );
  2022. var max = 0.0;
  2023. var min = Number.MAX_VALUE;
  2024. for ( var i = 0; i < children.length; ++ i ) {
  2025. if ( children[ i ] in this.layers ) {
  2026. layers.push( this.layers[ children[ i ] ] );
  2027. for ( var j = 0; j < this.layers[ children[ i ] ].length; ++ j ) {
  2028. function getMaxMin( layer ) {
  2029. function _getMaxMin( curves ) {
  2030. if ( curves.x ) {
  2031. max = curves.x.getLength() > max ? curves.x.getLength() : max;
  2032. min = curves.x.times[ 0 ] < min ? curves.x.times[ 0 ] : min;
  2033. }
  2034. if ( curves.y ) {
  2035. max = curves.y.getLength() > max ? curves.y.getLength() : max;
  2036. min = curves.y.times[ 0 ] < min ? curves.y.times[ 0 ] : min;
  2037. }
  2038. if ( curves.z ) {
  2039. max = curves.z.getLength() > max ? curves.z.getLength() : max;
  2040. min = curves.z.times[ 0 ] < min ? curves.z.times[ 0 ] : min;
  2041. }
  2042. }
  2043. if ( layer.R ) {
  2044. _getMaxMin( layer.R.curves );
  2045. }
  2046. if ( layer.S ) {
  2047. _getMaxMin( layer.S.curves );
  2048. }
  2049. if ( layer.T ) {
  2050. _getMaxMin( layer.T.curves );
  2051. }
  2052. }
  2053. var layer = this.layers[ children[ i ] ][ j ];
  2054. if ( layer ) {
  2055. getMaxMin( layer );
  2056. }
  2057. }
  2058. }
  2059. }
  2060. //Do we have an animation clip with an actual length?
  2061. if ( max > min ) {
  2062. this.stacks[ key ] = {
  2063. name: rawStacks[ key ].attrName,
  2064. layers: layers,
  2065. length: max - min,
  2066. frames: ( max - min ) * 30,
  2067. };
  2068. }
  2069. }
  2070. return this;
  2071. };
  2072. function Textures() {
  2073. this.textures = {};
  2074. //this.perGeoMap = {};
  2075. }
  2076. Textures.prototype.add = function ( tex ) {
  2077. debugger;
  2078. if ( this.textures === undefined ) {
  2079. this.textures = [];
  2080. }
  2081. this.textures.push( tex );
  2082. for ( var i = 0; i < tex.parentIds.length; ++ i ) {
  2083. if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) {
  2084. this.perGeoMap[ tex.parentIds[ i ] ] = [];
  2085. }
  2086. this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] );
  2087. }
  2088. };
  2089. Textures.prototype.parse = function ( node ) {
  2090. var rawNodes = node.Objects.subNodes.Texture;
  2091. for ( var n in rawNodes ) {
  2092. var tex = ( new Texture() ).parse( rawNodes[ n ], node );
  2093. this.textures[ n ] = tex;
  2094. }
  2095. return this;
  2096. };
  2097. Textures.prototype.getById = function ( id ) {
  2098. return this.perGeoMap[ id ];
  2099. };
  2100. function Texture() {
  2101. this.fileName = "";
  2102. this.name = "";
  2103. this.id = null;
  2104. this.parentIds = [];
  2105. }
  2106. Texture.prototype.parse = function ( node, nodes ) {
  2107. this.id = node.id;
  2108. this.name = node.attrName;
  2109. this.fileName = this.parseFileName( node.properties.FileName );
  2110. this.parentIds = this.searchParents( this.id, nodes );
  2111. return this;
  2112. };
  2113. // TODO: support directory
  2114. Texture.prototype.parseFileName = function ( fname ) {
  2115. if ( fname === undefined ) {
  2116. return "";
  2117. }
  2118. // ignore directory structure, flatten path
  2119. var splitted = fname.split( /[\\\/]/ );
  2120. if ( splitted.length > 0 ) {
  2121. return splitted[ splitted.length - 1 ];
  2122. } else {
  2123. return fname;
  2124. }
  2125. };
  2126. Texture.prototype.searchParents = function ( id, nodes ) {
  2127. var p = nodes.searchConnectionParent( id );
  2128. return p;
  2129. };
  2130. function Materials() {
  2131. this.materials = {};
  2132. this.perGeoMap = {};
  2133. }
  2134. Object.assign( Materials.prototype, {
  2135. parse: function ( node ) {
  2136. var rawNodes = node.Objects.subNodes.Material;
  2137. for ( var n in rawNodes ) {
  2138. var mat = ( new Material() ).parse( rawNodes[ n ], node );
  2139. this.materials[ n ] = mat;
  2140. }
  2141. return this;
  2142. }
  2143. } );
  2144. function Material() {
  2145. this.fileName = "";
  2146. this.name = "";
  2147. this.id = null;
  2148. this.parentIds = [];
  2149. }
  2150. Object.assign( Material.prototype, {
  2151. parse: function ( node, nodes ) {
  2152. this.id = node.id;
  2153. this.name = node.attrName;
  2154. this.type = node.properties.ShadingModel;
  2155. this.parameters = this.parseParameters( node.properties );
  2156. this.parentIds = this.searchParents( this.id, nodes );
  2157. return this;
  2158. },
  2159. parseParameters: function ( properties ) {
  2160. var parameters = {};
  2161. //TODO: Missing parameters:
  2162. // - Ambient
  2163. // - MultiLayer
  2164. // - ShininessExponent (Same vals as Shininess)
  2165. // - Specular (Same vals as SpecularColor)
  2166. // - TransparencyFactor (Maybe same as Opacity?).
  2167. if ( properties.Diffuse ) {
  2168. parameters.color = new THREE.Color().fromArray( [ parseFloat( properties.Diffuse.value.x ), parseFloat( properties.Diffuse.value.y ), parseFloat( properties.Diffuse.value.z ) ] );
  2169. }
  2170. if ( properties.Specular ) {
  2171. parameters.specular = new THREE.Color().fromArray( [ parseFloat( properties.Specular.value.x ), parseFloat( properties.Specular.value.y ), parseFloat( properties.Specular.value.z ) ] );
  2172. }
  2173. if ( properties.Shininess ) {
  2174. parameters.shininess = properties.Shininess.value;
  2175. }
  2176. if ( properties.Emissive ) {
  2177. parameters.emissive = new THREE.Color().fromArray( [ parseFloat( properties.Emissive.value.x ), parseFloat( properties.Emissive.value.y ), parseFloat( properties.Emissive.value.z ) ] );
  2178. }
  2179. if ( properties.EmissiveFactor ) {
  2180. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  2181. }
  2182. if ( properties.Reflectivity ) {
  2183. parameters.reflectivity = properties.Reflectivity.value;
  2184. }
  2185. if ( properties.Opacity ) {
  2186. parameters.opacity = properties.Opacity.value;
  2187. }
  2188. if ( parameters.opacity < 1.0 ) {
  2189. parameters.transparent = true;
  2190. }
  2191. //Assigning textures
  2192. return parameters;
  2193. },
  2194. searchParents: function ( id, nodes ) {
  2195. return nodes.searchConnectionParent( id );
  2196. }
  2197. } );
  2198. /* --------------------------------------------------------------------- */
  2199. /* --------------------------------------------------------------------- */
  2200. /* --------------------------------------------------------------------- */
  2201. /* --------------------------------------------------------------------- */
  2202. // LayerElementUV: 0 {
  2203. // Version: 101
  2204. // Name: "Texture_Projection"
  2205. // MappingInformationType: "ByPolygonVertex"
  2206. // ReferenceInformationType: "IndexToDirect"
  2207. // UV: *1746 {
  2208. // UVIndex: *7068 {
  2209. //
  2210. // The order of the uvs is given by the UVIndex property.
  2211. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) {
  2212. var res = [];
  2213. for ( var i = 0; i < indices.length; ++ i ) {
  2214. for ( var j = 0; j < itemSize; ++ j ) {
  2215. res.push( node[ ( indices[ i ] * itemSize ) + j ] );
  2216. }
  2217. }
  2218. return res;
  2219. }
  2220. // what want: normal per vertex, order vertice
  2221. // i have: normal per polygon
  2222. // i have: indice per polygon
  2223. function parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ) {
  2224. // *21204 > 3573
  2225. // Geometry: 690680816, "Geometry::", "Mesh" {
  2226. // Vertices: *3573 {
  2227. // PolygonVertexIndex: *7068 {
  2228. var tmp = [];
  2229. var currentIndex = 0;
  2230. // first: sort to per vertex
  2231. for ( var i = 0; i < indices.length; ++ i ) {
  2232. tmp[ indices[ i ] ] = [];
  2233. // TODO: duped entry? blend or something?
  2234. for ( var s = 0; s < itemSize; ++ s ) {
  2235. tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ];
  2236. }
  2237. currentIndex += itemSize;
  2238. }
  2239. // second: expand x,y,z into serial array
  2240. var res = [];
  2241. for ( var jj = 0; jj < tmp.length; ++ jj ) {
  2242. if ( tmp[ jj ] === undefined ) {
  2243. continue;
  2244. }
  2245. for ( var t = 0; t < itemSize; ++ t ) {
  2246. if ( tmp[ jj ][ t ] === undefined ) {
  2247. continue;
  2248. }
  2249. res.push( tmp[ jj ][ t ] );
  2250. }
  2251. }
  2252. return res;
  2253. }
  2254. // convert from by polygon(vert) data into by verts data
  2255. function mapByPolygonVertexToByVertex( data, indices, stride ) {
  2256. var tmp = {};
  2257. var res = [];
  2258. var max = 0;
  2259. for ( var i = 0; i < indices.length; ++ i ) {
  2260. if ( indices[ i ] in tmp ) {
  2261. continue;
  2262. }
  2263. tmp[ indices[ i ] ] = {};
  2264. for ( var j = 0; j < stride; ++ j ) {
  2265. tmp[ indices[ i ] ][ j ] = data[ i * stride + j ];
  2266. }
  2267. max = max < indices[ i ] ? indices[ i ] : max;
  2268. }
  2269. try {
  2270. for ( i = 0; i <= max; i ++ ) {
  2271. for ( var s = 0; s < stride; s ++ ) {
  2272. res.push( tmp[ i ][ s ] );
  2273. }
  2274. }
  2275. } catch ( e ) {
  2276. //console.log( max );
  2277. //console.log( tmp );
  2278. //console.log( i );
  2279. //console.log( e );
  2280. }
  2281. return res;
  2282. }
  2283. // AUTODESK uses broken clock. i guess
  2284. function FBXTimeToSeconds( adskTime ) {
  2285. return adskTime / 46186158000;
  2286. }
  2287. function degToRad( degrees ) {
  2288. return degrees * Math.PI / 180;
  2289. }
  2290. function quatFromVec( x, y, z ) {
  2291. var euler = new THREE.Euler( x, y, z, 'ZYX' );
  2292. var quat = new THREE.Quaternion();
  2293. quat.setFromEuler( euler );
  2294. return quat;
  2295. }
  2296. /**
  2297. * Parses a string of comma separated ints and returns
  2298. * an array of ints.
  2299. * @param {string} string - String comtaining comma separated float values.
  2300. * @returns {number[]}
  2301. */
  2302. function parseArrayToInt( string ) {
  2303. return string.split( ',' ).map( function ( element ) {
  2304. return parseInt( element );
  2305. } );
  2306. }
  2307. /**
  2308. * Parses a string of comma separated floats and returns
  2309. * an array of floats.
  2310. * @param {string} string - String containing comma separated float values.
  2311. * @returns {number[]}
  2312. */
  2313. function parseArrayToFloat( string ) {
  2314. return string.split( ',' ).map( function ( element ) {
  2315. return parseFloat( element );
  2316. } );
  2317. }
  2318. function parseArrayToRadians( string ) {
  2319. return string.split( ',' ).map( function ( element ) {
  2320. return degToRad( parseFloat( element ) );
  2321. } );
  2322. }
  2323. function parseArrayToMatrix( string ) {
  2324. var arr = parseArrayToFloat( string );
  2325. return new THREE.Matrix4().fromArray( arr );
  2326. }
  2327. } )();