ColladaLoader.js 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455
  1. /**
  2. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  3. */
  4. THREE.ColladaLoader = function () {
  5. var COLLADA = null;
  6. var scene = null;
  7. var daeScene;
  8. var readyCallbackFunc = null;
  9. var sources = {};
  10. var images = {};
  11. var animations = {};
  12. var controllers = {};
  13. var geometries = {};
  14. var materials = {};
  15. var effects = {};
  16. var cameras = {};
  17. var animData;
  18. var visualScenes;
  19. var baseUrl;
  20. var morphs;
  21. var skins;
  22. var flip_uv = true;
  23. var preferredShading = THREE.SmoothShading;
  24. var options = {
  25. // Force Geometry to always be centered at the local origin of the
  26. // containing Mesh.
  27. centerGeometry: false,
  28. // Axis conversion is done for geometries, animations, and controllers.
  29. // If we ever pull cameras or lights out of the COLLADA file, they'll
  30. // need extra work.
  31. convertUpAxis: false,
  32. subdivideFaces: true,
  33. upAxis: 'Y',
  34. // For reflective or refractive materials we'll use this cubemap
  35. defaultEnvMap: null
  36. };
  37. // TODO: support unit conversion as well
  38. var colladaUnit = 1.0;
  39. var colladaUp = 'Y';
  40. var upConversion = null;
  41. var TO_RADIANS = Math.PI / 180;
  42. function load ( url, readyCallback, progressCallback ) {
  43. var length = 0;
  44. if ( document.implementation && document.implementation.createDocument ) {
  45. var req = new XMLHttpRequest();
  46. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  47. req.onreadystatechange = function() {
  48. if( req.readyState == 4 ) {
  49. if( req.status == 0 || req.status == 200 ) {
  50. if ( req.responseXML ) {
  51. readyCallbackFunc = readyCallback;
  52. parse( req.responseXML, undefined, url );
  53. } else {
  54. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  55. }
  56. }
  57. } else if ( req.readyState == 3 ) {
  58. if ( progressCallback ) {
  59. if ( length == 0 ) {
  60. length = req.getResponseHeader( "Content-Length" );
  61. }
  62. progressCallback( { total: length, loaded: req.responseText.length } );
  63. }
  64. }
  65. }
  66. req.open( "GET", url, true );
  67. req.send( null );
  68. } else {
  69. alert( "Don't know how to parse XML!" );
  70. }
  71. };
  72. function parse( doc, callBack, url ) {
  73. COLLADA = doc;
  74. callBack = callBack || readyCallbackFunc;
  75. if ( url !== undefined ) {
  76. var parts = url.split( '/' );
  77. parts.pop();
  78. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  79. }
  80. parseAsset();
  81. setUpConversion();
  82. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  83. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  84. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  85. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  86. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  87. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  88. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  89. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  90. morphs = [];
  91. skins = [];
  92. daeScene = parseScene();
  93. scene = new THREE.Object3D();
  94. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  95. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  96. }
  97. createAnimations();
  98. var result = {
  99. scene: scene,
  100. morphs: morphs,
  101. skins: skins,
  102. animations: animData,
  103. dae: {
  104. images: images,
  105. materials: materials,
  106. cameras: cameras,
  107. effects: effects,
  108. geometries: geometries,
  109. controllers: controllers,
  110. animations: animations,
  111. visualScenes: visualScenes,
  112. scene: daeScene
  113. }
  114. };
  115. if ( callBack ) {
  116. callBack( result );
  117. }
  118. return result;
  119. };
  120. function setPreferredShading ( shading ) {
  121. preferredShading = shading;
  122. };
  123. function parseAsset () {
  124. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  125. var element = elements.iterateNext();
  126. if ( element && element.childNodes ) {
  127. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  128. var child = element.childNodes[ i ];
  129. switch ( child.nodeName ) {
  130. case 'unit':
  131. var meter = child.getAttribute( 'meter' );
  132. if ( meter ) {
  133. colladaUnit = parseFloat( meter );
  134. }
  135. break;
  136. case 'up_axis':
  137. colladaUp = child.textContent.charAt(0);
  138. break;
  139. }
  140. }
  141. }
  142. };
  143. function parseLib ( q, classSpec, prefix ) {
  144. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  145. var lib = {};
  146. var element = elements.iterateNext();
  147. var i = 0;
  148. while ( element ) {
  149. var daeElement = ( new classSpec() ).parse( element );
  150. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  151. lib[ daeElement.id ] = daeElement;
  152. element = elements.iterateNext();
  153. }
  154. return lib;
  155. };
  156. function parseScene() {
  157. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  158. if ( sceneElement ) {
  159. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  160. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  161. } else {
  162. return null;
  163. }
  164. };
  165. function createAnimations() {
  166. animData = [];
  167. // fill in the keys
  168. recurseHierarchy( scene );
  169. };
  170. function recurseHierarchy( node ) {
  171. var n = daeScene.getChildById( node.name, true ),
  172. newData = null;
  173. if ( n && n.keys ) {
  174. newData = {
  175. fps: 60,
  176. hierarchy: [ {
  177. node: n,
  178. keys: n.keys,
  179. sids: n.sids
  180. } ],
  181. node: node,
  182. name: 'animation_' + node.name,
  183. length: 0
  184. };
  185. animData.push(newData);
  186. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  187. newData.length = Math.max( newData.length, n.keys[i].time );
  188. }
  189. } else {
  190. newData = {
  191. hierarchy: [ {
  192. keys: [],
  193. sids: []
  194. } ]
  195. }
  196. }
  197. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  198. var d = recurseHierarchy( node.children[i] );
  199. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  200. newData.hierarchy.push( {
  201. keys: [],
  202. sids: []
  203. } );
  204. }
  205. }
  206. return newData;
  207. };
  208. function calcAnimationBounds () {
  209. var start = 1000000;
  210. var end = -start;
  211. var frames = 0;
  212. for ( var id in animations ) {
  213. var animation = animations[ id ];
  214. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  215. var sampler = animation.sampler[ i ];
  216. sampler.create();
  217. start = Math.min( start, sampler.startTime );
  218. end = Math.max( end, sampler.endTime );
  219. frames = Math.max( frames, sampler.input.length );
  220. }
  221. }
  222. return { start:start, end:end, frames:frames };
  223. };
  224. function createMorph ( geometry, ctrl ) {
  225. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  226. if ( !morphCtrl || !morphCtrl.morph ) {
  227. console.log("could not find morph controller!");
  228. return;
  229. }
  230. var morph = morphCtrl.morph;
  231. for ( var i = 0; i < morph.targets.length; i ++ ) {
  232. var target_id = morph.targets[ i ];
  233. var daeGeometry = geometries[ target_id ];
  234. if ( !daeGeometry.mesh ||
  235. !daeGeometry.mesh.primitives ||
  236. !daeGeometry.mesh.primitives.length ) {
  237. continue;
  238. }
  239. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  240. if ( target.vertices.length === geometry.vertices.length ) {
  241. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  242. }
  243. }
  244. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  245. };
  246. function createSkin ( geometry, ctrl, applyBindShape ) {
  247. var skinCtrl = controllers[ ctrl.url ];
  248. if ( !skinCtrl || !skinCtrl.skin ) {
  249. console.log( "could not find skin controller!" );
  250. return;
  251. }
  252. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  253. console.log( "could not find the skeleton for the skin!" );
  254. return;
  255. }
  256. var skin = skinCtrl.skin;
  257. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  258. var hierarchy = [];
  259. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  260. var bones = [];
  261. geometry.skinWeights = [];
  262. geometry.skinIndices = [];
  263. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  264. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  265. /*
  266. geometry.animation = {
  267. name: 'take_001',
  268. fps: 30,
  269. length: 2,
  270. JIT: true,
  271. hierarchy: hierarchy
  272. };
  273. */
  274. if ( applyBindShape ) {
  275. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  276. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ] );
  277. }
  278. }
  279. };
  280. function setupSkeleton ( node, bones, frame, parent ) {
  281. node.world = node.world || new THREE.Matrix4();
  282. node.world.copy( node.matrix );
  283. if ( node.channels && node.channels.length ) {
  284. var channel = node.channels[ 0 ];
  285. var m = channel.sampler.output[ frame ];
  286. if ( m instanceof THREE.Matrix4 ) {
  287. node.world.copy( m );
  288. }
  289. }
  290. if ( parent ) {
  291. node.world.multiply( parent, node.world );
  292. }
  293. bones.push( node );
  294. for ( var i = 0; i < node.nodes.length; i ++ ) {
  295. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  296. }
  297. };
  298. function setupSkinningMatrices ( bones, skin ) {
  299. // FIXME: this is dumb...
  300. for ( var i = 0; i < bones.length; i ++ ) {
  301. var bone = bones[ i ];
  302. var found = -1;
  303. if ( bone.type != 'JOINT' ) continue;
  304. for ( var j = 0; j < skin.joints.length; j ++ ) {
  305. if ( bone.sid == skin.joints[ j ] ) {
  306. found = j;
  307. break;
  308. }
  309. }
  310. if ( found >= 0 ) {
  311. var inv = skin.invBindMatrices[ found ];
  312. bone.invBindMatrix = inv;
  313. bone.skinningMatrix = new THREE.Matrix4();
  314. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  315. bone.weights = [];
  316. for ( var j = 0; j < skin.weights.length; j ++ ) {
  317. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  318. var w = skin.weights[ j ][ k ];
  319. if ( w.joint == found ) {
  320. bone.weights.push( w );
  321. }
  322. }
  323. }
  324. } else {
  325. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  326. }
  327. }
  328. };
  329. function applySkin ( geometry, instanceCtrl, frame ) {
  330. var skinController = controllers[ instanceCtrl.url ];
  331. frame = frame !== undefined ? frame : 40;
  332. if ( !skinController || !skinController.skin ) {
  333. console.log( 'ColladaLoader: Could not find skin controller.' );
  334. return;
  335. }
  336. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  337. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  338. return;
  339. }
  340. var animationBounds = calcAnimationBounds();
  341. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  342. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  343. var i, j, w, vidx, weight;
  344. var v = new THREE.Vector3(), o, s;
  345. // move vertices to bind shape
  346. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  347. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i] );
  348. }
  349. // process animation, or simply pose the rig if no animation
  350. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  351. var bones = [];
  352. var skinned = [];
  353. // zero skinned vertices
  354. for ( i = 0; i < geometry.vertices.length; i++ ) {
  355. skinned.push( new THREE.Vector3() );
  356. }
  357. // process the frame and setup the rig with a fresh
  358. // transform, possibly from the bone's animation channel(s)
  359. setupSkeleton( skeleton, bones, frame );
  360. setupSkinningMatrices( bones, skinController.skin );
  361. // skin 'm
  362. for ( i = 0; i < bones.length; i ++ ) {
  363. if ( bones[ i ].type != 'JOINT' ) continue;
  364. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  365. w = bones[ i ].weights[ j ];
  366. vidx = w.index;
  367. weight = w.weight;
  368. o = geometry.vertices[vidx];
  369. s = skinned[vidx];
  370. v.x = o.x;
  371. v.y = o.y;
  372. v.z = o.z;
  373. bones[i].skinningMatrix.multiplyVector3(v);
  374. s.x += (v.x * weight);
  375. s.y += (v.y * weight);
  376. s.z += (v.z * weight);
  377. }
  378. }
  379. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  380. }
  381. };
  382. function createSceneGraph ( node, parent ) {
  383. var obj = new THREE.Object3D();
  384. var skinned = false;
  385. var skinController;
  386. var morphController;
  387. var i, j;
  388. // FIXME: controllers
  389. for ( i = 0; i < node.controllers.length; i ++ ) {
  390. var controller = controllers[ node.controllers[ i ].url ];
  391. switch ( controller.type ) {
  392. case 'skin':
  393. if ( geometries[ controller.skin.source ] ) {
  394. var inst_geom = new InstanceGeometry();
  395. inst_geom.url = controller.skin.source;
  396. inst_geom.instance_material = node.controllers[ i ].instance_material;
  397. node.geometries.push( inst_geom );
  398. skinned = true;
  399. skinController = node.controllers[ i ];
  400. } else if ( controllers[ controller.skin.source ] ) {
  401. // urgh: controller can be chained
  402. // handle the most basic case...
  403. var second = controllers[ controller.skin.source ];
  404. morphController = second;
  405. // skinController = node.controllers[i];
  406. if ( second.morph && geometries[ second.morph.source ] ) {
  407. var inst_geom = new InstanceGeometry();
  408. inst_geom.url = second.morph.source;
  409. inst_geom.instance_material = node.controllers[ i ].instance_material;
  410. node.geometries.push( inst_geom );
  411. }
  412. }
  413. break;
  414. case 'morph':
  415. if ( geometries[ controller.morph.source ] ) {
  416. var inst_geom = new InstanceGeometry();
  417. inst_geom.url = controller.morph.source;
  418. inst_geom.instance_material = node.controllers[ i ].instance_material;
  419. node.geometries.push( inst_geom );
  420. morphController = node.controllers[ i ];
  421. }
  422. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  423. default:
  424. break;
  425. }
  426. }
  427. // FIXME: multi-material mesh?
  428. // geometries
  429. for ( i = 0; i < node.geometries.length; i ++ ) {
  430. var instance_geometry = node.geometries[i];
  431. var instance_materials = instance_geometry.instance_material;
  432. var geometry = geometries[instance_geometry.url];
  433. var used_materials = {};
  434. var used_materials_array = [];
  435. var num_materials = 0;
  436. var first_material;
  437. if ( geometry ) {
  438. if ( !geometry.mesh || !geometry.mesh.primitives )
  439. continue;
  440. if ( obj.name.length == 0 ) {
  441. obj.name = geometry.id;
  442. }
  443. // collect used fx for this geometry-instance
  444. if ( instance_materials ) {
  445. for ( j = 0; j < instance_materials.length; j ++ ) {
  446. var instance_material = instance_materials[ j ];
  447. var mat = materials[ instance_material.target ];
  448. var effect_id = mat.instance_effect.url;
  449. var shader = effects[ effect_id ].shader;
  450. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  451. used_materials[ instance_material.symbol ] = num_materials;
  452. used_materials_array.push( shader.material )
  453. first_material = shader.material;
  454. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  455. num_materials ++;
  456. }
  457. }
  458. var mesh;
  459. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  460. var geom = geometry.mesh.geometry3js;
  461. if ( num_materials > 1 ) {
  462. material = new THREE.MeshFaceMaterial();
  463. geom.materials = used_materials_array;
  464. for ( j = 0; j < geom.faces.length; j ++ ) {
  465. var face = geom.faces[ j ];
  466. face.materialIndex = used_materials[ face.daeMaterial ]
  467. }
  468. }
  469. if ( skinController !== undefined ) {
  470. applySkin( geom, skinController );
  471. material.morphTargets = true;
  472. mesh = new THREE.SkinnedMesh( geom, material, false );
  473. mesh.skeleton = skinController.skeleton;
  474. mesh.skinController = controllers[ skinController.url ];
  475. mesh.skinInstanceController = skinController;
  476. mesh.name = 'skin_' + skins.length;
  477. skins.push( mesh );
  478. } else if ( morphController !== undefined ) {
  479. createMorph( geom, morphController );
  480. material.morphTargets = true;
  481. mesh = new THREE.Mesh( geom, material );
  482. mesh.name = 'morph_' + morphs.length;
  483. morphs.push( mesh );
  484. } else {
  485. mesh = new THREE.Mesh( geom, material );
  486. // mesh.geom.name = geometry.id;
  487. }
  488. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  489. }
  490. }
  491. for ( i = 0; i < node.cameras.length; i ++ ) {
  492. var instance_camera = node.cameras[i];
  493. var cparams = cameras[instance_camera.url];
  494. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  495. }
  496. obj.name = node.id || "";
  497. obj.matrix = node.matrix;
  498. var props = node.matrix.decompose();
  499. obj.position = props[ 0 ];
  500. obj.quaternion = props[ 1 ];
  501. obj.useQuaternion = true;
  502. obj.scale = props[ 2 ];
  503. if ( options.centerGeometry && obj.geometry ) {
  504. var delta = THREE.GeometryUtils.center( obj.geometry );
  505. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  506. obj.position.subSelf( delta );
  507. }
  508. for ( i = 0; i < node.nodes.length; i ++ ) {
  509. obj.add( createSceneGraph( node.nodes[i], node ) );
  510. }
  511. return obj;
  512. };
  513. function getJointId( skin, id ) {
  514. for ( var i = 0; i < skin.joints.length; i ++ ) {
  515. if ( skin.joints[ i ] == id ) {
  516. return i;
  517. }
  518. }
  519. };
  520. function getLibraryNode( id ) {
  521. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  522. };
  523. function getChannelsForNode (node ) {
  524. var channels = [];
  525. var startTime = 1000000;
  526. var endTime = -1000000;
  527. for ( var id in animations ) {
  528. var animation = animations[id];
  529. for ( var i = 0; i < animation.channel.length; i ++ ) {
  530. var channel = animation.channel[i];
  531. var sampler = animation.sampler[i];
  532. var id = channel.target.split('/')[0];
  533. if ( id == node.id ) {
  534. sampler.create();
  535. channel.sampler = sampler;
  536. startTime = Math.min(startTime, sampler.startTime);
  537. endTime = Math.max(endTime, sampler.endTime);
  538. channels.push(channel);
  539. }
  540. }
  541. }
  542. if ( channels.length ) {
  543. node.startTime = startTime;
  544. node.endTime = endTime;
  545. }
  546. return channels;
  547. };
  548. function calcFrameDuration( node ) {
  549. var minT = 10000000;
  550. for ( var i = 0; i < node.channels.length; i ++ ) {
  551. var sampler = node.channels[i].sampler;
  552. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  553. var t0 = sampler.input[ j ];
  554. var t1 = sampler.input[ j + 1 ];
  555. minT = Math.min( minT, t1 - t0 );
  556. }
  557. }
  558. return minT;
  559. };
  560. function calcMatrixAt( node, t ) {
  561. var animated = {};
  562. var i, j;
  563. for ( i = 0; i < node.channels.length; i ++ ) {
  564. var channel = node.channels[ i ];
  565. animated[ channel.sid ] = channel;
  566. }
  567. var matrix = new THREE.Matrix4();
  568. for ( i = 0; i < node.transforms.length; i ++ ) {
  569. var transform = node.transforms[ i ];
  570. var channel = animated[ transform.sid ];
  571. if ( channel !== undefined ) {
  572. var sampler = channel.sampler;
  573. var value;
  574. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  575. if ( sampler.input[ j + 1 ] > t ) {
  576. value = sampler.output[ j ];
  577. //console.log(value.flatten)
  578. break;
  579. }
  580. }
  581. if ( value !== undefined ) {
  582. if ( value instanceof THREE.Matrix4 ) {
  583. matrix = matrix.multiply( matrix, value );
  584. } else {
  585. // FIXME: handle other types
  586. matrix = matrix.multiply( matrix, transform.matrix );
  587. }
  588. } else {
  589. matrix = matrix.multiply( matrix, transform.matrix );
  590. }
  591. } else {
  592. matrix = matrix.multiply( matrix, transform.matrix );
  593. }
  594. }
  595. return matrix;
  596. };
  597. function bakeAnimations ( node ) {
  598. if ( node.channels && node.channels.length ) {
  599. var keys = [],
  600. sids = [];
  601. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  602. var channel = node.channels[i],
  603. fullSid = channel.fullSid,
  604. sampler = channel.sampler,
  605. input = sampler.input,
  606. transform = node.getTransformBySid( channel.sid ),
  607. member;
  608. if ( channel.arrIndices ) {
  609. member = [];
  610. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
  611. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  612. }
  613. } else {
  614. member = getConvertedMember( channel.member );
  615. }
  616. if ( transform ) {
  617. if ( sids.indexOf( fullSid ) === -1 ) {
  618. sids.push( fullSid );
  619. }
  620. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  621. var time = input[j],
  622. data = sampler.getData( transform.type, j ),
  623. key = findKey( keys, time );
  624. if ( !key ) {
  625. key = new Key( time );
  626. var timeNdx = findTimeNdx( keys, time );
  627. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  628. }
  629. key.addTarget( fullSid, transform, member, data );
  630. }
  631. } else {
  632. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  633. }
  634. }
  635. // post process
  636. for ( var i = 0; i < sids.length; i++ ) {
  637. var sid = sids[ i ];
  638. for ( var j = 0; j < keys.length; j++ ) {
  639. var key = keys[ j ];
  640. if ( !key.hasTarget( sid ) ) {
  641. interpolateKeys( keys, key, j, sid );
  642. }
  643. }
  644. }
  645. node.keys = keys;
  646. node.sids = sids;
  647. }
  648. };
  649. function findKey ( keys, time) {
  650. var retVal = null;
  651. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  652. var key = keys[i];
  653. if ( key.time === time ) {
  654. retVal = key;
  655. } else if ( key.time > time ) {
  656. break;
  657. }
  658. }
  659. return retVal;
  660. };
  661. function findTimeNdx ( keys, time) {
  662. var ndx = -1;
  663. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  664. var key = keys[i];
  665. if ( key.time >= time ) {
  666. ndx = i;
  667. }
  668. }
  669. return ndx;
  670. };
  671. function interpolateKeys ( keys, key, ndx, fullSid ) {
  672. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  673. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  674. if ( prevKey && nextKey ) {
  675. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  676. prevTarget = prevKey.getTarget( fullSid ),
  677. nextData = nextKey.getTarget( fullSid ).data,
  678. prevData = prevTarget.data,
  679. data;
  680. if ( prevTarget.type === 'matrix' ) {
  681. data = prevData;
  682. } else if ( prevData.length ) {
  683. data = [];
  684. for ( var i = 0; i < prevData.length; ++i ) {
  685. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  686. }
  687. } else {
  688. data = prevData + ( nextData - prevData ) * scale;
  689. }
  690. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  691. }
  692. };
  693. // Get next key with given sid
  694. function getNextKeyWith( keys, fullSid, ndx ) {
  695. for ( ; ndx < keys.length; ndx++ ) {
  696. var key = keys[ ndx ];
  697. if ( key.hasTarget( fullSid ) ) {
  698. return key;
  699. }
  700. }
  701. return null;
  702. };
  703. // Get previous key with given sid
  704. function getPrevKeyWith( keys, fullSid, ndx ) {
  705. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  706. for ( ; ndx >= 0; ndx-- ) {
  707. var key = keys[ ndx ];
  708. if ( key.hasTarget( fullSid ) ) {
  709. return key;
  710. }
  711. }
  712. return null;
  713. };
  714. function _Image() {
  715. this.id = "";
  716. this.init_from = "";
  717. };
  718. _Image.prototype.parse = function(element) {
  719. this.id = element.getAttribute('id');
  720. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  721. var child = element.childNodes[ i ];
  722. if ( child.nodeName == 'init_from' ) {
  723. this.init_from = child.textContent;
  724. }
  725. }
  726. return this;
  727. };
  728. function Controller() {
  729. this.id = "";
  730. this.name = "";
  731. this.type = "";
  732. this.skin = null;
  733. this.morph = null;
  734. };
  735. Controller.prototype.parse = function( element ) {
  736. this.id = element.getAttribute('id');
  737. this.name = element.getAttribute('name');
  738. this.type = "none";
  739. for ( var i = 0; i < element.childNodes.length; i++ ) {
  740. var child = element.childNodes[ i ];
  741. switch ( child.nodeName ) {
  742. case 'skin':
  743. this.skin = (new Skin()).parse(child);
  744. this.type = child.nodeName;
  745. break;
  746. case 'morph':
  747. this.morph = (new Morph()).parse(child);
  748. this.type = child.nodeName;
  749. break;
  750. default:
  751. break;
  752. }
  753. }
  754. return this;
  755. };
  756. function Morph() {
  757. this.method = null;
  758. this.source = null;
  759. this.targets = null;
  760. this.weights = null;
  761. };
  762. Morph.prototype.parse = function( element ) {
  763. var sources = {};
  764. var inputs = [];
  765. var i;
  766. this.method = element.getAttribute( 'method' );
  767. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  768. for ( i = 0; i < element.childNodes.length; i ++ ) {
  769. var child = element.childNodes[ i ];
  770. if ( child.nodeType != 1 ) continue;
  771. switch ( child.nodeName ) {
  772. case 'source':
  773. var source = ( new Source() ).parse( child );
  774. sources[ source.id ] = source;
  775. break;
  776. case 'targets':
  777. inputs = this.parseInputs( child );
  778. break;
  779. default:
  780. console.log( child.nodeName );
  781. break;
  782. }
  783. }
  784. for ( i = 0; i < inputs.length; i ++ ) {
  785. var input = inputs[ i ];
  786. var source = sources[ input.source ];
  787. switch ( input.semantic ) {
  788. case 'MORPH_TARGET':
  789. this.targets = source.read();
  790. break;
  791. case 'MORPH_WEIGHT':
  792. this.weights = source.read();
  793. break;
  794. default:
  795. break;
  796. }
  797. }
  798. return this;
  799. };
  800. Morph.prototype.parseInputs = function(element) {
  801. var inputs = [];
  802. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  803. var child = element.childNodes[i];
  804. if ( child.nodeType != 1) continue;
  805. switch ( child.nodeName ) {
  806. case 'input':
  807. inputs.push( (new Input()).parse(child) );
  808. break;
  809. default:
  810. break;
  811. }
  812. }
  813. return inputs;
  814. };
  815. function Skin() {
  816. this.source = "";
  817. this.bindShapeMatrix = null;
  818. this.invBindMatrices = [];
  819. this.joints = [];
  820. this.weights = [];
  821. };
  822. Skin.prototype.parse = function( element ) {
  823. var sources = {};
  824. var joints, weights;
  825. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  826. this.invBindMatrices = [];
  827. this.joints = [];
  828. this.weights = [];
  829. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  830. var child = element.childNodes[i];
  831. if ( child.nodeType != 1 ) continue;
  832. switch ( child.nodeName ) {
  833. case 'bind_shape_matrix':
  834. var f = _floats(child.textContent);
  835. this.bindShapeMatrix = getConvertedMat4( f );
  836. break;
  837. case 'source':
  838. var src = new Source().parse(child);
  839. sources[ src.id ] = src;
  840. break;
  841. case 'joints':
  842. joints = child;
  843. break;
  844. case 'vertex_weights':
  845. weights = child;
  846. break;
  847. default:
  848. console.log( child.nodeName );
  849. break;
  850. }
  851. }
  852. this.parseJoints( joints, sources );
  853. this.parseWeights( weights, sources );
  854. return this;
  855. };
  856. Skin.prototype.parseJoints = function ( element, sources ) {
  857. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  858. var child = element.childNodes[ i ];
  859. if ( child.nodeType != 1 ) continue;
  860. switch ( child.nodeName ) {
  861. case 'input':
  862. var input = ( new Input() ).parse( child );
  863. var source = sources[ input.source ];
  864. if ( input.semantic == 'JOINT' ) {
  865. this.joints = source.read();
  866. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  867. this.invBindMatrices = source.read();
  868. }
  869. break;
  870. default:
  871. break;
  872. }
  873. }
  874. };
  875. Skin.prototype.parseWeights = function ( element, sources ) {
  876. var v, vcount, inputs = [];
  877. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  878. var child = element.childNodes[ i ];
  879. if ( child.nodeType != 1 ) continue;
  880. switch ( child.nodeName ) {
  881. case 'input':
  882. inputs.push( ( new Input() ).parse( child ) );
  883. break;
  884. case 'v':
  885. v = _ints( child.textContent );
  886. break;
  887. case 'vcount':
  888. vcount = _ints( child.textContent );
  889. break;
  890. default:
  891. break;
  892. }
  893. }
  894. var index = 0;
  895. for ( var i = 0; i < vcount.length; i ++ ) {
  896. var numBones = vcount[i];
  897. var vertex_weights = [];
  898. for ( var j = 0; j < numBones; j++ ) {
  899. var influence = {};
  900. for ( var k = 0; k < inputs.length; k ++ ) {
  901. var input = inputs[ k ];
  902. var value = v[ index + input.offset ];
  903. switch ( input.semantic ) {
  904. case 'JOINT':
  905. influence.joint = value;//this.joints[value];
  906. break;
  907. case 'WEIGHT':
  908. influence.weight = sources[ input.source ].data[ value ];
  909. break;
  910. default:
  911. break;
  912. }
  913. }
  914. vertex_weights.push( influence );
  915. index += inputs.length;
  916. }
  917. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  918. vertex_weights[ j ].index = i;
  919. }
  920. this.weights.push( vertex_weights );
  921. }
  922. };
  923. function VisualScene () {
  924. this.id = "";
  925. this.name = "";
  926. this.nodes = [];
  927. this.scene = new THREE.Object3D();
  928. };
  929. VisualScene.prototype.getChildById = function( id, recursive ) {
  930. for ( var i = 0; i < this.nodes.length; i ++ ) {
  931. var node = this.nodes[ i ].getChildById( id, recursive );
  932. if ( node ) {
  933. return node;
  934. }
  935. }
  936. return null;
  937. };
  938. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  939. for ( var i = 0; i < this.nodes.length; i ++ ) {
  940. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  941. if ( node ) {
  942. return node;
  943. }
  944. }
  945. return null;
  946. };
  947. VisualScene.prototype.parse = function( element ) {
  948. this.id = element.getAttribute( 'id' );
  949. this.name = element.getAttribute( 'name' );
  950. this.nodes = [];
  951. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  952. var child = element.childNodes[ i ];
  953. if ( child.nodeType != 1 ) continue;
  954. switch ( child.nodeName ) {
  955. case 'node':
  956. this.nodes.push( ( new Node() ).parse( child ) );
  957. break;
  958. default:
  959. break;
  960. }
  961. }
  962. return this;
  963. };
  964. function Node() {
  965. this.id = "";
  966. this.name = "";
  967. this.sid = "";
  968. this.nodes = [];
  969. this.controllers = [];
  970. this.transforms = [];
  971. this.geometries = [];
  972. this.channels = [];
  973. this.matrix = new THREE.Matrix4();
  974. };
  975. Node.prototype.getChannelForTransform = function( transformSid ) {
  976. for ( var i = 0; i < this.channels.length; i ++ ) {
  977. var channel = this.channels[i];
  978. var parts = channel.target.split('/');
  979. var id = parts.shift();
  980. var sid = parts.shift();
  981. var dotSyntax = (sid.indexOf(".") >= 0);
  982. var arrSyntax = (sid.indexOf("(") >= 0);
  983. var arrIndices;
  984. var member;
  985. if ( dotSyntax ) {
  986. parts = sid.split(".");
  987. sid = parts.shift();
  988. member = parts.shift();
  989. } else if ( arrSyntax ) {
  990. arrIndices = sid.split("(");
  991. sid = arrIndices.shift();
  992. for ( var j = 0; j < arrIndices.length; j ++ ) {
  993. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  994. }
  995. }
  996. if ( sid == transformSid ) {
  997. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  998. return channel;
  999. }
  1000. }
  1001. return null;
  1002. };
  1003. Node.prototype.getChildById = function ( id, recursive ) {
  1004. if ( this.id == id ) {
  1005. return this;
  1006. }
  1007. if ( recursive ) {
  1008. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1009. var n = this.nodes[ i ].getChildById( id, recursive );
  1010. if ( n ) {
  1011. return n;
  1012. }
  1013. }
  1014. }
  1015. return null;
  1016. };
  1017. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1018. if ( this.sid == sid ) {
  1019. return this;
  1020. }
  1021. if ( recursive ) {
  1022. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1023. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1024. if ( n ) {
  1025. return n;
  1026. }
  1027. }
  1028. }
  1029. return null;
  1030. };
  1031. Node.prototype.getTransformBySid = function ( sid ) {
  1032. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1033. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  1034. }
  1035. return null;
  1036. };
  1037. Node.prototype.parse = function( element ) {
  1038. var url;
  1039. this.id = element.getAttribute('id');
  1040. this.sid = element.getAttribute('sid');
  1041. this.name = element.getAttribute('name');
  1042. this.type = element.getAttribute('type');
  1043. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  1044. this.nodes = [];
  1045. this.transforms = [];
  1046. this.geometries = [];
  1047. this.cameras = [];
  1048. this.controllers = [];
  1049. this.matrix = new THREE.Matrix4();
  1050. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1051. var child = element.childNodes[ i ];
  1052. if ( child.nodeType != 1 ) continue;
  1053. switch ( child.nodeName ) {
  1054. case 'node':
  1055. this.nodes.push( ( new Node() ).parse( child ) );
  1056. break;
  1057. case 'instance_camera':
  1058. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1059. break;
  1060. case 'instance_controller':
  1061. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1062. break;
  1063. case 'instance_geometry':
  1064. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1065. break;
  1066. case 'instance_light':
  1067. break;
  1068. case 'instance_node':
  1069. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1070. var iNode = getLibraryNode( url );
  1071. if ( iNode ) {
  1072. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1073. }
  1074. break;
  1075. case 'rotate':
  1076. case 'translate':
  1077. case 'scale':
  1078. case 'matrix':
  1079. case 'lookat':
  1080. case 'skew':
  1081. this.transforms.push( ( new Transform() ).parse( child ) );
  1082. break;
  1083. case 'extra':
  1084. break;
  1085. default:
  1086. console.log( child.nodeName );
  1087. break;
  1088. }
  1089. }
  1090. this.channels = getChannelsForNode( this );
  1091. bakeAnimations( this );
  1092. this.updateMatrix();
  1093. return this;
  1094. };
  1095. Node.prototype.updateMatrix = function () {
  1096. this.matrix.identity();
  1097. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1098. this.transforms[ i ].apply( this.matrix );
  1099. }
  1100. };
  1101. function Transform () {
  1102. this.sid = "";
  1103. this.type = "";
  1104. this.data = [];
  1105. this.obj = null;
  1106. };
  1107. Transform.prototype.parse = function ( element ) {
  1108. this.sid = element.getAttribute( 'sid' );
  1109. this.type = element.nodeName;
  1110. this.data = _floats( element.textContent );
  1111. this.convert();
  1112. return this;
  1113. };
  1114. Transform.prototype.convert = function () {
  1115. switch ( this.type ) {
  1116. case 'matrix':
  1117. this.obj = getConvertedMat4( this.data );
  1118. break;
  1119. case 'rotate':
  1120. this.angle = this.data[3] * TO_RADIANS;
  1121. case 'translate':
  1122. fixCoords( this.data, -1 );
  1123. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1124. break;
  1125. case 'scale':
  1126. fixCoords( this.data, 1 );
  1127. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1128. break;
  1129. default:
  1130. console.log( 'Can not convert Transform of type ' + this.type );
  1131. break;
  1132. }
  1133. };
  1134. Transform.prototype.apply = function ( matrix ) {
  1135. switch ( this.type ) {
  1136. case 'matrix':
  1137. matrix.multiplySelf( this.obj );
  1138. break;
  1139. case 'translate':
  1140. matrix.translate( this.obj );
  1141. break;
  1142. case 'rotate':
  1143. matrix.rotateByAxis( this.obj, this.angle );
  1144. break;
  1145. case 'scale':
  1146. matrix.scale( this.obj );
  1147. break;
  1148. }
  1149. };
  1150. Transform.prototype.update = function ( data, member ) {
  1151. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1152. switch ( this.type ) {
  1153. case 'matrix':
  1154. if ( ! member ) {
  1155. this.obj.copy( data );
  1156. } else if ( member.length === 1 ) {
  1157. switch ( member[ 0 ] ) {
  1158. case 0:
  1159. this.obj.n11 = data[ 0 ];
  1160. this.obj.n21 = data[ 1 ];
  1161. this.obj.n31 = data[ 2 ];
  1162. this.obj.n41 = data[ 3 ];
  1163. break;
  1164. case 1:
  1165. this.obj.n12 = data[ 0 ];
  1166. this.obj.n22 = data[ 1 ];
  1167. this.obj.n32 = data[ 2 ];
  1168. this.obj.n42 = data[ 3 ];
  1169. break;
  1170. case 2:
  1171. this.obj.n13 = data[ 0 ];
  1172. this.obj.n23 = data[ 1 ];
  1173. this.obj.n33 = data[ 2 ];
  1174. this.obj.n43 = data[ 3 ];
  1175. break;
  1176. case 3:
  1177. this.obj.n14 = data[ 0 ];
  1178. this.obj.n24 = data[ 1 ];
  1179. this.obj.n34 = data[ 2 ];
  1180. this.obj.n44 = data[ 3 ];
  1181. break;
  1182. }
  1183. } else if ( member.length === 2 ) {
  1184. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1185. this.obj[ propName ] = data;
  1186. } else {
  1187. console.log('Incorrect addressing of matrix in transform.');
  1188. }
  1189. break;
  1190. case 'translate':
  1191. case 'scale':
  1192. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1193. member = members[ member[ 0 ] ];
  1194. }
  1195. switch ( member ) {
  1196. case 'X':
  1197. this.obj.x = data;
  1198. break;
  1199. case 'Y':
  1200. this.obj.y = data;
  1201. break;
  1202. case 'Z':
  1203. this.obj.z = data;
  1204. break;
  1205. default:
  1206. this.obj.x = data[ 0 ];
  1207. this.obj.y = data[ 1 ];
  1208. this.obj.z = data[ 2 ];
  1209. break;
  1210. }
  1211. break;
  1212. case 'rotate':
  1213. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1214. member = members[ member[ 0 ] ];
  1215. }
  1216. switch ( member ) {
  1217. case 'X':
  1218. this.obj.x = data;
  1219. break;
  1220. case 'Y':
  1221. this.obj.y = data;
  1222. break;
  1223. case 'Z':
  1224. this.obj.z = data;
  1225. break;
  1226. case 'ANGLE':
  1227. this.angle = data * TO_RADIANS;
  1228. break;
  1229. default:
  1230. this.obj.x = data[ 0 ];
  1231. this.obj.y = data[ 1 ];
  1232. this.obj.z = data[ 2 ];
  1233. this.angle = data[ 3 ] * TO_RADIANS;
  1234. break;
  1235. }
  1236. break;
  1237. }
  1238. };
  1239. function InstanceController() {
  1240. this.url = "";
  1241. this.skeleton = [];
  1242. this.instance_material = [];
  1243. };
  1244. InstanceController.prototype.parse = function ( element ) {
  1245. this.url = element.getAttribute('url').replace(/^#/, '');
  1246. this.skeleton = [];
  1247. this.instance_material = [];
  1248. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1249. var child = element.childNodes[i];
  1250. if (child.nodeType != 1) continue;
  1251. switch ( child.nodeName ) {
  1252. case 'skeleton':
  1253. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1254. break;
  1255. case 'bind_material':
  1256. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  1257. if ( instances ) {
  1258. var instance = instances.iterateNext();
  1259. while ( instance ) {
  1260. this.instance_material.push((new InstanceMaterial()).parse(instance));
  1261. instance = instances.iterateNext();
  1262. }
  1263. }
  1264. break;
  1265. case 'extra':
  1266. break;
  1267. default:
  1268. break;
  1269. }
  1270. }
  1271. return this;
  1272. };
  1273. function InstanceMaterial () {
  1274. this.symbol = "";
  1275. this.target = "";
  1276. };
  1277. InstanceMaterial.prototype.parse = function ( element ) {
  1278. this.symbol = element.getAttribute('symbol');
  1279. this.target = element.getAttribute('target').replace(/^#/, '');
  1280. return this;
  1281. };
  1282. function InstanceGeometry() {
  1283. this.url = "";
  1284. this.instance_material = [];
  1285. };
  1286. InstanceGeometry.prototype.parse = function ( element ) {
  1287. this.url = element.getAttribute('url').replace(/^#/, '');
  1288. this.instance_material = [];
  1289. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1290. var child = element.childNodes[i];
  1291. if ( child.nodeType != 1 ) continue;
  1292. if ( child.nodeName == 'bind_material' ) {
  1293. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  1294. if ( instances ) {
  1295. var instance = instances.iterateNext();
  1296. while ( instance ) {
  1297. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1298. instance = instances.iterateNext();
  1299. }
  1300. }
  1301. break;
  1302. }
  1303. }
  1304. return this;
  1305. };
  1306. function Geometry() {
  1307. this.id = "";
  1308. this.mesh = null;
  1309. };
  1310. Geometry.prototype.parse = function ( element ) {
  1311. this.id = element.getAttribute('id');
  1312. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1313. var child = element.childNodes[i];
  1314. switch ( child.nodeName ) {
  1315. case 'mesh':
  1316. this.mesh = (new Mesh(this)).parse(child);
  1317. break;
  1318. case 'extra':
  1319. // console.log( child );
  1320. break;
  1321. default:
  1322. break;
  1323. }
  1324. }
  1325. return this;
  1326. };
  1327. function Mesh( geometry ) {
  1328. this.geometry = geometry.id;
  1329. this.primitives = [];
  1330. this.vertices = null;
  1331. this.geometry3js = null;
  1332. };
  1333. Mesh.prototype.parse = function( element ) {
  1334. this.primitives = [];
  1335. var i, j;
  1336. for ( i = 0; i < element.childNodes.length; i ++ ) {
  1337. var child = element.childNodes[ i ];
  1338. switch ( child.nodeName ) {
  1339. case 'source':
  1340. _source( child );
  1341. break;
  1342. case 'vertices':
  1343. this.vertices = ( new Vertices() ).parse( child );
  1344. break;
  1345. case 'triangles':
  1346. this.primitives.push( ( new Triangles().parse( child ) ) );
  1347. break;
  1348. case 'polygons':
  1349. this.primitives.push( ( new Polygons().parse( child ) ) );
  1350. break;
  1351. case 'polylist':
  1352. this.primitives.push( ( new Polylist().parse( child ) ) );
  1353. break;
  1354. default:
  1355. break;
  1356. }
  1357. }
  1358. this.geometry3js = new THREE.Geometry();
  1359. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1360. for ( i = 0; i < vertexData.length; i += 3 ) {
  1361. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1362. }
  1363. for ( i = 0; i < this.primitives.length; i ++ ) {
  1364. var primitive = this.primitives[ i ];
  1365. primitive.setVertices( this.vertices );
  1366. this.handlePrimitive( primitive, this.geometry3js );
  1367. }
  1368. this.geometry3js.computeCentroids();
  1369. this.geometry3js.computeFaceNormals();
  1370. if ( this.geometry3js.calcNormals ) {
  1371. this.geometry3js.computeVertexNormals();
  1372. delete this.geometry3js.calcNormals;
  1373. }
  1374. this.geometry3js.computeBoundingBox();
  1375. return this;
  1376. };
  1377. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  1378. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1379. var input, index, idx32;
  1380. var source, numParams;
  1381. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1382. var texture_sets = [];
  1383. for ( j = 0; j < inputs.length; j ++ ) {
  1384. input = inputs[ j ];
  1385. var offset = input.offset + 1;
  1386. maxOffset = (maxOffset < offset)? offset : maxOffset;
  1387. switch ( input.semantic ) {
  1388. case 'TEXCOORD':
  1389. texture_sets.push( input.set );
  1390. break;
  1391. }
  1392. }
  1393. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  1394. var p = pList[ pCount ], i = 0;
  1395. while ( i < p.length ) {
  1396. var vs = [];
  1397. var ns = [];
  1398. var ts = null;
  1399. var cs = [];
  1400. if ( primitive.vcount ) {
  1401. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1402. } else {
  1403. vcount = p.length / maxOffset;
  1404. }
  1405. for ( j = 0; j < vcount; j ++ ) {
  1406. for ( k = 0; k < inputs.length; k ++ ) {
  1407. input = inputs[ k ];
  1408. source = sources[ input.source ];
  1409. index = p[ i + ( j * maxOffset ) + input.offset ];
  1410. numParams = source.accessor.params.length;
  1411. idx32 = index * numParams;
  1412. switch ( input.semantic ) {
  1413. case 'VERTEX':
  1414. vs.push( index );
  1415. break;
  1416. case 'NORMAL':
  1417. ns.push( getConvertedVec3( source.data, idx32 ) );
  1418. break;
  1419. case 'TEXCOORD':
  1420. ts = ts || { };
  1421. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1422. // invert the V
  1423. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1424. break;
  1425. case 'COLOR':
  1426. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1427. break;
  1428. default:
  1429. break;
  1430. }
  1431. }
  1432. }
  1433. if ( ns.length == 0 ) {
  1434. // check the vertices inputs
  1435. input = this.vertices.input.NORMAL;
  1436. if ( input ) {
  1437. source = sources[ input.source ];
  1438. numParams = source.accessor.params.length;
  1439. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  1440. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1441. }
  1442. } else {
  1443. geom.calcNormals = true;
  1444. }
  1445. }
  1446. if ( !ts ) {
  1447. ts = { };
  1448. // check the vertices inputs
  1449. input = this.vertices.input.TEXCOORD;
  1450. if ( input ) {
  1451. texture_sets.push( input.set );
  1452. source = sources[ input.source ];
  1453. numParams = source.accessor.params.length;
  1454. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  1455. idx32 = vs[ ndx ] * numParams;
  1456. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1457. // invert the V
  1458. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1459. }
  1460. }
  1461. }
  1462. if ( cs.length == 0 ) {
  1463. // check the vertices inputs
  1464. input = this.vertices.input.COLOR;
  1465. if ( input ) {
  1466. source = sources[ input.source ];
  1467. numParams = source.accessor.params.length;
  1468. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  1469. idx32 = vs[ ndx ] * numParams;
  1470. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1471. }
  1472. }
  1473. }
  1474. var face = null, faces = [], uv, uvArr;
  1475. if ( vcount === 3 ) {
  1476. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1477. } else if ( vcount === 4 ) {
  1478. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  1479. } else if ( vcount > 4 && options.subdivideFaces ) {
  1480. var clr = cs.length ? cs : new THREE.Color(),
  1481. vec1, vec2, vec3, v1, v2, norm;
  1482. // subdivide into multiple Face3s
  1483. for ( k = 1; k < vcount-1; ) {
  1484. // FIXME: normals don't seem to be quite right
  1485. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  1486. }
  1487. }
  1488. if ( faces.length ) {
  1489. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  1490. face = faces[ndx];
  1491. face.daeMaterial = primitive.material;
  1492. geom.faces.push( face );
  1493. for ( k = 0; k < texture_sets.length; k++ ) {
  1494. uv = ts[ texture_sets[k] ];
  1495. if ( vcount > 4 ) {
  1496. // Grab the right UVs for the vertices in this face
  1497. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  1498. } else if ( vcount === 4 ) {
  1499. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  1500. } else {
  1501. uvArr = [ uv[0], uv[1], uv[2] ];
  1502. }
  1503. if ( !geom.faceVertexUvs[k] ) {
  1504. geom.faceVertexUvs[k] = [];
  1505. }
  1506. geom.faceVertexUvs[k].push( uvArr );
  1507. }
  1508. }
  1509. } else {
  1510. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1511. }
  1512. i += maxOffset * vcount;
  1513. }
  1514. }
  1515. };
  1516. function Polygons () {
  1517. this.material = "";
  1518. this.count = 0;
  1519. this.inputs = [];
  1520. this.vcount = null;
  1521. this.p = [];
  1522. this.geometry = new THREE.Geometry();
  1523. };
  1524. Polygons.prototype.setVertices = function ( vertices ) {
  1525. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1526. if ( this.inputs[ i ].source == vertices.id ) {
  1527. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1528. }
  1529. }
  1530. };
  1531. Polygons.prototype.parse = function ( element ) {
  1532. this.material = element.getAttribute( 'material' );
  1533. this.count = _attr_as_int( element, 'count', 0 );
  1534. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1535. var child = element.childNodes[ i ];
  1536. switch ( child.nodeName ) {
  1537. case 'input':
  1538. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1539. break;
  1540. case 'vcount':
  1541. this.vcount = _ints( child.textContent );
  1542. break;
  1543. case 'p':
  1544. this.p.push( _ints( child.textContent ) );
  1545. break;
  1546. case 'ph':
  1547. console.warn( 'polygon holes not yet supported!' );
  1548. break;
  1549. default:
  1550. break;
  1551. }
  1552. }
  1553. return this;
  1554. };
  1555. function Polylist () {
  1556. Polygons.call( this );
  1557. this.vcount = [];
  1558. };
  1559. Polylist.prototype = Object.create( Polygons.prototype );
  1560. function Triangles () {
  1561. Polygons.call( this );
  1562. this.vcount = 3;
  1563. };
  1564. Triangles.prototype = Object.create( Polygons.prototype );
  1565. function Accessor() {
  1566. this.source = "";
  1567. this.count = 0;
  1568. this.stride = 0;
  1569. this.params = [];
  1570. };
  1571. Accessor.prototype.parse = function ( element ) {
  1572. this.params = [];
  1573. this.source = element.getAttribute( 'source' );
  1574. this.count = _attr_as_int( element, 'count', 0 );
  1575. this.stride = _attr_as_int( element, 'stride', 0 );
  1576. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1577. var child = element.childNodes[ i ];
  1578. if ( child.nodeName == 'param' ) {
  1579. var param = {};
  1580. param[ 'name' ] = child.getAttribute( 'name' );
  1581. param[ 'type' ] = child.getAttribute( 'type' );
  1582. this.params.push( param );
  1583. }
  1584. }
  1585. return this;
  1586. };
  1587. function Vertices() {
  1588. this.input = {};
  1589. };
  1590. Vertices.prototype.parse = function ( element ) {
  1591. this.id = element.getAttribute('id');
  1592. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1593. if ( element.childNodes[i].nodeName == 'input' ) {
  1594. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1595. this.input[ input.semantic ] = input;
  1596. }
  1597. }
  1598. return this;
  1599. };
  1600. function Input () {
  1601. this.semantic = "";
  1602. this.offset = 0;
  1603. this.source = "";
  1604. this.set = 0;
  1605. };
  1606. Input.prototype.parse = function ( element ) {
  1607. this.semantic = element.getAttribute('semantic');
  1608. this.source = element.getAttribute('source').replace(/^#/, '');
  1609. this.set = _attr_as_int(element, 'set', -1);
  1610. this.offset = _attr_as_int(element, 'offset', 0);
  1611. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  1612. this.set = 0;
  1613. }
  1614. return this;
  1615. };
  1616. function Source ( id ) {
  1617. this.id = id;
  1618. this.type = null;
  1619. };
  1620. Source.prototype.parse = function ( element ) {
  1621. this.id = element.getAttribute( 'id' );
  1622. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1623. var child = element.childNodes[i];
  1624. switch ( child.nodeName ) {
  1625. case 'bool_array':
  1626. this.data = _bools( child.textContent );
  1627. this.type = child.nodeName;
  1628. break;
  1629. case 'float_array':
  1630. this.data = _floats( child.textContent );
  1631. this.type = child.nodeName;
  1632. break;
  1633. case 'int_array':
  1634. this.data = _ints( child.textContent );
  1635. this.type = child.nodeName;
  1636. break;
  1637. case 'IDREF_array':
  1638. case 'Name_array':
  1639. this.data = _strings( child.textContent );
  1640. this.type = child.nodeName;
  1641. break;
  1642. case 'technique_common':
  1643. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1644. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  1645. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1646. break;
  1647. }
  1648. }
  1649. break;
  1650. default:
  1651. // console.log(child.nodeName);
  1652. break;
  1653. }
  1654. }
  1655. return this;
  1656. };
  1657. Source.prototype.read = function () {
  1658. var result = [];
  1659. //for (var i = 0; i < this.accessor.params.length; i++) {
  1660. var param = this.accessor.params[ 0 ];
  1661. //console.log(param.name + " " + param.type);
  1662. switch ( param.type ) {
  1663. case 'IDREF':
  1664. case 'Name': case 'name':
  1665. case 'float':
  1666. return this.data;
  1667. case 'float4x4':
  1668. for ( var j = 0; j < this.data.length; j += 16 ) {
  1669. var s = this.data.slice( j, j + 16 );
  1670. var m = getConvertedMat4( s );
  1671. result.push( m );
  1672. }
  1673. break;
  1674. default:
  1675. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  1676. break;
  1677. }
  1678. //}
  1679. return result;
  1680. };
  1681. function Material () {
  1682. this.id = "";
  1683. this.name = "";
  1684. this.instance_effect = null;
  1685. };
  1686. Material.prototype.parse = function ( element ) {
  1687. this.id = element.getAttribute( 'id' );
  1688. this.name = element.getAttribute( 'name' );
  1689. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1690. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  1691. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  1692. break;
  1693. }
  1694. }
  1695. return this;
  1696. };
  1697. function ColorOrTexture () {
  1698. this.color = new THREE.Color( 0 );
  1699. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  1700. this.color.a = 1.0;
  1701. this.texture = null;
  1702. this.texcoord = null;
  1703. this.texOpts = null;
  1704. };
  1705. ColorOrTexture.prototype.isColor = function () {
  1706. return ( this.texture == null );
  1707. };
  1708. ColorOrTexture.prototype.isTexture = function () {
  1709. return ( this.texture != null );
  1710. };
  1711. ColorOrTexture.prototype.parse = function ( element ) {
  1712. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1713. var child = element.childNodes[ i ];
  1714. if ( child.nodeType != 1 ) continue;
  1715. switch ( child.nodeName ) {
  1716. case 'color':
  1717. var rgba = _floats( child.textContent );
  1718. this.color = new THREE.Color(0);
  1719. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  1720. this.color.a = rgba[3];
  1721. break;
  1722. case 'texture':
  1723. this.texture = child.getAttribute('texture');
  1724. this.texcoord = child.getAttribute('texcoord');
  1725. // Defaults from:
  1726. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  1727. this.texOpts = {
  1728. offsetU: 0,
  1729. offsetV: 0,
  1730. repeatU: 1,
  1731. repeatV: 1,
  1732. wrapU: 1,
  1733. wrapV: 1,
  1734. };
  1735. this.parseTexture( child );
  1736. break;
  1737. default:
  1738. break;
  1739. }
  1740. }
  1741. return this;
  1742. };
  1743. ColorOrTexture.prototype.parseTexture = function ( element ) {
  1744. if ( ! element.childNodes ) return this;
  1745. // This should be supported by Maya, 3dsMax, and MotionBuilder
  1746. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  1747. element = element.childNodes[1];
  1748. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  1749. element = element.childNodes[1];
  1750. }
  1751. }
  1752. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1753. var child = element.childNodes[ i ];
  1754. switch ( child.nodeName ) {
  1755. case 'offsetU':
  1756. case 'offsetV':
  1757. case 'repeatU':
  1758. case 'repeatV':
  1759. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  1760. break;
  1761. case 'wrapU':
  1762. case 'wrapV':
  1763. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  1764. break;
  1765. default:
  1766. this.texOpts[ child.nodeName ] = child.textContent;
  1767. break;
  1768. }
  1769. }
  1770. return this;
  1771. };
  1772. function Shader ( type, effect ) {
  1773. this.type = type;
  1774. this.effect = effect;
  1775. this.material = null;
  1776. };
  1777. Shader.prototype.parse = function ( element ) {
  1778. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1779. var child = element.childNodes[ i ];
  1780. if ( child.nodeType != 1 ) continue;
  1781. switch ( child.nodeName ) {
  1782. case 'ambient':
  1783. case 'emission':
  1784. case 'diffuse':
  1785. case 'specular':
  1786. case 'transparent':
  1787. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  1788. break;
  1789. case 'shininess':
  1790. case 'reflectivity':
  1791. case 'index_of_refraction':
  1792. case 'transparency':
  1793. var f = evaluateXPath( child, './/dae:float' );
  1794. if ( f.length > 0 )
  1795. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  1796. break;
  1797. default:
  1798. break;
  1799. }
  1800. }
  1801. this.create();
  1802. return this;
  1803. };
  1804. Shader.prototype.create = function() {
  1805. var props = {};
  1806. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  1807. for ( var prop in this ) {
  1808. switch ( prop ) {
  1809. case 'ambient':
  1810. case 'emission':
  1811. case 'diffuse':
  1812. case 'specular':
  1813. var cot = this[prop];
  1814. if ( cot instanceof ColorOrTexture ) {
  1815. if ( cot.isTexture() ) {
  1816. if ( this.effect.sampler && this.effect.surface ) {
  1817. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  1818. var image = images[this.effect.surface.init_from];
  1819. if ( image ) {
  1820. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  1821. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  1822. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  1823. texture.offset.x = cot.texOpts.offsetU;
  1824. texture.offset.y = cot.texOpts.offsetV;
  1825. texture.repeat.x = cot.texOpts.repeatU;
  1826. texture.repeat.y = cot.texOpts.repeatV;
  1827. props['map'] = texture;
  1828. // Texture with baked lighting?
  1829. if ( prop == 'emission' ) props[ 'emissive' ] = 0xffffff;
  1830. }
  1831. }
  1832. }
  1833. } else if ( prop == 'diffuse' || !transparent ) {
  1834. if ( prop == 'emission' ) {
  1835. props[ 'emissive' ] = cot.color.getHex();
  1836. } else {
  1837. props[ prop ] = cot.color.getHex();
  1838. }
  1839. }
  1840. }
  1841. break;
  1842. case 'shininess':
  1843. props[ prop ] = this[ prop ];
  1844. break;
  1845. case 'reflectivity':
  1846. props[ prop ] = this[ prop ];
  1847. if(props[ prop ] > 0.0) props['envMap'] = options.defaultEnvMap;
  1848. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  1849. break;
  1850. case 'index_of_refraction':
  1851. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  1852. if(this[ prop ] != 1.0) props['envMap'] = options.defaultEnvMap;
  1853. break;
  1854. case 'transparency':
  1855. if ( transparent ) {
  1856. props[ 'transparent' ] = true;
  1857. props[ 'opacity' ] = this[ prop ];
  1858. transparent = true;
  1859. }
  1860. break;
  1861. default:
  1862. break;
  1863. }
  1864. }
  1865. props[ 'shading' ] = preferredShading;
  1866. props[ 'doubleSided' ] = this.effect.doubleSided;
  1867. switch ( this.type ) {
  1868. case 'constant':
  1869. props.color = props.emission;
  1870. this.material = new THREE.MeshBasicMaterial( props );
  1871. break;
  1872. case 'phong':
  1873. case 'blinn':
  1874. props.color = props.diffuse;
  1875. this.material = new THREE.MeshPhongMaterial( props );
  1876. break;
  1877. case 'lambert':
  1878. default:
  1879. props.color = props.diffuse;
  1880. this.material = new THREE.MeshLambertMaterial( props );
  1881. break;
  1882. }
  1883. return this.material;
  1884. };
  1885. function Surface ( effect ) {
  1886. this.effect = effect;
  1887. this.init_from = null;
  1888. this.format = null;
  1889. };
  1890. Surface.prototype.parse = function ( element ) {
  1891. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1892. var child = element.childNodes[ i ];
  1893. if ( child.nodeType != 1 ) continue;
  1894. switch ( child.nodeName ) {
  1895. case 'init_from':
  1896. this.init_from = child.textContent;
  1897. break;
  1898. case 'format':
  1899. this.format = child.textContent;
  1900. break;
  1901. default:
  1902. console.log( "unhandled Surface prop: " + child.nodeName );
  1903. break;
  1904. }
  1905. }
  1906. return this;
  1907. };
  1908. function Sampler2D ( effect ) {
  1909. this.effect = effect;
  1910. this.source = null;
  1911. this.wrap_s = null;
  1912. this.wrap_t = null;
  1913. this.minfilter = null;
  1914. this.magfilter = null;
  1915. this.mipfilter = null;
  1916. };
  1917. Sampler2D.prototype.parse = function ( element ) {
  1918. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1919. var child = element.childNodes[ i ];
  1920. if ( child.nodeType != 1 ) continue;
  1921. switch ( child.nodeName ) {
  1922. case 'source':
  1923. this.source = child.textContent;
  1924. break;
  1925. case 'minfilter':
  1926. this.minfilter = child.textContent;
  1927. break;
  1928. case 'magfilter':
  1929. this.magfilter = child.textContent;
  1930. break;
  1931. case 'mipfilter':
  1932. this.mipfilter = child.textContent;
  1933. break;
  1934. case 'wrap_s':
  1935. this.wrap_s = child.textContent;
  1936. break;
  1937. case 'wrap_t':
  1938. this.wrap_t = child.textContent;
  1939. break;
  1940. default:
  1941. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  1942. break;
  1943. }
  1944. }
  1945. return this;
  1946. };
  1947. function Effect () {
  1948. this.id = "";
  1949. this.name = "";
  1950. this.shader = null;
  1951. this.surface = null;
  1952. this.sampler = null;
  1953. };
  1954. Effect.prototype.create = function () {
  1955. if ( this.shader == null ) {
  1956. return null;
  1957. }
  1958. };
  1959. Effect.prototype.parse = function ( element ) {
  1960. this.id = element.getAttribute( 'id' );
  1961. this.name = element.getAttribute( 'name' );
  1962. this.doubleSided = false;
  1963. var double_sided = COLLADA.evaluate( './/dae:extra//dae:double_sided', element, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  1964. if (double_sided) {
  1965. double_sided = double_sided.iterateNext();
  1966. if ( double_sided && parseInt( double_sided.textContent, 10 ) === 1) {
  1967. this.doubleSided = true;
  1968. }
  1969. }
  1970. this.shader = null;
  1971. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1972. var child = element.childNodes[ i ];
  1973. if ( child.nodeType != 1 ) continue;
  1974. switch ( child.nodeName ) {
  1975. case 'profile_COMMON':
  1976. this.parseTechnique( this.parseProfileCOMMON( child ) );
  1977. break;
  1978. default:
  1979. break;
  1980. }
  1981. }
  1982. return this;
  1983. };
  1984. Effect.prototype.parseNewparam = function ( element ) {
  1985. var sid = element.getAttribute( 'sid' );
  1986. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1987. var child = element.childNodes[ i ];
  1988. if ( child.nodeType != 1 ) continue;
  1989. switch ( child.nodeName ) {
  1990. case 'surface':
  1991. this.surface = ( new Surface( this ) ).parse( child );
  1992. this.surface.sid = sid;
  1993. break;
  1994. case 'sampler2D':
  1995. this.sampler = ( new Sampler2D( this ) ).parse( child );
  1996. this.sampler.sid = sid;
  1997. break;
  1998. case 'extra':
  1999. break;
  2000. default:
  2001. console.log( child.nodeName );
  2002. break;
  2003. }
  2004. }
  2005. };
  2006. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2007. var technique;
  2008. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2009. var child = element.childNodes[ i ];
  2010. if ( child.nodeType != 1 ) continue;
  2011. switch ( child.nodeName ) {
  2012. case 'profile_COMMON':
  2013. this.parseProfileCOMMON( child );
  2014. break;
  2015. case 'technique':
  2016. technique = child;
  2017. break;
  2018. case 'newparam':
  2019. this.parseNewparam( child );
  2020. break;
  2021. case 'image':
  2022. var _image = ( new _Image() ).parse( child );
  2023. images[ _image.id ] = _image;
  2024. break;
  2025. case 'extra':
  2026. break;
  2027. default:
  2028. console.log( child.nodeName );
  2029. break;
  2030. }
  2031. }
  2032. return technique;
  2033. };
  2034. Effect.prototype.parseTechnique= function ( element ) {
  2035. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2036. var child = element.childNodes[i];
  2037. if ( child.nodeType != 1 ) continue;
  2038. switch ( child.nodeName ) {
  2039. case 'constant':
  2040. case 'lambert':
  2041. case 'blinn':
  2042. case 'phong':
  2043. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2044. break;
  2045. default:
  2046. break;
  2047. }
  2048. }
  2049. };
  2050. function InstanceEffect () {
  2051. this.url = "";
  2052. };
  2053. InstanceEffect.prototype.parse = function ( element ) {
  2054. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2055. return this;
  2056. };
  2057. function Animation() {
  2058. this.id = "";
  2059. this.name = "";
  2060. this.source = {};
  2061. this.sampler = [];
  2062. this.channel = [];
  2063. };
  2064. Animation.prototype.parse = function ( element ) {
  2065. this.id = element.getAttribute( 'id' );
  2066. this.name = element.getAttribute( 'name' );
  2067. this.source = {};
  2068. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2069. var child = element.childNodes[ i ];
  2070. if ( child.nodeType != 1 ) continue;
  2071. switch ( child.nodeName ) {
  2072. case 'animation':
  2073. var anim = ( new Animation() ).parse( child );
  2074. for ( var src in anim.source ) {
  2075. this.source[ src ] = anim.source[ src ];
  2076. }
  2077. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2078. this.channel.push( anim.channel[ j ] );
  2079. this.sampler.push( anim.sampler[ j ] );
  2080. }
  2081. break;
  2082. case 'source':
  2083. var src = ( new Source() ).parse( child );
  2084. this.source[ src.id ] = src;
  2085. break;
  2086. case 'sampler':
  2087. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2088. break;
  2089. case 'channel':
  2090. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2091. break;
  2092. default:
  2093. break;
  2094. }
  2095. }
  2096. return this;
  2097. };
  2098. function Channel( animation ) {
  2099. this.animation = animation;
  2100. this.source = "";
  2101. this.target = "";
  2102. this.fullSid = null;
  2103. this.sid = null;
  2104. this.dotSyntax = null;
  2105. this.arrSyntax = null;
  2106. this.arrIndices = null;
  2107. this.member = null;
  2108. };
  2109. Channel.prototype.parse = function ( element ) {
  2110. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2111. this.target = element.getAttribute( 'target' );
  2112. var parts = this.target.split( '/' );
  2113. var id = parts.shift();
  2114. var sid = parts.shift();
  2115. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2116. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2117. if ( dotSyntax ) {
  2118. parts = sid.split(".");
  2119. this.sid = parts.shift();
  2120. this.member = parts.shift();
  2121. } else if ( arrSyntax ) {
  2122. var arrIndices = sid.split("(");
  2123. this.sid = arrIndices.shift();
  2124. for (var j = 0; j < arrIndices.length; j ++ ) {
  2125. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2126. }
  2127. this.arrIndices = arrIndices;
  2128. } else {
  2129. this.sid = sid;
  2130. }
  2131. this.fullSid = sid;
  2132. this.dotSyntax = dotSyntax;
  2133. this.arrSyntax = arrSyntax;
  2134. return this;
  2135. };
  2136. function Sampler ( animation ) {
  2137. this.id = "";
  2138. this.animation = animation;
  2139. this.inputs = [];
  2140. this.input = null;
  2141. this.output = null;
  2142. this.strideOut = null;
  2143. this.interpolation = null;
  2144. this.startTime = null;
  2145. this.endTime = null;
  2146. this.duration = 0;
  2147. };
  2148. Sampler.prototype.parse = function ( element ) {
  2149. this.id = element.getAttribute( 'id' );
  2150. this.inputs = [];
  2151. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2152. var child = element.childNodes[ i ];
  2153. if ( child.nodeType != 1 ) continue;
  2154. switch ( child.nodeName ) {
  2155. case 'input':
  2156. this.inputs.push( (new Input()).parse( child ) );
  2157. break;
  2158. default:
  2159. break;
  2160. }
  2161. }
  2162. return this;
  2163. };
  2164. Sampler.prototype.create = function () {
  2165. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2166. var input = this.inputs[ i ];
  2167. var source = this.animation.source[ input.source ];
  2168. switch ( input.semantic ) {
  2169. case 'INPUT':
  2170. this.input = source.read();
  2171. break;
  2172. case 'OUTPUT':
  2173. this.output = source.read();
  2174. this.strideOut = source.accessor.stride;
  2175. break;
  2176. case 'INTERPOLATION':
  2177. this.interpolation = source.read();
  2178. break;
  2179. case 'IN_TANGENT':
  2180. break;
  2181. case 'OUT_TANGENT':
  2182. break;
  2183. default:
  2184. console.log(input.semantic);
  2185. break;
  2186. }
  2187. }
  2188. this.startTime = 0;
  2189. this.endTime = 0;
  2190. this.duration = 0;
  2191. if ( this.input.length ) {
  2192. this.startTime = 100000000;
  2193. this.endTime = -100000000;
  2194. for ( var i = 0; i < this.input.length; i ++ ) {
  2195. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2196. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2197. }
  2198. this.duration = this.endTime - this.startTime;
  2199. }
  2200. };
  2201. Sampler.prototype.getData = function ( type, ndx ) {
  2202. var data;
  2203. if ( type === 'matrix' && this.strideOut === 16 ) {
  2204. data = this.output[ ndx ];
  2205. } else if ( this.strideOut > 1 ) {
  2206. data = [];
  2207. ndx *= this.strideOut;
  2208. for ( var i = 0; i < this.strideOut; ++i ) {
  2209. data[ i ] = this.output[ ndx + i ];
  2210. }
  2211. if ( this.strideOut === 3 ) {
  2212. switch ( type ) {
  2213. case 'rotate':
  2214. case 'translate':
  2215. fixCoords( data, -1 );
  2216. break;
  2217. case 'scale':
  2218. fixCoords( data, 1 );
  2219. break;
  2220. }
  2221. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2222. fixCoords( data, -1 );
  2223. }
  2224. } else {
  2225. data = this.output[ ndx ];
  2226. }
  2227. return data;
  2228. };
  2229. function Key ( time ) {
  2230. this.targets = [];
  2231. this.time = time;
  2232. };
  2233. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2234. this.targets.push( {
  2235. sid: fullSid,
  2236. member: member,
  2237. transform: transform,
  2238. data: data
  2239. } );
  2240. };
  2241. Key.prototype.apply = function ( opt_sid ) {
  2242. for ( var i = 0; i < this.targets.length; ++i ) {
  2243. var target = this.targets[ i ];
  2244. if ( !opt_sid || target.sid === opt_sid ) {
  2245. target.transform.update( target.data, target.member );
  2246. }
  2247. }
  2248. };
  2249. Key.prototype.getTarget = function ( fullSid ) {
  2250. for ( var i = 0; i < this.targets.length; ++i ) {
  2251. if ( this.targets[ i ].sid === fullSid ) {
  2252. return this.targets[ i ];
  2253. }
  2254. }
  2255. return null;
  2256. };
  2257. Key.prototype.hasTarget = function ( fullSid ) {
  2258. for ( var i = 0; i < this.targets.length; ++i ) {
  2259. if ( this.targets[ i ].sid === fullSid ) {
  2260. return true;
  2261. }
  2262. }
  2263. return false;
  2264. };
  2265. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2266. Key.prototype.interpolate = function ( nextKey, time ) {
  2267. for ( var i = 0; i < this.targets.length; ++i ) {
  2268. var target = this.targets[ i ],
  2269. nextTarget = nextKey.getTarget( target.sid ),
  2270. data;
  2271. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2272. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2273. nextData = nextTarget.data,
  2274. prevData = target.data;
  2275. // check scale error
  2276. if ( scale < 0 || scale > 1 ) {
  2277. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  2278. scale = scale < 0 ? 0 : 1;
  2279. }
  2280. if ( prevData.length ) {
  2281. data = [];
  2282. for ( var j = 0; j < prevData.length; ++j ) {
  2283. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2284. }
  2285. } else {
  2286. data = prevData + ( nextData - prevData ) * scale;
  2287. }
  2288. } else {
  2289. data = target.data;
  2290. }
  2291. target.transform.update( data, target.member );
  2292. }
  2293. };
  2294. function Camera() {
  2295. this.id = "";
  2296. this.name = "";
  2297. this.technique = "";
  2298. };
  2299. Camera.prototype.parse = function ( element ) {
  2300. this.id = element.getAttribute( 'id' );
  2301. this.name = element.getAttribute( 'name' );
  2302. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2303. var child = element.childNodes[ i ];
  2304. if ( child.nodeType != 1 ) continue;
  2305. switch ( child.nodeName ) {
  2306. case 'optics':
  2307. this.parseOptics( child );
  2308. break;
  2309. default:
  2310. break;
  2311. }
  2312. }
  2313. return this;
  2314. };
  2315. Camera.prototype.parseOptics = function ( element ) {
  2316. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2317. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  2318. var technique = element.childNodes[ i ];
  2319. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2320. this.technique = technique.childNodes[ j ].nodeName;
  2321. if ( this.technique == 'perspective' ) {
  2322. var perspective = technique.childNodes[ j ];
  2323. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2324. var param = perspective.childNodes[ k ];
  2325. switch ( param.nodeName ) {
  2326. case 'yfov':
  2327. this.yfov = param.textContent;
  2328. break;
  2329. case 'xfov':
  2330. this.xfov = param.textContent;
  2331. break;
  2332. case 'znear':
  2333. this.znear = param.textContent;
  2334. break;
  2335. case 'zfar':
  2336. this.zfar = param.textContent;
  2337. break;
  2338. case 'aspect_ratio':
  2339. this.aspect_ratio = param.textContent;
  2340. break;
  2341. }
  2342. }
  2343. } else if ( this.technique == 'orthographic' ) {
  2344. var orthographic = technique.childNodes[ j ];
  2345. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2346. var param = orthographic.childNodes[ k ];
  2347. switch ( param.nodeName ) {
  2348. case 'xmag':
  2349. this.xmag = param.textContent;
  2350. break;
  2351. case 'ymag':
  2352. this.ymag = param.textContent;
  2353. break;
  2354. case 'znear':
  2355. this.znear = param.textContent;
  2356. break;
  2357. case 'zfar':
  2358. this.zfar = param.textContent;
  2359. break;
  2360. case 'aspect_ratio':
  2361. this.aspect_ratio = param.textContent;
  2362. break;
  2363. }
  2364. }
  2365. }
  2366. }
  2367. }
  2368. }
  2369. return this;
  2370. };
  2371. function InstanceCamera() {
  2372. this.url = "";
  2373. };
  2374. InstanceCamera.prototype.parse = function ( element ) {
  2375. this.url = element.getAttribute('url').replace(/^#/, '');
  2376. return this;
  2377. };
  2378. function _source( element ) {
  2379. var id = element.getAttribute( 'id' );
  2380. if ( sources[ id ] != undefined ) {
  2381. return sources[ id ];
  2382. }
  2383. sources[ id ] = ( new Source(id )).parse( element );
  2384. return sources[ id ];
  2385. };
  2386. function _nsResolver( nsPrefix ) {
  2387. if ( nsPrefix == "dae" ) {
  2388. return "http://www.collada.org/2005/11/COLLADASchema";
  2389. }
  2390. return null;
  2391. };
  2392. function _bools( str ) {
  2393. var raw = _strings( str );
  2394. var data = [];
  2395. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  2396. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  2397. }
  2398. return data;
  2399. };
  2400. function _floats( str ) {
  2401. var raw = _strings(str);
  2402. var data = [];
  2403. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  2404. data.push( parseFloat( raw[ i ] ) );
  2405. }
  2406. return data;
  2407. };
  2408. function _ints( str ) {
  2409. var raw = _strings( str );
  2410. var data = [];
  2411. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  2412. data.push( parseInt( raw[ i ], 10 ) );
  2413. }
  2414. return data;
  2415. };
  2416. function _strings( str ) {
  2417. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  2418. };
  2419. function _trimString( str ) {
  2420. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  2421. };
  2422. function _attr_as_float( element, name, defaultValue ) {
  2423. if ( element.hasAttribute( name ) ) {
  2424. return parseFloat( element.getAttribute( name ) );
  2425. } else {
  2426. return defaultValue;
  2427. }
  2428. };
  2429. function _attr_as_int( element, name, defaultValue ) {
  2430. if ( element.hasAttribute( name ) ) {
  2431. return parseInt( element.getAttribute( name ), 10) ;
  2432. } else {
  2433. return defaultValue;
  2434. }
  2435. };
  2436. function _attr_as_string( element, name, defaultValue ) {
  2437. if ( element.hasAttribute( name ) ) {
  2438. return element.getAttribute( name );
  2439. } else {
  2440. return defaultValue;
  2441. }
  2442. };
  2443. function _format_float( f, num ) {
  2444. if ( f === undefined ) {
  2445. var s = '0.';
  2446. while ( s.length < num + 2 ) {
  2447. s += '0';
  2448. }
  2449. return s;
  2450. }
  2451. num = num || 2;
  2452. var parts = f.toString().split( '.' );
  2453. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  2454. while( parts[ 1 ].length < num ) {
  2455. parts[ 1 ] += '0';
  2456. }
  2457. return parts.join( '.' );
  2458. };
  2459. function evaluateXPath( node, query ) {
  2460. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  2461. var inst = instances.iterateNext();
  2462. var result = [];
  2463. while ( inst ) {
  2464. result.push( inst );
  2465. inst = instances.iterateNext();
  2466. }
  2467. return result;
  2468. };
  2469. // Up axis conversion
  2470. function setUpConversion() {
  2471. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  2472. upConversion = null;
  2473. } else {
  2474. switch ( colladaUp ) {
  2475. case 'X':
  2476. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  2477. break;
  2478. case 'Y':
  2479. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  2480. break;
  2481. case 'Z':
  2482. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  2483. break;
  2484. }
  2485. }
  2486. };
  2487. function fixCoords( data, sign ) {
  2488. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  2489. return;
  2490. }
  2491. switch ( upConversion ) {
  2492. case 'XtoY':
  2493. var tmp = data[ 0 ];
  2494. data[ 0 ] = sign * data[ 1 ];
  2495. data[ 1 ] = tmp;
  2496. break;
  2497. case 'XtoZ':
  2498. var tmp = data[ 2 ];
  2499. data[ 2 ] = data[ 1 ];
  2500. data[ 1 ] = data[ 0 ];
  2501. data[ 0 ] = tmp;
  2502. break;
  2503. case 'YtoX':
  2504. var tmp = data[ 0 ];
  2505. data[ 0 ] = data[ 1 ];
  2506. data[ 1 ] = sign * tmp;
  2507. break;
  2508. case 'YtoZ':
  2509. var tmp = data[ 1 ];
  2510. data[ 1 ] = sign * data[ 2 ];
  2511. data[ 2 ] = tmp;
  2512. break;
  2513. case 'ZtoX':
  2514. var tmp = data[ 0 ];
  2515. data[ 0 ] = data[ 1 ];
  2516. data[ 1 ] = data[ 2 ];
  2517. data[ 2 ] = tmp;
  2518. break;
  2519. case 'ZtoY':
  2520. var tmp = data[ 1 ];
  2521. data[ 1 ] = data[ 2 ];
  2522. data[ 2 ] = sign * tmp;
  2523. break;
  2524. }
  2525. };
  2526. function getConvertedVec3( data, offset ) {
  2527. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  2528. fixCoords( arr, -1 );
  2529. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  2530. };
  2531. function getConvertedMat4( data ) {
  2532. if ( options.convertUpAxis ) {
  2533. // First fix rotation and scale
  2534. // Columns first
  2535. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  2536. fixCoords( arr, -1 );
  2537. data[ 0 ] = arr[ 0 ];
  2538. data[ 4 ] = arr[ 1 ];
  2539. data[ 8 ] = arr[ 2 ];
  2540. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  2541. fixCoords( arr, -1 );
  2542. data[ 1 ] = arr[ 0 ];
  2543. data[ 5 ] = arr[ 1 ];
  2544. data[ 9 ] = arr[ 2 ];
  2545. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  2546. fixCoords( arr, -1 );
  2547. data[ 2 ] = arr[ 0 ];
  2548. data[ 6 ] = arr[ 1 ];
  2549. data[ 10 ] = arr[ 2 ];
  2550. // Rows second
  2551. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  2552. fixCoords( arr, -1 );
  2553. data[ 0 ] = arr[ 0 ];
  2554. data[ 1 ] = arr[ 1 ];
  2555. data[ 2 ] = arr[ 2 ];
  2556. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  2557. fixCoords( arr, -1 );
  2558. data[ 4 ] = arr[ 0 ];
  2559. data[ 5 ] = arr[ 1 ];
  2560. data[ 6 ] = arr[ 2 ];
  2561. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  2562. fixCoords( arr, -1 );
  2563. data[ 8 ] = arr[ 0 ];
  2564. data[ 9 ] = arr[ 1 ];
  2565. data[ 10 ] = arr[ 2 ];
  2566. // Now fix translation
  2567. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  2568. fixCoords( arr, -1 );
  2569. data[ 3 ] = arr[ 0 ];
  2570. data[ 7 ] = arr[ 1 ];
  2571. data[ 11 ] = arr[ 2 ];
  2572. }
  2573. return new THREE.Matrix4(
  2574. data[0], data[1], data[2], data[3],
  2575. data[4], data[5], data[6], data[7],
  2576. data[8], data[9], data[10], data[11],
  2577. data[12], data[13], data[14], data[15]
  2578. );
  2579. };
  2580. function getConvertedIndex( index ) {
  2581. if ( index > -1 && index < 3 ) {
  2582. var members = ['X', 'Y', 'Z'],
  2583. indices = { X: 0, Y: 1, Z: 2 };
  2584. index = getConvertedMember( members[ index ] );
  2585. index = indices[ index ];
  2586. }
  2587. return index;
  2588. };
  2589. function getConvertedMember( member ) {
  2590. if ( options.convertUpAxis ) {
  2591. switch ( member ) {
  2592. case 'X':
  2593. switch ( upConversion ) {
  2594. case 'XtoY':
  2595. case 'XtoZ':
  2596. case 'YtoX':
  2597. member = 'Y';
  2598. break;
  2599. case 'ZtoX':
  2600. member = 'Z';
  2601. break;
  2602. }
  2603. break;
  2604. case 'Y':
  2605. switch ( upConversion ) {
  2606. case 'XtoY':
  2607. case 'YtoX':
  2608. case 'ZtoX':
  2609. member = 'X';
  2610. break;
  2611. case 'XtoZ':
  2612. case 'YtoZ':
  2613. case 'ZtoY':
  2614. member = 'Z';
  2615. break;
  2616. }
  2617. break;
  2618. case 'Z':
  2619. switch ( upConversion ) {
  2620. case 'XtoZ':
  2621. member = 'X';
  2622. break;
  2623. case 'YtoZ':
  2624. case 'ZtoX':
  2625. case 'ZtoY':
  2626. member = 'Y';
  2627. break;
  2628. }
  2629. break;
  2630. }
  2631. }
  2632. return member;
  2633. };
  2634. return {
  2635. load: load,
  2636. parse: parse,
  2637. setPreferredShading: setPreferredShading,
  2638. applySkin: applySkin,
  2639. geometries : geometries,
  2640. options: options
  2641. };
  2642. };