ColladaLoader.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511
  1. /**
  2. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  3. * @author Tony Parisi / http://www.tonyparisi.com/
  4. */
  5. THREE.ColladaLoader = function () {
  6. var COLLADA = null;
  7. var scene = null;
  8. var visualScene;
  9. var kinematicsModel;
  10. var readyCallbackFunc = null;
  11. var sources = {};
  12. var images = {};
  13. var animations = {};
  14. var controllers = {};
  15. var geometries = {};
  16. var materials = {};
  17. var effects = {};
  18. var cameras = {};
  19. var lights = {};
  20. var animData;
  21. var kinematics;
  22. var visualScenes;
  23. var kinematicsModels;
  24. var baseUrl;
  25. var morphs;
  26. var skins;
  27. var flip_uv = true;
  28. var preferredShading = THREE.SmoothShading;
  29. var options = {
  30. // Force Geometry to always be centered at the local origin of the
  31. // containing Mesh.
  32. centerGeometry: false,
  33. // Axis conversion is done for geometries, animations, and controllers.
  34. // If we ever pull cameras or lights out of the COLLADA file, they'll
  35. // need extra work.
  36. convertUpAxis: false,
  37. subdivideFaces: true,
  38. upAxis: 'Y',
  39. // For reflective or refractive materials we'll use this cubemap
  40. defaultEnvMap: null
  41. };
  42. var colladaUnit = 1.0;
  43. var colladaUp = 'Y';
  44. var upConversion = null;
  45. function load ( url, readyCallback, progressCallback, failCallback ) {
  46. var length = 0;
  47. if ( document.implementation && document.implementation.createDocument ) {
  48. var request = new XMLHttpRequest();
  49. request.onreadystatechange = function() {
  50. if ( request.readyState === 4 ) {
  51. if ( request.status === 0 || request.status === 200 ) {
  52. if ( request.responseXML ) {
  53. readyCallbackFunc = readyCallback;
  54. parse( request.responseXML, undefined, url );
  55. } else if ( request.responseText ) {
  56. readyCallbackFunc = readyCallback;
  57. var xmlParser = new DOMParser();
  58. var responseXML = xmlParser.parseFromString( request.responseText, "application/xml" );
  59. parse( responseXML, undefined, url );
  60. } else {
  61. if ( faillCallback ) {
  62. failCallback();
  63. } else {
  64. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  65. }
  66. }
  67. }
  68. } else if ( request.readyState === 3 ) {
  69. if ( progressCallback ) {
  70. if ( length === 0 ) {
  71. length = request.getResponseHeader( "Content-Length" );
  72. }
  73. progressCallback( { total: length, loaded: request.responseText.length } );
  74. }
  75. }
  76. }
  77. request.open( "GET", url, true );
  78. request.send( null );
  79. } else {
  80. alert( "Don't know how to parse XML!" );
  81. }
  82. }
  83. function parse( doc, callBack, url ) {
  84. COLLADA = doc;
  85. callBack = callBack || readyCallbackFunc;
  86. if ( url !== undefined ) {
  87. var parts = url.split( '/' );
  88. parts.pop();
  89. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  90. }
  91. parseAsset();
  92. setUpConversion();
  93. images = parseLib( "library_images image", _Image, "image" );
  94. materials = parseLib( "library_materials material", Material, "material" );
  95. effects = parseLib( "library_effects effect", Effect, "effect" );
  96. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  97. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  98. lights = parseLib( "library_lights light", Light, "light" );
  99. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  100. animations = parseLib( "library_animations animation", Animation, "animation" );
  101. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  102. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  103. morphs = [];
  104. skins = [];
  105. visualScene = parseScene();
  106. scene = new THREE.Group();
  107. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  108. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  109. }
  110. // unit conversion
  111. scene.scale.multiplyScalar( colladaUnit );
  112. createAnimations();
  113. kinematicsModel = parseKinematicsModel();
  114. createKinematics();
  115. var result = {
  116. scene: scene,
  117. morphs: morphs,
  118. skins: skins,
  119. animations: animData,
  120. kinematics: kinematics,
  121. dae: {
  122. images: images,
  123. materials: materials,
  124. cameras: cameras,
  125. lights: lights,
  126. effects: effects,
  127. geometries: geometries,
  128. controllers: controllers,
  129. animations: animations,
  130. visualScenes: visualScenes,
  131. visualScene: visualScene,
  132. scene: visualScene,
  133. kinematicsModels: kinematicsModels,
  134. kinematicsModel: kinematicsModel
  135. }
  136. };
  137. if ( callBack ) {
  138. callBack( result );
  139. }
  140. return result;
  141. }
  142. function setPreferredShading ( shading ) {
  143. preferredShading = shading;
  144. }
  145. function parseAsset () {
  146. var elements = COLLADA.querySelectorAll('asset');
  147. var element = elements[0];
  148. if ( element && element.childNodes ) {
  149. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  150. var child = element.childNodes[ i ];
  151. switch ( child.nodeName ) {
  152. case 'unit':
  153. var meter = child.getAttribute( 'meter' );
  154. if ( meter ) {
  155. colladaUnit = parseFloat( meter );
  156. }
  157. break;
  158. case 'up_axis':
  159. colladaUp = child.textContent.charAt(0);
  160. break;
  161. }
  162. }
  163. }
  164. }
  165. function parseLib ( q, classSpec, prefix ) {
  166. var elements = COLLADA.querySelectorAll(q);
  167. var lib = {};
  168. var i = 0;
  169. var elementsLength = elements.length;
  170. for ( var j = 0; j < elementsLength; j ++ ) {
  171. var element = elements[j];
  172. var daeElement = ( new classSpec() ).parse( element );
  173. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  174. lib[ daeElement.id ] = daeElement;
  175. }
  176. return lib;
  177. }
  178. function parseScene() {
  179. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  180. if ( sceneElement ) {
  181. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  182. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  183. } else {
  184. return null;
  185. }
  186. }
  187. function parseKinematicsModel() {
  188. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  189. if ( kinematicsModelElement ) {
  190. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  191. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  192. } else {
  193. return null;
  194. }
  195. }
  196. function createAnimations() {
  197. animData = [];
  198. // fill in the keys
  199. recurseHierarchy( scene );
  200. }
  201. function recurseHierarchy( node ) {
  202. var n = visualScene.getChildById( node.colladaId, true ),
  203. newData = null;
  204. if ( n && n.keys ) {
  205. newData = {
  206. fps: 60,
  207. hierarchy: [ {
  208. node: n,
  209. keys: n.keys,
  210. sids: n.sids
  211. } ],
  212. node: node,
  213. name: 'animation_' + node.name,
  214. length: 0
  215. };
  216. animData.push(newData);
  217. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  218. newData.length = Math.max( newData.length, n.keys[i].time );
  219. }
  220. } else {
  221. newData = {
  222. hierarchy: [ {
  223. keys: [],
  224. sids: []
  225. } ]
  226. }
  227. }
  228. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  229. var d = recurseHierarchy( node.children[i] );
  230. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  231. newData.hierarchy.push( {
  232. keys: [],
  233. sids: []
  234. } );
  235. }
  236. }
  237. return newData;
  238. }
  239. function calcAnimationBounds () {
  240. var start = 1000000;
  241. var end = -start;
  242. var frames = 0;
  243. var ID;
  244. for ( var id in animations ) {
  245. var animation = animations[ id ];
  246. ID = ID || animation.id;
  247. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  248. var sampler = animation.sampler[ i ];
  249. sampler.create();
  250. start = Math.min( start, sampler.startTime );
  251. end = Math.max( end, sampler.endTime );
  252. frames = Math.max( frames, sampler.input.length );
  253. }
  254. }
  255. return { start:start, end:end, frames:frames,ID:ID };
  256. }
  257. function createMorph ( geometry, ctrl ) {
  258. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  259. if ( !morphCtrl || !morphCtrl.morph ) {
  260. console.log("could not find morph controller!");
  261. return;
  262. }
  263. var morph = morphCtrl.morph;
  264. for ( var i = 0; i < morph.targets.length; i ++ ) {
  265. var target_id = morph.targets[ i ];
  266. var daeGeometry = geometries[ target_id ];
  267. if ( !daeGeometry.mesh ||
  268. !daeGeometry.mesh.primitives ||
  269. !daeGeometry.mesh.primitives.length ) {
  270. continue;
  271. }
  272. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  273. if ( target.vertices.length === geometry.vertices.length ) {
  274. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  275. }
  276. }
  277. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  278. };
  279. function createSkin ( geometry, ctrl, applyBindShape ) {
  280. var skinCtrl = controllers[ ctrl.url ];
  281. if ( !skinCtrl || !skinCtrl.skin ) {
  282. console.log( "could not find skin controller!" );
  283. return;
  284. }
  285. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  286. console.log( "could not find the skeleton for the skin!" );
  287. return;
  288. }
  289. var skin = skinCtrl.skin;
  290. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  291. var hierarchy = [];
  292. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  293. var bones = [];
  294. geometry.skinWeights = [];
  295. geometry.skinIndices = [];
  296. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  297. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  298. /*
  299. geometry.animation = {
  300. name: 'take_001',
  301. fps: 30,
  302. length: 2,
  303. JIT: true,
  304. hierarchy: hierarchy
  305. };
  306. */
  307. if ( applyBindShape ) {
  308. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  309. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  310. }
  311. }
  312. }
  313. function setupSkeleton ( node, bones, frame, parent ) {
  314. node.world = node.world || new THREE.Matrix4();
  315. node.localworld = node.localworld || new THREE.Matrix4();
  316. node.world.copy( node.matrix );
  317. node.localworld.copy( node.matrix );
  318. if ( node.channels && node.channels.length ) {
  319. var channel = node.channels[ 0 ];
  320. var m = channel.sampler.output[ frame ];
  321. if ( m instanceof THREE.Matrix4 ) {
  322. node.world.copy( m );
  323. node.localworld.copy(m);
  324. if (frame === 0)
  325. node.matrix.copy(m);
  326. }
  327. }
  328. if ( parent ) {
  329. node.world.multiplyMatrices( parent, node.world );
  330. }
  331. bones.push( node );
  332. for ( var i = 0; i < node.nodes.length; i ++ ) {
  333. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  334. }
  335. }
  336. function setupSkinningMatrices ( bones, skin ) {
  337. // FIXME: this is dumb...
  338. for ( var i = 0; i < bones.length; i ++ ) {
  339. var bone = bones[ i ];
  340. var found = -1;
  341. if ( bone.type != 'JOINT' ) continue;
  342. for ( var j = 0; j < skin.joints.length; j ++ ) {
  343. if ( bone.sid === skin.joints[ j ] ) {
  344. found = j;
  345. break;
  346. }
  347. }
  348. if ( found >= 0 ) {
  349. var inv = skin.invBindMatrices[ found ];
  350. bone.invBindMatrix = inv;
  351. bone.skinningMatrix = new THREE.Matrix4();
  352. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  353. bone.animatrix = new THREE.Matrix4();
  354. bone.animatrix.copy(bone.localworld);
  355. bone.weights = [];
  356. for ( var j = 0; j < skin.weights.length; j ++ ) {
  357. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  358. var w = skin.weights[ j ][ k ];
  359. if ( w.joint === found ) {
  360. bone.weights.push( w );
  361. }
  362. }
  363. }
  364. } else {
  365. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  366. bone.skinningMatrix = new THREE.Matrix4();
  367. bone.weights = [];
  368. }
  369. }
  370. }
  371. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  372. function flattenSkeleton(skeleton) {
  373. var list = [];
  374. var walk = function(parentid, node, list) {
  375. var bone = {};
  376. bone.name = node.sid;
  377. bone.parent = parentid;
  378. bone.matrix = node.matrix;
  379. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  380. bone.matrix.decompose(data[0], data[1], data[2]);
  381. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  382. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  383. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  384. list.push(bone);
  385. for (var i in node.nodes) {
  386. walk(node.sid, node.nodes[i], list);
  387. }
  388. };
  389. walk(-1, skeleton, list);
  390. return list;
  391. }
  392. //Move the vertices into the pose that is proper for the start of the animation
  393. function skinToBindPose(geometry,skeleton,skinController) {
  394. var bones = [];
  395. setupSkeleton( skeleton, bones, -1 );
  396. setupSkinningMatrices( bones, skinController.skin );
  397. v = new THREE.Vector3();
  398. var skinned = [];
  399. for (var i = 0; i < geometry.vertices.length; i ++) {
  400. skinned.push(new THREE.Vector3());
  401. }
  402. for ( i = 0; i < bones.length; i ++ ) {
  403. if ( bones[ i ].type != 'JOINT' ) continue;
  404. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  405. w = bones[ i ].weights[ j ];
  406. vidx = w.index;
  407. weight = w.weight;
  408. o = geometry.vertices[vidx];
  409. s = skinned[vidx];
  410. v.x = o.x;
  411. v.y = o.y;
  412. v.z = o.z;
  413. v.applyMatrix4( bones[i].skinningMatrix );
  414. s.x += (v.x * weight);
  415. s.y += (v.y * weight);
  416. s.z += (v.z * weight);
  417. }
  418. }
  419. for (var i = 0; i < geometry.vertices.length; i ++) {
  420. geometry.vertices[i] = skinned[i];
  421. }
  422. }
  423. function applySkin ( geometry, instanceCtrl, frame ) {
  424. var skinController = controllers[ instanceCtrl.url ];
  425. frame = frame !== undefined ? frame : 40;
  426. if ( !skinController || !skinController.skin ) {
  427. console.log( 'ColladaLoader: Could not find skin controller.' );
  428. return;
  429. }
  430. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  431. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  432. return;
  433. }
  434. var animationBounds = calcAnimationBounds();
  435. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  436. //flatten the skeleton into a list of bones
  437. var bonelist = flattenSkeleton(skeleton);
  438. var joints = skinController.skin.joints;
  439. //sort that list so that the order reflects the order in the joint list
  440. var sortedbones = [];
  441. for (var i = 0; i < joints.length; i ++) {
  442. for (var j = 0; j < bonelist.length; j ++) {
  443. if (bonelist[j].name === joints[i]) {
  444. sortedbones[i] = bonelist[j];
  445. }
  446. }
  447. }
  448. //hook up the parents by index instead of name
  449. for (var i = 0; i < sortedbones.length; i ++) {
  450. for (var j = 0; j < sortedbones.length; j ++) {
  451. if (sortedbones[i].parent === sortedbones[j].name) {
  452. sortedbones[i].parent = j;
  453. }
  454. }
  455. }
  456. var i, j, w, vidx, weight;
  457. var v = new THREE.Vector3(), o, s;
  458. // move vertices to bind shape
  459. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  460. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  461. }
  462. var skinIndices = [];
  463. var skinWeights = [];
  464. var weights = skinController.skin.weights;
  465. // hook up the skin weights
  466. // TODO - this might be a good place to choose greatest 4 weights
  467. for ( var i =0; i < weights.length; i ++ ) {
  468. var indicies = new THREE.Vector4(weights[i][0] ? weights[i][0].joint : 0,weights[i][1] ? weights[i][1].joint : 0,weights[i][2] ? weights[i][2].joint : 0,weights[i][3] ? weights[i][3].joint : 0);
  469. var weight = new THREE.Vector4(weights[i][0] ? weights[i][0].weight : 0,weights[i][1] ? weights[i][1].weight : 0,weights[i][2] ? weights[i][2].weight : 0,weights[i][3] ? weights[i][3].weight : 0);
  470. skinIndices.push(indicies);
  471. skinWeights.push(weight);
  472. }
  473. geometry.skinIndices = skinIndices;
  474. geometry.skinWeights = skinWeights;
  475. geometry.bones = sortedbones;
  476. // process animation, or simply pose the rig if no animation
  477. //create an animation for the animated bones
  478. //NOTE: this has no effect when using morphtargets
  479. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  480. for (var j = 0; j < sortedbones.length; j ++) {
  481. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  482. }
  483. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  484. skinToBindPose(geometry, skeleton, skinController);
  485. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  486. var bones = [];
  487. var skinned = [];
  488. // process the frame and setup the rig with a fresh
  489. // transform, possibly from the bone's animation channel(s)
  490. setupSkeleton( skeleton, bones, frame );
  491. setupSkinningMatrices( bones, skinController.skin );
  492. for (var i = 0; i < bones.length; i ++) {
  493. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  494. if (animationdata.hierarchy[j].name === bones[i].sid) {
  495. var key = {};
  496. key.time = (frame / 30);
  497. key.matrix = bones[i].animatrix;
  498. if (frame === 0)
  499. bones[i].matrix = key.matrix;
  500. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  501. key.matrix.decompose(data[0], data[1], data[2]);
  502. key.pos = [ data[0].x,data[0].y,data[0].z ];
  503. key.scl = [ data[2].x,data[2].y,data[2].z ];
  504. key.rot = data[1];
  505. animationdata.hierarchy[j].keys.push(key);
  506. }
  507. }
  508. }
  509. geometry.animation = animationdata;
  510. }
  511. };
  512. function createKinematics() {
  513. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  514. kinematics = undefined;
  515. return;
  516. }
  517. var jointMap = {};
  518. var _addToMap = function( jointIndex, parentVisualElement ) {
  519. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  520. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  521. var joint = kinematicsModel.joints[ jointIndex ];
  522. scene.traverse(function( node ) {
  523. if ( node.colladaId == parentVisualElementId ) {
  524. jointMap[ jointIndex ] = {
  525. node: node,
  526. transforms: colladaNode.transforms,
  527. joint: joint,
  528. position: joint.zeroPosition
  529. };
  530. }
  531. });
  532. };
  533. kinematics = {
  534. joints: kinematicsModel && kinematicsModel.joints,
  535. getJointValue: function( jointIndex ) {
  536. var jointData = jointMap[ jointIndex ];
  537. if ( jointData ) {
  538. return jointData.position;
  539. } else {
  540. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  541. }
  542. },
  543. setJointValue: function( jointIndex, value ) {
  544. var jointData = jointMap[ jointIndex ];
  545. if ( jointData ) {
  546. var joint = jointData.joint;
  547. if ( value > joint.limits.max || value < joint.limits.min ) {
  548. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  549. } else if ( joint.static ) {
  550. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  551. } else {
  552. var threejsNode = jointData.node;
  553. var axis = joint.axis;
  554. var transforms = jointData.transforms;
  555. var matrix = new THREE.Matrix4();
  556. for (i = 0; i < transforms.length; i ++ ) {
  557. var transform = transforms[ i ];
  558. // kinda ghetto joint detection
  559. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  560. // apply actual joint value here
  561. switch ( joint.type ) {
  562. case 'revolute':
  563. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  564. break;
  565. case 'prismatic':
  566. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  567. break;
  568. default:
  569. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  570. break;
  571. }
  572. } else {
  573. var m1 = new THREE.Matrix4();
  574. switch ( transform.type ) {
  575. case 'matrix':
  576. matrix.multiply( transform.obj );
  577. break;
  578. case 'translate':
  579. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  580. break;
  581. case 'rotate':
  582. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  583. break;
  584. }
  585. }
  586. }
  587. // apply the matrix to the threejs node
  588. var elementsFloat32Arr = matrix.elements;
  589. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  590. var elementsRowMajor = [
  591. elements[ 0 ],
  592. elements[ 4 ],
  593. elements[ 8 ],
  594. elements[ 12 ],
  595. elements[ 1 ],
  596. elements[ 5 ],
  597. elements[ 9 ],
  598. elements[ 13 ],
  599. elements[ 2 ],
  600. elements[ 6 ],
  601. elements[ 10 ],
  602. elements[ 14 ],
  603. elements[ 3 ],
  604. elements[ 7 ],
  605. elements[ 11 ],
  606. elements[ 15 ]
  607. ];
  608. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  609. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  610. }
  611. } else {
  612. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  613. }
  614. }
  615. };
  616. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  617. if ( element ) {
  618. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  619. var child = element.childNodes[ i ];
  620. if ( child.nodeType != 1 ) continue;
  621. switch ( child.nodeName ) {
  622. case 'bind_joint_axis':
  623. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  624. var axis = child.querySelector('axis param').textContent;
  625. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  626. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  627. if ( visualTargetElement ) {
  628. var parentVisualElement = visualTargetElement.parentElement;
  629. _addToMap(jointIndex, parentVisualElement);
  630. }
  631. break;
  632. default:
  633. break;
  634. }
  635. }
  636. }
  637. };
  638. function createSceneGraph ( node, parent ) {
  639. var obj = new THREE.Object3D();
  640. var skinned = false;
  641. var skinController;
  642. var morphController;
  643. var i, j;
  644. // FIXME: controllers
  645. for ( i = 0; i < node.controllers.length; i ++ ) {
  646. var controller = controllers[ node.controllers[ i ].url ];
  647. switch ( controller.type ) {
  648. case 'skin':
  649. if ( geometries[ controller.skin.source ] ) {
  650. var inst_geom = new InstanceGeometry();
  651. inst_geom.url = controller.skin.source;
  652. inst_geom.instance_material = node.controllers[ i ].instance_material;
  653. node.geometries.push( inst_geom );
  654. skinned = true;
  655. skinController = node.controllers[ i ];
  656. } else if ( controllers[ controller.skin.source ] ) {
  657. // urgh: controller can be chained
  658. // handle the most basic case...
  659. var second = controllers[ controller.skin.source ];
  660. morphController = second;
  661. // skinController = node.controllers[i];
  662. if ( second.morph && geometries[ second.morph.source ] ) {
  663. var inst_geom = new InstanceGeometry();
  664. inst_geom.url = second.morph.source;
  665. inst_geom.instance_material = node.controllers[ i ].instance_material;
  666. node.geometries.push( inst_geom );
  667. }
  668. }
  669. break;
  670. case 'morph':
  671. if ( geometries[ controller.morph.source ] ) {
  672. var inst_geom = new InstanceGeometry();
  673. inst_geom.url = controller.morph.source;
  674. inst_geom.instance_material = node.controllers[ i ].instance_material;
  675. node.geometries.push( inst_geom );
  676. morphController = node.controllers[ i ];
  677. }
  678. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  679. default:
  680. break;
  681. }
  682. }
  683. // geometries
  684. var double_sided_materials = {};
  685. for ( i = 0; i < node.geometries.length; i ++ ) {
  686. var instance_geometry = node.geometries[i];
  687. var instance_materials = instance_geometry.instance_material;
  688. var geometry = geometries[ instance_geometry.url ];
  689. var used_materials = {};
  690. var used_materials_array = [];
  691. var num_materials = 0;
  692. var first_material;
  693. if ( geometry ) {
  694. if ( !geometry.mesh || !geometry.mesh.primitives )
  695. continue;
  696. if ( obj.name.length === 0 ) {
  697. obj.name = geometry.id;
  698. }
  699. // collect used fx for this geometry-instance
  700. if ( instance_materials ) {
  701. for ( j = 0; j < instance_materials.length; j ++ ) {
  702. var instance_material = instance_materials[ j ];
  703. var mat = materials[ instance_material.target ];
  704. var effect_id = mat.instance_effect.url;
  705. var shader = effects[ effect_id ].shader;
  706. var material3js = shader.material;
  707. if ( geometry.doubleSided ) {
  708. if ( !( instance_material.symbol in double_sided_materials ) ) {
  709. var _copied_material = material3js.clone();
  710. _copied_material.side = THREE.DoubleSide;
  711. double_sided_materials[ instance_material.symbol ] = _copied_material;
  712. }
  713. material3js = double_sided_materials[ instance_material.symbol ];
  714. }
  715. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  716. used_materials[ instance_material.symbol ] = num_materials;
  717. used_materials_array.push( material3js );
  718. first_material = material3js;
  719. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  720. num_materials ++;
  721. }
  722. }
  723. var mesh;
  724. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  725. var geom = geometry.mesh.geometry3js;
  726. if ( num_materials > 1 ) {
  727. material = new THREE.MeshFaceMaterial( used_materials_array );
  728. for ( j = 0; j < geom.faces.length; j ++ ) {
  729. var face = geom.faces[ j ];
  730. face.materialIndex = used_materials[ face.daeMaterial ]
  731. }
  732. }
  733. if ( skinController !== undefined ) {
  734. applySkin( geom, skinController );
  735. if ( geom.morphTargets.length > 0 ) {
  736. material.morphTargets = true;
  737. material.skinning = false;
  738. } else {
  739. material.morphTargets = false;
  740. material.skinning = true;
  741. }
  742. mesh = new THREE.SkinnedMesh( geom, material, false );
  743. //mesh.skeleton = skinController.skeleton;
  744. //mesh.skinController = controllers[ skinController.url ];
  745. //mesh.skinInstanceController = skinController;
  746. mesh.name = 'skin_' + skins.length;
  747. //mesh.animationHandle.setKey(0);
  748. skins.push( mesh );
  749. } else if ( morphController !== undefined ) {
  750. createMorph( geom, morphController );
  751. material.morphTargets = true;
  752. mesh = new THREE.Mesh( geom, material );
  753. mesh.name = 'morph_' + morphs.length;
  754. morphs.push( mesh );
  755. } else {
  756. if ( geom.isLineStrip === true ) {
  757. mesh = new THREE.Line( geom );
  758. } else {
  759. mesh = new THREE.Mesh( geom, material );
  760. }
  761. }
  762. obj.add(mesh);
  763. }
  764. }
  765. for ( i = 0; i < node.cameras.length; i ++ ) {
  766. var instance_camera = node.cameras[i];
  767. var cparams = cameras[instance_camera.url];
  768. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  769. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  770. obj.add(cam);
  771. }
  772. for ( i = 0; i < node.lights.length; i ++ ) {
  773. var light = null;
  774. var instance_light = node.lights[i];
  775. var lparams = lights[instance_light.url];
  776. if ( lparams && lparams.technique ) {
  777. var color = lparams.color.getHex();
  778. var intensity = lparams.intensity;
  779. var distance = lparams.distance;
  780. var angle = lparams.falloff_angle;
  781. var exponent; // Intentionally undefined, don't know what this is yet
  782. switch ( lparams.technique ) {
  783. case 'directional':
  784. light = new THREE.DirectionalLight( color, intensity, distance );
  785. light.position.set(0, 0, 1);
  786. break;
  787. case 'point':
  788. light = new THREE.PointLight( color, intensity, distance );
  789. break;
  790. case 'spot':
  791. light = new THREE.SpotLight( color, intensity, distance, angle, exponent );
  792. light.position.set(0, 0, 1);
  793. break;
  794. case 'ambient':
  795. light = new THREE.AmbientLight( color );
  796. break;
  797. }
  798. }
  799. if (light) {
  800. obj.add(light);
  801. }
  802. }
  803. obj.name = node.name || node.id || "";
  804. obj.colladaId = node.id || "";
  805. obj.layer = node.layer || "";
  806. obj.matrix = node.matrix;
  807. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  808. if ( options.centerGeometry && obj.geometry ) {
  809. var delta = obj.geometry.center();
  810. delta.multiply( obj.scale );
  811. delta.applyQuaternion( obj.quaternion );
  812. obj.position.sub( delta );
  813. }
  814. for ( i = 0; i < node.nodes.length; i ++ ) {
  815. obj.add( createSceneGraph( node.nodes[i], node ) );
  816. }
  817. return obj;
  818. };
  819. function getJointId( skin, id ) {
  820. for ( var i = 0; i < skin.joints.length; i ++ ) {
  821. if ( skin.joints[ i ] === id ) {
  822. return i;
  823. }
  824. }
  825. };
  826. function getLibraryNode( id ) {
  827. var nodes = COLLADA.querySelectorAll('library_nodes node');
  828. for ( var i = 0; i < nodes.length; i++ ) {
  829. var attObj = nodes[i].attributes.getNamedItem('id');
  830. if ( attObj && attObj.value === id ) {
  831. return nodes[i];
  832. }
  833. }
  834. return undefined;
  835. };
  836. function getChannelsForNode ( node ) {
  837. var channels = [];
  838. var startTime = 1000000;
  839. var endTime = -1000000;
  840. for ( var id in animations ) {
  841. var animation = animations[id];
  842. for ( var i = 0; i < animation.channel.length; i ++ ) {
  843. var channel = animation.channel[i];
  844. var sampler = animation.sampler[i];
  845. var id = channel.target.split('/')[0];
  846. if ( id == node.id ) {
  847. sampler.create();
  848. channel.sampler = sampler;
  849. startTime = Math.min(startTime, sampler.startTime);
  850. endTime = Math.max(endTime, sampler.endTime);
  851. channels.push(channel);
  852. }
  853. }
  854. }
  855. if ( channels.length ) {
  856. node.startTime = startTime;
  857. node.endTime = endTime;
  858. }
  859. return channels;
  860. };
  861. function calcFrameDuration( node ) {
  862. var minT = 10000000;
  863. for ( var i = 0; i < node.channels.length; i ++ ) {
  864. var sampler = node.channels[i].sampler;
  865. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  866. var t0 = sampler.input[ j ];
  867. var t1 = sampler.input[ j + 1 ];
  868. minT = Math.min( minT, t1 - t0 );
  869. }
  870. }
  871. return minT;
  872. };
  873. function calcMatrixAt( node, t ) {
  874. var animated = {};
  875. var i, j;
  876. for ( i = 0; i < node.channels.length; i ++ ) {
  877. var channel = node.channels[ i ];
  878. animated[ channel.sid ] = channel;
  879. }
  880. var matrix = new THREE.Matrix4();
  881. for ( i = 0; i < node.transforms.length; i ++ ) {
  882. var transform = node.transforms[ i ];
  883. var channel = animated[ transform.sid ];
  884. if ( channel !== undefined ) {
  885. var sampler = channel.sampler;
  886. var value;
  887. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  888. if ( sampler.input[ j + 1 ] > t ) {
  889. value = sampler.output[ j ];
  890. //console.log(value.flatten)
  891. break;
  892. }
  893. }
  894. if ( value !== undefined ) {
  895. if ( value instanceof THREE.Matrix4 ) {
  896. matrix.multiplyMatrices( matrix, value );
  897. } else {
  898. // FIXME: handle other types
  899. matrix.multiplyMatrices( matrix, transform.matrix );
  900. }
  901. } else {
  902. matrix.multiplyMatrices( matrix, transform.matrix );
  903. }
  904. } else {
  905. matrix.multiplyMatrices( matrix, transform.matrix );
  906. }
  907. }
  908. return matrix;
  909. };
  910. function bakeAnimations ( node ) {
  911. if ( node.channels && node.channels.length ) {
  912. var keys = [],
  913. sids = [];
  914. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  915. var channel = node.channels[i],
  916. fullSid = channel.fullSid,
  917. sampler = channel.sampler,
  918. input = sampler.input,
  919. transform = node.getTransformBySid( channel.sid ),
  920. member;
  921. if ( channel.arrIndices ) {
  922. member = [];
  923. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  924. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  925. }
  926. } else {
  927. member = getConvertedMember( channel.member );
  928. }
  929. if ( transform ) {
  930. if ( sids.indexOf( fullSid ) === -1 ) {
  931. sids.push( fullSid );
  932. }
  933. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  934. var time = input[j],
  935. data = sampler.getData( transform.type, j, member ),
  936. key = findKey( keys, time );
  937. if ( !key ) {
  938. key = new Key( time );
  939. var timeNdx = findTimeNdx( keys, time );
  940. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  941. }
  942. key.addTarget( fullSid, transform, member, data );
  943. }
  944. } else {
  945. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  946. }
  947. }
  948. // post process
  949. for ( var i = 0; i < sids.length; i ++ ) {
  950. var sid = sids[ i ];
  951. for ( var j = 0; j < keys.length; j ++ ) {
  952. var key = keys[ j ];
  953. if ( !key.hasTarget( sid ) ) {
  954. interpolateKeys( keys, key, j, sid );
  955. }
  956. }
  957. }
  958. node.keys = keys;
  959. node.sids = sids;
  960. }
  961. };
  962. function findKey ( keys, time) {
  963. var retVal = null;
  964. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  965. var key = keys[i];
  966. if ( key.time === time ) {
  967. retVal = key;
  968. } else if ( key.time > time ) {
  969. break;
  970. }
  971. }
  972. return retVal;
  973. };
  974. function findTimeNdx ( keys, time) {
  975. var ndx = -1;
  976. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  977. var key = keys[i];
  978. if ( key.time >= time ) {
  979. ndx = i;
  980. }
  981. }
  982. return ndx;
  983. };
  984. function interpolateKeys ( keys, key, ndx, fullSid ) {
  985. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  986. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  987. if ( prevKey && nextKey ) {
  988. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  989. prevTarget = prevKey.getTarget( fullSid ),
  990. nextData = nextKey.getTarget( fullSid ).data,
  991. prevData = prevTarget.data,
  992. data;
  993. if ( prevTarget.type === 'matrix' ) {
  994. data = prevData;
  995. } else if ( prevData.length ) {
  996. data = [];
  997. for ( var i = 0; i < prevData.length; ++ i ) {
  998. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  999. }
  1000. } else {
  1001. data = prevData + ( nextData - prevData ) * scale;
  1002. }
  1003. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  1004. }
  1005. };
  1006. // Get next key with given sid
  1007. function getNextKeyWith( keys, fullSid, ndx ) {
  1008. for ( ; ndx < keys.length; ndx ++ ) {
  1009. var key = keys[ ndx ];
  1010. if ( key.hasTarget( fullSid ) ) {
  1011. return key;
  1012. }
  1013. }
  1014. return null;
  1015. };
  1016. // Get previous key with given sid
  1017. function getPrevKeyWith( keys, fullSid, ndx ) {
  1018. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  1019. for ( ; ndx >= 0; ndx -- ) {
  1020. var key = keys[ ndx ];
  1021. if ( key.hasTarget( fullSid ) ) {
  1022. return key;
  1023. }
  1024. }
  1025. return null;
  1026. };
  1027. function _Image() {
  1028. this.id = "";
  1029. this.init_from = "";
  1030. };
  1031. _Image.prototype.parse = function(element) {
  1032. this.id = element.getAttribute('id');
  1033. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1034. var child = element.childNodes[ i ];
  1035. if ( child.nodeName === 'init_from' ) {
  1036. this.init_from = child.textContent;
  1037. }
  1038. }
  1039. return this;
  1040. };
  1041. function Controller() {
  1042. this.id = "";
  1043. this.name = "";
  1044. this.type = "";
  1045. this.skin = null;
  1046. this.morph = null;
  1047. };
  1048. Controller.prototype.parse = function( element ) {
  1049. this.id = element.getAttribute('id');
  1050. this.name = element.getAttribute('name');
  1051. this.type = "none";
  1052. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1053. var child = element.childNodes[ i ];
  1054. switch ( child.nodeName ) {
  1055. case 'skin':
  1056. this.skin = (new Skin()).parse(child);
  1057. this.type = child.nodeName;
  1058. break;
  1059. case 'morph':
  1060. this.morph = (new Morph()).parse(child);
  1061. this.type = child.nodeName;
  1062. break;
  1063. default:
  1064. break;
  1065. }
  1066. }
  1067. return this;
  1068. };
  1069. function Morph() {
  1070. this.method = null;
  1071. this.source = null;
  1072. this.targets = null;
  1073. this.weights = null;
  1074. };
  1075. Morph.prototype.parse = function( element ) {
  1076. var sources = {};
  1077. var inputs = [];
  1078. var i;
  1079. this.method = element.getAttribute( 'method' );
  1080. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1081. for ( i = 0; i < element.childNodes.length; i ++ ) {
  1082. var child = element.childNodes[ i ];
  1083. if ( child.nodeType != 1 ) continue;
  1084. switch ( child.nodeName ) {
  1085. case 'source':
  1086. var source = ( new Source() ).parse( child );
  1087. sources[ source.id ] = source;
  1088. break;
  1089. case 'targets':
  1090. inputs = this.parseInputs( child );
  1091. break;
  1092. default:
  1093. console.log( child.nodeName );
  1094. break;
  1095. }
  1096. }
  1097. for ( i = 0; i < inputs.length; i ++ ) {
  1098. var input = inputs[ i ];
  1099. var source = sources[ input.source ];
  1100. switch ( input.semantic ) {
  1101. case 'MORPH_TARGET':
  1102. this.targets = source.read();
  1103. break;
  1104. case 'MORPH_WEIGHT':
  1105. this.weights = source.read();
  1106. break;
  1107. default:
  1108. break;
  1109. }
  1110. }
  1111. return this;
  1112. };
  1113. Morph.prototype.parseInputs = function(element) {
  1114. var inputs = [];
  1115. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1116. var child = element.childNodes[i];
  1117. if ( child.nodeType != 1) continue;
  1118. switch ( child.nodeName ) {
  1119. case 'input':
  1120. inputs.push( (new Input()).parse(child) );
  1121. break;
  1122. default:
  1123. break;
  1124. }
  1125. }
  1126. return inputs;
  1127. };
  1128. function Skin() {
  1129. this.source = "";
  1130. this.bindShapeMatrix = null;
  1131. this.invBindMatrices = [];
  1132. this.joints = [];
  1133. this.weights = [];
  1134. };
  1135. Skin.prototype.parse = function( element ) {
  1136. var sources = {};
  1137. var joints, weights;
  1138. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1139. this.invBindMatrices = [];
  1140. this.joints = [];
  1141. this.weights = [];
  1142. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1143. var child = element.childNodes[i];
  1144. if ( child.nodeType != 1 ) continue;
  1145. switch ( child.nodeName ) {
  1146. case 'bind_shape_matrix':
  1147. var f = _floats(child.textContent);
  1148. this.bindShapeMatrix = getConvertedMat4( f );
  1149. break;
  1150. case 'source':
  1151. var src = new Source().parse(child);
  1152. sources[ src.id ] = src;
  1153. break;
  1154. case 'joints':
  1155. joints = child;
  1156. break;
  1157. case 'vertex_weights':
  1158. weights = child;
  1159. break;
  1160. default:
  1161. console.log( child.nodeName );
  1162. break;
  1163. }
  1164. }
  1165. this.parseJoints( joints, sources );
  1166. this.parseWeights( weights, sources );
  1167. return this;
  1168. };
  1169. Skin.prototype.parseJoints = function ( element, sources ) {
  1170. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1171. var child = element.childNodes[ i ];
  1172. if ( child.nodeType != 1 ) continue;
  1173. switch ( child.nodeName ) {
  1174. case 'input':
  1175. var input = ( new Input() ).parse( child );
  1176. var source = sources[ input.source ];
  1177. if ( input.semantic === 'JOINT' ) {
  1178. this.joints = source.read();
  1179. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  1180. this.invBindMatrices = source.read();
  1181. }
  1182. break;
  1183. default:
  1184. break;
  1185. }
  1186. }
  1187. };
  1188. Skin.prototype.parseWeights = function ( element, sources ) {
  1189. var v, vcount, inputs = [];
  1190. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1191. var child = element.childNodes[ i ];
  1192. if ( child.nodeType != 1 ) continue;
  1193. switch ( child.nodeName ) {
  1194. case 'input':
  1195. inputs.push( ( new Input() ).parse( child ) );
  1196. break;
  1197. case 'v':
  1198. v = _ints( child.textContent );
  1199. break;
  1200. case 'vcount':
  1201. vcount = _ints( child.textContent );
  1202. break;
  1203. default:
  1204. break;
  1205. }
  1206. }
  1207. var index = 0;
  1208. for ( var i = 0; i < vcount.length; i ++ ) {
  1209. var numBones = vcount[i];
  1210. var vertex_weights = [];
  1211. for ( var j = 0; j < numBones; j ++ ) {
  1212. var influence = {};
  1213. for ( var k = 0; k < inputs.length; k ++ ) {
  1214. var input = inputs[ k ];
  1215. var value = v[ index + input.offset ];
  1216. switch ( input.semantic ) {
  1217. case 'JOINT':
  1218. influence.joint = value;//this.joints[value];
  1219. break;
  1220. case 'WEIGHT':
  1221. influence.weight = sources[ input.source ].data[ value ];
  1222. break;
  1223. default:
  1224. break;
  1225. }
  1226. }
  1227. vertex_weights.push( influence );
  1228. index += inputs.length;
  1229. }
  1230. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  1231. vertex_weights[ j ].index = i;
  1232. }
  1233. this.weights.push( vertex_weights );
  1234. }
  1235. };
  1236. function VisualScene () {
  1237. this.id = "";
  1238. this.name = "";
  1239. this.nodes = [];
  1240. this.scene = new THREE.Group();
  1241. };
  1242. VisualScene.prototype.getChildById = function( id, recursive ) {
  1243. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1244. var node = this.nodes[ i ].getChildById( id, recursive );
  1245. if ( node ) {
  1246. return node;
  1247. }
  1248. }
  1249. return null;
  1250. };
  1251. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  1252. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1253. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  1254. if ( node ) {
  1255. return node;
  1256. }
  1257. }
  1258. return null;
  1259. };
  1260. VisualScene.prototype.parse = function( element ) {
  1261. this.id = element.getAttribute( 'id' );
  1262. this.name = element.getAttribute( 'name' );
  1263. this.nodes = [];
  1264. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1265. var child = element.childNodes[ i ];
  1266. if ( child.nodeType != 1 ) continue;
  1267. switch ( child.nodeName ) {
  1268. case 'node':
  1269. this.nodes.push( ( new Node() ).parse( child ) );
  1270. break;
  1271. default:
  1272. break;
  1273. }
  1274. }
  1275. return this;
  1276. };
  1277. function Node() {
  1278. this.id = "";
  1279. this.name = "";
  1280. this.sid = "";
  1281. this.nodes = [];
  1282. this.controllers = [];
  1283. this.transforms = [];
  1284. this.geometries = [];
  1285. this.channels = [];
  1286. this.matrix = new THREE.Matrix4();
  1287. };
  1288. Node.prototype.getChannelForTransform = function( transformSid ) {
  1289. for ( var i = 0; i < this.channels.length; i ++ ) {
  1290. var channel = this.channels[i];
  1291. var parts = channel.target.split('/');
  1292. var id = parts.shift();
  1293. var sid = parts.shift();
  1294. var dotSyntax = (sid.indexOf(".") >= 0);
  1295. var arrSyntax = (sid.indexOf("(") >= 0);
  1296. var arrIndices;
  1297. var member;
  1298. if ( dotSyntax ) {
  1299. parts = sid.split(".");
  1300. sid = parts.shift();
  1301. member = parts.shift();
  1302. } else if ( arrSyntax ) {
  1303. arrIndices = sid.split("(");
  1304. sid = arrIndices.shift();
  1305. for ( var j = 0; j < arrIndices.length; j ++ ) {
  1306. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  1307. }
  1308. }
  1309. if ( sid === transformSid ) {
  1310. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  1311. return channel;
  1312. }
  1313. }
  1314. return null;
  1315. };
  1316. Node.prototype.getChildById = function ( id, recursive ) {
  1317. if ( this.id === id ) {
  1318. return this;
  1319. }
  1320. if ( recursive ) {
  1321. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1322. var n = this.nodes[ i ].getChildById( id, recursive );
  1323. if ( n ) {
  1324. return n;
  1325. }
  1326. }
  1327. }
  1328. return null;
  1329. };
  1330. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1331. if ( this.sid === sid ) {
  1332. return this;
  1333. }
  1334. if ( recursive ) {
  1335. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1336. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1337. if ( n ) {
  1338. return n;
  1339. }
  1340. }
  1341. }
  1342. return null;
  1343. };
  1344. Node.prototype.getTransformBySid = function ( sid ) {
  1345. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1346. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  1347. }
  1348. return null;
  1349. };
  1350. Node.prototype.parse = function( element ) {
  1351. var url;
  1352. this.id = element.getAttribute('id');
  1353. this.sid = element.getAttribute('sid');
  1354. this.name = element.getAttribute('name');
  1355. this.type = element.getAttribute('type');
  1356. this.layer = element.getAttribute('layer');
  1357. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  1358. this.nodes = [];
  1359. this.transforms = [];
  1360. this.geometries = [];
  1361. this.cameras = [];
  1362. this.lights = [];
  1363. this.controllers = [];
  1364. this.matrix = new THREE.Matrix4();
  1365. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1366. var child = element.childNodes[ i ];
  1367. if ( child.nodeType != 1 ) continue;
  1368. switch ( child.nodeName ) {
  1369. case 'node':
  1370. this.nodes.push( ( new Node() ).parse( child ) );
  1371. break;
  1372. case 'instance_camera':
  1373. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1374. break;
  1375. case 'instance_controller':
  1376. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1377. break;
  1378. case 'instance_geometry':
  1379. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1380. break;
  1381. case 'instance_light':
  1382. this.lights.push( ( new InstanceLight() ).parse( child ) );
  1383. break;
  1384. case 'instance_node':
  1385. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1386. var iNode = getLibraryNode( url );
  1387. if ( iNode ) {
  1388. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1389. }
  1390. break;
  1391. case 'rotate':
  1392. case 'translate':
  1393. case 'scale':
  1394. case 'matrix':
  1395. case 'lookat':
  1396. case 'skew':
  1397. this.transforms.push( ( new Transform() ).parse( child ) );
  1398. break;
  1399. case 'extra':
  1400. break;
  1401. default:
  1402. console.log( child.nodeName );
  1403. break;
  1404. }
  1405. }
  1406. this.channels = getChannelsForNode( this );
  1407. bakeAnimations( this );
  1408. this.updateMatrix();
  1409. return this;
  1410. };
  1411. Node.prototype.updateMatrix = function () {
  1412. this.matrix.identity();
  1413. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1414. this.transforms[ i ].apply( this.matrix );
  1415. }
  1416. };
  1417. function Transform () {
  1418. this.sid = "";
  1419. this.type = "";
  1420. this.data = [];
  1421. this.obj = null;
  1422. };
  1423. Transform.prototype.parse = function ( element ) {
  1424. this.sid = element.getAttribute( 'sid' );
  1425. this.type = element.nodeName;
  1426. this.data = _floats( element.textContent );
  1427. this.convert();
  1428. return this;
  1429. };
  1430. Transform.prototype.convert = function () {
  1431. switch ( this.type ) {
  1432. case 'matrix':
  1433. this.obj = getConvertedMat4( this.data );
  1434. break;
  1435. case 'rotate':
  1436. this.angle = THREE.Math.degToRad( this.data[3] );
  1437. case 'translate':
  1438. fixCoords( this.data, -1 );
  1439. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1440. break;
  1441. case 'scale':
  1442. fixCoords( this.data, 1 );
  1443. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1444. break;
  1445. default:
  1446. console.log( 'Can not convert Transform of type ' + this.type );
  1447. break;
  1448. }
  1449. };
  1450. Transform.prototype.apply = function () {
  1451. var m1 = new THREE.Matrix4();
  1452. return function ( matrix ) {
  1453. switch ( this.type ) {
  1454. case 'matrix':
  1455. matrix.multiply( this.obj );
  1456. break;
  1457. case 'translate':
  1458. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  1459. break;
  1460. case 'rotate':
  1461. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  1462. break;
  1463. case 'scale':
  1464. matrix.scale( this.obj );
  1465. break;
  1466. }
  1467. };
  1468. }();
  1469. Transform.prototype.update = function ( data, member ) {
  1470. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1471. switch ( this.type ) {
  1472. case 'matrix':
  1473. if ( ! member ) {
  1474. this.obj.copy( data );
  1475. } else if ( member.length === 1 ) {
  1476. switch ( member[ 0 ] ) {
  1477. case 0:
  1478. this.obj.n11 = data[ 0 ];
  1479. this.obj.n21 = data[ 1 ];
  1480. this.obj.n31 = data[ 2 ];
  1481. this.obj.n41 = data[ 3 ];
  1482. break;
  1483. case 1:
  1484. this.obj.n12 = data[ 0 ];
  1485. this.obj.n22 = data[ 1 ];
  1486. this.obj.n32 = data[ 2 ];
  1487. this.obj.n42 = data[ 3 ];
  1488. break;
  1489. case 2:
  1490. this.obj.n13 = data[ 0 ];
  1491. this.obj.n23 = data[ 1 ];
  1492. this.obj.n33 = data[ 2 ];
  1493. this.obj.n43 = data[ 3 ];
  1494. break;
  1495. case 3:
  1496. this.obj.n14 = data[ 0 ];
  1497. this.obj.n24 = data[ 1 ];
  1498. this.obj.n34 = data[ 2 ];
  1499. this.obj.n44 = data[ 3 ];
  1500. break;
  1501. }
  1502. } else if ( member.length === 2 ) {
  1503. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1504. this.obj[ propName ] = data;
  1505. } else {
  1506. console.log('Incorrect addressing of matrix in transform.');
  1507. }
  1508. break;
  1509. case 'translate':
  1510. case 'scale':
  1511. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1512. member = members[ member[ 0 ] ];
  1513. }
  1514. switch ( member ) {
  1515. case 'X':
  1516. this.obj.x = data;
  1517. break;
  1518. case 'Y':
  1519. this.obj.y = data;
  1520. break;
  1521. case 'Z':
  1522. this.obj.z = data;
  1523. break;
  1524. default:
  1525. this.obj.x = data[ 0 ];
  1526. this.obj.y = data[ 1 ];
  1527. this.obj.z = data[ 2 ];
  1528. break;
  1529. }
  1530. break;
  1531. case 'rotate':
  1532. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1533. member = members[ member[ 0 ] ];
  1534. }
  1535. switch ( member ) {
  1536. case 'X':
  1537. this.obj.x = data;
  1538. break;
  1539. case 'Y':
  1540. this.obj.y = data;
  1541. break;
  1542. case 'Z':
  1543. this.obj.z = data;
  1544. break;
  1545. case 'ANGLE':
  1546. this.angle = THREE.Math.degToRad( data );
  1547. break;
  1548. default:
  1549. this.obj.x = data[ 0 ];
  1550. this.obj.y = data[ 1 ];
  1551. this.obj.z = data[ 2 ];
  1552. this.angle = THREE.Math.degToRad( data[ 3 ] );
  1553. break;
  1554. }
  1555. break;
  1556. }
  1557. };
  1558. function InstanceController() {
  1559. this.url = "";
  1560. this.skeleton = [];
  1561. this.instance_material = [];
  1562. };
  1563. InstanceController.prototype.parse = function ( element ) {
  1564. this.url = element.getAttribute('url').replace(/^#/, '');
  1565. this.skeleton = [];
  1566. this.instance_material = [];
  1567. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1568. var child = element.childNodes[ i ];
  1569. if ( child.nodeType !== 1 ) continue;
  1570. switch ( child.nodeName ) {
  1571. case 'skeleton':
  1572. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1573. break;
  1574. case 'bind_material':
  1575. var instances = child.querySelectorAll('instance_material');
  1576. for ( var j = 0; j < instances.length; j ++ ) {
  1577. var instance = instances[j];
  1578. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1579. }
  1580. break;
  1581. case 'extra':
  1582. break;
  1583. default:
  1584. break;
  1585. }
  1586. }
  1587. return this;
  1588. };
  1589. function InstanceMaterial () {
  1590. this.symbol = "";
  1591. this.target = "";
  1592. };
  1593. InstanceMaterial.prototype.parse = function ( element ) {
  1594. this.symbol = element.getAttribute('symbol');
  1595. this.target = element.getAttribute('target').replace(/^#/, '');
  1596. return this;
  1597. };
  1598. function InstanceGeometry() {
  1599. this.url = "";
  1600. this.instance_material = [];
  1601. };
  1602. InstanceGeometry.prototype.parse = function ( element ) {
  1603. this.url = element.getAttribute('url').replace(/^#/, '');
  1604. this.instance_material = [];
  1605. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1606. var child = element.childNodes[i];
  1607. if ( child.nodeType != 1 ) continue;
  1608. if ( child.nodeName === 'bind_material' ) {
  1609. var instances = child.querySelectorAll('instance_material');
  1610. for ( var j = 0; j < instances.length; j ++ ) {
  1611. var instance = instances[j];
  1612. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1613. }
  1614. break;
  1615. }
  1616. }
  1617. return this;
  1618. };
  1619. function Geometry() {
  1620. this.id = "";
  1621. this.mesh = null;
  1622. };
  1623. Geometry.prototype.parse = function ( element ) {
  1624. this.id = element.getAttribute('id');
  1625. extractDoubleSided( this, element );
  1626. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1627. var child = element.childNodes[i];
  1628. switch ( child.nodeName ) {
  1629. case 'mesh':
  1630. this.mesh = (new Mesh(this)).parse(child);
  1631. break;
  1632. case 'extra':
  1633. // console.log( child );
  1634. break;
  1635. default:
  1636. break;
  1637. }
  1638. }
  1639. return this;
  1640. };
  1641. function Mesh( geometry ) {
  1642. this.geometry = geometry.id;
  1643. this.primitives = [];
  1644. this.vertices = null;
  1645. this.geometry3js = null;
  1646. };
  1647. Mesh.prototype.parse = function ( element ) {
  1648. this.primitives = [];
  1649. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1650. var child = element.childNodes[ i ];
  1651. switch ( child.nodeName ) {
  1652. case 'source':
  1653. _source( child );
  1654. break;
  1655. case 'vertices':
  1656. this.vertices = ( new Vertices() ).parse( child );
  1657. break;
  1658. case 'linestrips':
  1659. this.primitives.push( ( new LineStrips().parse( child ) ) );
  1660. break;
  1661. case 'triangles':
  1662. this.primitives.push( ( new Triangles().parse( child ) ) );
  1663. break;
  1664. case 'polygons':
  1665. this.primitives.push( ( new Polygons().parse( child ) ) );
  1666. break;
  1667. case 'polylist':
  1668. this.primitives.push( ( new Polylist().parse( child ) ) );
  1669. break;
  1670. default:
  1671. break;
  1672. }
  1673. }
  1674. this.geometry3js = new THREE.Geometry();
  1675. if ( this.vertices === null ) {
  1676. // TODO (mrdoob): Study case when this is null (carrier.dae)
  1677. return this;
  1678. }
  1679. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1680. for ( var i = 0; i < vertexData.length; i += 3 ) {
  1681. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1682. }
  1683. for ( var i = 0; i < this.primitives.length; i ++ ) {
  1684. var primitive = this.primitives[ i ];
  1685. primitive.setVertices( this.vertices );
  1686. this.handlePrimitive( primitive, this.geometry3js );
  1687. }
  1688. if ( this.geometry3js.calcNormals ) {
  1689. this.geometry3js.computeVertexNormals();
  1690. delete this.geometry3js.calcNormals;
  1691. }
  1692. return this;
  1693. };
  1694. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  1695. if ( primitive instanceof LineStrips ) {
  1696. // TODO: Handle indices. Maybe easier with BufferGeometry?
  1697. geom.isLineStrip = true;
  1698. return;
  1699. }
  1700. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1701. var input, index, idx32;
  1702. var source, numParams;
  1703. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1704. var texture_sets = [];
  1705. for ( j = 0; j < inputs.length; j ++ ) {
  1706. input = inputs[ j ];
  1707. var offset = input.offset + 1;
  1708. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  1709. switch ( input.semantic ) {
  1710. case 'TEXCOORD':
  1711. texture_sets.push( input.set );
  1712. break;
  1713. }
  1714. }
  1715. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  1716. var p = pList[ pCount ], i = 0;
  1717. while ( i < p.length ) {
  1718. var vs = [];
  1719. var ns = [];
  1720. var ts = null;
  1721. var cs = [];
  1722. if ( primitive.vcount ) {
  1723. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1724. } else {
  1725. vcount = p.length / maxOffset;
  1726. }
  1727. for ( j = 0; j < vcount; j ++ ) {
  1728. for ( k = 0; k < inputs.length; k ++ ) {
  1729. input = inputs[ k ];
  1730. source = sources[ input.source ];
  1731. index = p[ i + ( j * maxOffset ) + input.offset ];
  1732. numParams = source.accessor.params.length;
  1733. idx32 = index * numParams;
  1734. switch ( input.semantic ) {
  1735. case 'VERTEX':
  1736. vs.push( index );
  1737. break;
  1738. case 'NORMAL':
  1739. ns.push( getConvertedVec3( source.data, idx32 ) );
  1740. break;
  1741. case 'TEXCOORD':
  1742. ts = ts || { };
  1743. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1744. // invert the V
  1745. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1746. break;
  1747. case 'COLOR':
  1748. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1749. break;
  1750. default:
  1751. break;
  1752. }
  1753. }
  1754. }
  1755. if ( ns.length === 0 ) {
  1756. // check the vertices inputs
  1757. input = this.vertices.input.NORMAL;
  1758. if ( input ) {
  1759. source = sources[ input.source ];
  1760. numParams = source.accessor.params.length;
  1761. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1762. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1763. }
  1764. } else {
  1765. geom.calcNormals = true;
  1766. }
  1767. }
  1768. if ( !ts ) {
  1769. ts = { };
  1770. // check the vertices inputs
  1771. input = this.vertices.input.TEXCOORD;
  1772. if ( input ) {
  1773. texture_sets.push( input.set );
  1774. source = sources[ input.source ];
  1775. numParams = source.accessor.params.length;
  1776. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1777. idx32 = vs[ ndx ] * numParams;
  1778. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1779. // invert the V
  1780. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1781. }
  1782. }
  1783. }
  1784. if ( cs.length === 0 ) {
  1785. // check the vertices inputs
  1786. input = this.vertices.input.COLOR;
  1787. if ( input ) {
  1788. source = sources[ input.source ];
  1789. numParams = source.accessor.params.length;
  1790. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1791. idx32 = vs[ ndx ] * numParams;
  1792. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1793. }
  1794. }
  1795. }
  1796. var face = null, faces = [], uv, uvArr;
  1797. if ( vcount === 3 ) {
  1798. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1799. } else if ( vcount === 4 ) {
  1800. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], [ ns[0].clone(), ns[1].clone(), ns[3].clone() ], cs.length ? [ cs[0], cs[1], cs[3] ] : new THREE.Color() ) );
  1801. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], [ ns[1].clone(), ns[2].clone(), ns[3].clone() ], cs.length ? [ cs[1], cs[2], cs[3] ] : new THREE.Color() ) );
  1802. } else if ( vcount > 4 && options.subdivideFaces ) {
  1803. var clr = cs.length ? cs : new THREE.Color(),
  1804. vec1, vec2, vec3, v1, v2, norm;
  1805. // subdivide into multiple Face3s
  1806. for ( k = 1; k < vcount - 1; ) {
  1807. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ], clr ) );
  1808. }
  1809. }
  1810. if ( faces.length ) {
  1811. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  1812. face = faces[ndx];
  1813. face.daeMaterial = primitive.material;
  1814. geom.faces.push( face );
  1815. for ( k = 0; k < texture_sets.length; k ++ ) {
  1816. uv = ts[ texture_sets[k] ];
  1817. if ( vcount > 4 ) {
  1818. // Grab the right UVs for the vertices in this face
  1819. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  1820. } else if ( vcount === 4 ) {
  1821. if ( ndx === 0 ) {
  1822. uvArr = [ uv[0], uv[1], uv[3] ];
  1823. } else {
  1824. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  1825. }
  1826. } else {
  1827. uvArr = [ uv[0], uv[1], uv[2] ];
  1828. }
  1829. if ( geom.faceVertexUvs[k] === undefined ) {
  1830. geom.faceVertexUvs[k] = [];
  1831. }
  1832. geom.faceVertexUvs[k].push( uvArr );
  1833. }
  1834. }
  1835. } else {
  1836. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1837. }
  1838. i += maxOffset * vcount;
  1839. }
  1840. }
  1841. };
  1842. function Polygons () {
  1843. this.material = "";
  1844. this.count = 0;
  1845. this.inputs = [];
  1846. this.vcount = null;
  1847. this.p = [];
  1848. this.geometry = new THREE.Geometry();
  1849. };
  1850. Polygons.prototype.setVertices = function ( vertices ) {
  1851. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1852. if ( this.inputs[ i ].source === vertices.id ) {
  1853. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1854. }
  1855. }
  1856. };
  1857. Polygons.prototype.parse = function ( element ) {
  1858. this.material = element.getAttribute( 'material' );
  1859. this.count = _attr_as_int( element, 'count', 0 );
  1860. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1861. var child = element.childNodes[ i ];
  1862. switch ( child.nodeName ) {
  1863. case 'input':
  1864. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1865. break;
  1866. case 'vcount':
  1867. this.vcount = _ints( child.textContent );
  1868. break;
  1869. case 'p':
  1870. this.p.push( _ints( child.textContent ) );
  1871. break;
  1872. case 'ph':
  1873. console.warn( 'polygon holes not yet supported!' );
  1874. break;
  1875. default:
  1876. break;
  1877. }
  1878. }
  1879. return this;
  1880. };
  1881. function Polylist () {
  1882. Polygons.call( this );
  1883. this.vcount = [];
  1884. };
  1885. Polylist.prototype = Object.create( Polygons.prototype );
  1886. Polylist.prototype.constructor = Polylist;
  1887. function LineStrips() {
  1888. Polygons.call( this );
  1889. this.vcount = 1;
  1890. };
  1891. LineStrips.prototype = Object.create( Polygons.prototype );
  1892. LineStrips.prototype.constructor = LineStrips;
  1893. function Triangles () {
  1894. Polygons.call( this );
  1895. this.vcount = 3;
  1896. };
  1897. Triangles.prototype = Object.create( Polygons.prototype );
  1898. Triangles.prototype.constructor = Triangles;
  1899. function Accessor() {
  1900. this.source = "";
  1901. this.count = 0;
  1902. this.stride = 0;
  1903. this.params = [];
  1904. };
  1905. Accessor.prototype.parse = function ( element ) {
  1906. this.params = [];
  1907. this.source = element.getAttribute( 'source' );
  1908. this.count = _attr_as_int( element, 'count', 0 );
  1909. this.stride = _attr_as_int( element, 'stride', 0 );
  1910. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1911. var child = element.childNodes[ i ];
  1912. if ( child.nodeName === 'param' ) {
  1913. var param = {};
  1914. param[ 'name' ] = child.getAttribute( 'name' );
  1915. param[ 'type' ] = child.getAttribute( 'type' );
  1916. this.params.push( param );
  1917. }
  1918. }
  1919. return this;
  1920. };
  1921. function Vertices() {
  1922. this.input = {};
  1923. };
  1924. Vertices.prototype.parse = function ( element ) {
  1925. this.id = element.getAttribute('id');
  1926. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1927. if ( element.childNodes[i].nodeName === 'input' ) {
  1928. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1929. this.input[ input.semantic ] = input;
  1930. }
  1931. }
  1932. return this;
  1933. };
  1934. function Input () {
  1935. this.semantic = "";
  1936. this.offset = 0;
  1937. this.source = "";
  1938. this.set = 0;
  1939. };
  1940. Input.prototype.parse = function ( element ) {
  1941. this.semantic = element.getAttribute('semantic');
  1942. this.source = element.getAttribute('source').replace(/^#/, '');
  1943. this.set = _attr_as_int(element, 'set', -1);
  1944. this.offset = _attr_as_int(element, 'offset', 0);
  1945. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  1946. this.set = 0;
  1947. }
  1948. return this;
  1949. };
  1950. function Source ( id ) {
  1951. this.id = id;
  1952. this.type = null;
  1953. };
  1954. Source.prototype.parse = function ( element ) {
  1955. this.id = element.getAttribute( 'id' );
  1956. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1957. var child = element.childNodes[i];
  1958. switch ( child.nodeName ) {
  1959. case 'bool_array':
  1960. this.data = _bools( child.textContent );
  1961. this.type = child.nodeName;
  1962. break;
  1963. case 'float_array':
  1964. this.data = _floats( child.textContent );
  1965. this.type = child.nodeName;
  1966. break;
  1967. case 'int_array':
  1968. this.data = _ints( child.textContent );
  1969. this.type = child.nodeName;
  1970. break;
  1971. case 'IDREF_array':
  1972. case 'Name_array':
  1973. this.data = _strings( child.textContent );
  1974. this.type = child.nodeName;
  1975. break;
  1976. case 'technique_common':
  1977. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1978. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  1979. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1980. break;
  1981. }
  1982. }
  1983. break;
  1984. default:
  1985. // console.log(child.nodeName);
  1986. break;
  1987. }
  1988. }
  1989. return this;
  1990. };
  1991. Source.prototype.read = function () {
  1992. var result = [];
  1993. //for (var i = 0; i < this.accessor.params.length; i++) {
  1994. var param = this.accessor.params[ 0 ];
  1995. //console.log(param.name + " " + param.type);
  1996. switch ( param.type ) {
  1997. case 'IDREF':
  1998. case 'Name': case 'name':
  1999. case 'float':
  2000. return this.data;
  2001. case 'float4x4':
  2002. for ( var j = 0; j < this.data.length; j += 16 ) {
  2003. var s = this.data.slice( j, j + 16 );
  2004. var m = getConvertedMat4( s );
  2005. result.push( m );
  2006. }
  2007. break;
  2008. default:
  2009. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  2010. break;
  2011. }
  2012. //}
  2013. return result;
  2014. };
  2015. function Material () {
  2016. this.id = "";
  2017. this.name = "";
  2018. this.instance_effect = null;
  2019. };
  2020. Material.prototype.parse = function ( element ) {
  2021. this.id = element.getAttribute( 'id' );
  2022. this.name = element.getAttribute( 'name' );
  2023. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2024. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  2025. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  2026. break;
  2027. }
  2028. }
  2029. return this;
  2030. };
  2031. function ColorOrTexture () {
  2032. this.color = new THREE.Color();
  2033. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  2034. this.color.a = 1.0;
  2035. this.texture = null;
  2036. this.texcoord = null;
  2037. this.texOpts = null;
  2038. };
  2039. ColorOrTexture.prototype.isColor = function () {
  2040. return ( this.texture === null );
  2041. };
  2042. ColorOrTexture.prototype.isTexture = function () {
  2043. return ( this.texture != null );
  2044. };
  2045. ColorOrTexture.prototype.parse = function ( element ) {
  2046. if (element.nodeName === 'transparent') {
  2047. this.opaque = element.getAttribute('opaque');
  2048. }
  2049. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2050. var child = element.childNodes[ i ];
  2051. if ( child.nodeType != 1 ) continue;
  2052. switch ( child.nodeName ) {
  2053. case 'color':
  2054. var rgba = _floats( child.textContent );
  2055. this.color = new THREE.Color();
  2056. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2057. this.color.a = rgba[3];
  2058. break;
  2059. case 'texture':
  2060. this.texture = child.getAttribute('texture');
  2061. this.texcoord = child.getAttribute('texcoord');
  2062. // Defaults from:
  2063. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  2064. this.texOpts = {
  2065. offsetU: 0,
  2066. offsetV: 0,
  2067. repeatU: 1,
  2068. repeatV: 1,
  2069. wrapU: 1,
  2070. wrapV: 1
  2071. };
  2072. this.parseTexture( child );
  2073. break;
  2074. default:
  2075. break;
  2076. }
  2077. }
  2078. return this;
  2079. };
  2080. ColorOrTexture.prototype.parseTexture = function ( element ) {
  2081. if ( ! element.childNodes ) return this;
  2082. // This should be supported by Maya, 3dsMax, and MotionBuilder
  2083. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  2084. element = element.childNodes[1];
  2085. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  2086. element = element.childNodes[1];
  2087. }
  2088. }
  2089. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2090. var child = element.childNodes[ i ];
  2091. switch ( child.nodeName ) {
  2092. case 'offsetU':
  2093. case 'offsetV':
  2094. case 'repeatU':
  2095. case 'repeatV':
  2096. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  2097. break;
  2098. case 'wrapU':
  2099. case 'wrapV':
  2100. // some dae have a value of true which becomes NaN via parseInt
  2101. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  2102. this.texOpts[ child.nodeName ] = 1;
  2103. } else {
  2104. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  2105. }
  2106. break;
  2107. default:
  2108. this.texOpts[ child.nodeName ] = child.textContent;
  2109. break;
  2110. }
  2111. }
  2112. return this;
  2113. };
  2114. function Shader ( type, effect ) {
  2115. this.type = type;
  2116. this.effect = effect;
  2117. this.material = null;
  2118. };
  2119. Shader.prototype.parse = function ( element ) {
  2120. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2121. var child = element.childNodes[ i ];
  2122. if ( child.nodeType != 1 ) continue;
  2123. switch ( child.nodeName ) {
  2124. case 'emission':
  2125. case 'diffuse':
  2126. case 'specular':
  2127. case 'transparent':
  2128. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  2129. break;
  2130. case 'bump':
  2131. // If 'bumptype' is 'heightfield', create a 'bump' property
  2132. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  2133. // (Default to 'bump')
  2134. var bumpType = child.getAttribute( 'bumptype' );
  2135. if ( bumpType ) {
  2136. if ( bumpType.toLowerCase() === "heightfield" ) {
  2137. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2138. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  2139. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  2140. } else {
  2141. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  2142. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2143. }
  2144. } else {
  2145. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  2146. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2147. }
  2148. break;
  2149. case 'shininess':
  2150. case 'reflectivity':
  2151. case 'index_of_refraction':
  2152. case 'transparency':
  2153. var f = child.querySelectorAll('float');
  2154. if ( f.length > 0 )
  2155. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  2156. break;
  2157. default:
  2158. break;
  2159. }
  2160. }
  2161. this.create();
  2162. return this;
  2163. };
  2164. Shader.prototype.create = function() {
  2165. var props = {};
  2166. var transparent = false;
  2167. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  2168. // convert transparent color RBG to average value
  2169. var transparentColor = this['transparent'];
  2170. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  2171. if (transparencyLevel > 0) {
  2172. transparent = true;
  2173. props[ 'transparent' ] = true;
  2174. props[ 'opacity' ] = 1 - transparencyLevel;
  2175. }
  2176. }
  2177. var keys = {
  2178. 'diffuse':'map',
  2179. 'ambient':'lightMap',
  2180. 'specular':'specularMap',
  2181. 'emission':'emissionMap',
  2182. 'bump':'bumpMap',
  2183. 'normal':'normalMap'
  2184. };
  2185. for ( var prop in this ) {
  2186. switch ( prop ) {
  2187. case 'ambient':
  2188. case 'emission':
  2189. case 'diffuse':
  2190. case 'specular':
  2191. case 'bump':
  2192. case 'normal':
  2193. var cot = this[ prop ];
  2194. if ( cot instanceof ColorOrTexture ) {
  2195. if ( cot.isTexture() ) {
  2196. var samplerId = cot.texture;
  2197. var surfaceId = this.effect.sampler[samplerId];
  2198. if ( surfaceId !== undefined && surfaceId.source !== undefined ) {
  2199. var surface = this.effect.surface[surfaceId.source];
  2200. if ( surface !== undefined ) {
  2201. var image = images[ surface.init_from ];
  2202. if ( image ) {
  2203. var url = baseUrl + image.init_from;
  2204. var texture;
  2205. var loader = THREE.Loader.Handlers.get( url );
  2206. if ( loader !== null ) {
  2207. texture = loader.load( url );
  2208. } else {
  2209. texture = new THREE.Texture();
  2210. loadTextureImage( texture, url );
  2211. }
  2212. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2213. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2214. texture.offset.x = cot.texOpts.offsetU;
  2215. texture.offset.y = cot.texOpts.offsetV;
  2216. texture.repeat.x = cot.texOpts.repeatU;
  2217. texture.repeat.y = cot.texOpts.repeatV;
  2218. props[keys[prop]] = texture;
  2219. // Texture with baked lighting?
  2220. if (prop === 'emission') props['emissive'] = 0xffffff;
  2221. }
  2222. }
  2223. }
  2224. } else if ( prop === 'diffuse' || !transparent ) {
  2225. if ( prop === 'emission' ) {
  2226. props[ 'emissive' ] = cot.color.getHex();
  2227. } else {
  2228. props[ prop ] = cot.color.getHex();
  2229. }
  2230. }
  2231. }
  2232. break;
  2233. case 'shininess':
  2234. props[ prop ] = this[ prop ];
  2235. break;
  2236. case 'reflectivity':
  2237. props[ prop ] = this[ prop ];
  2238. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  2239. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  2240. break;
  2241. case 'index_of_refraction':
  2242. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  2243. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  2244. break;
  2245. case 'transparency':
  2246. // gets figured out up top
  2247. break;
  2248. default:
  2249. break;
  2250. }
  2251. }
  2252. props[ 'shading' ] = preferredShading;
  2253. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  2254. switch ( this.type ) {
  2255. case 'constant':
  2256. if (props.emissive != undefined) props.color = props.emissive;
  2257. this.material = new THREE.MeshBasicMaterial( props );
  2258. break;
  2259. case 'phong':
  2260. case 'blinn':
  2261. if (props.diffuse != undefined) props.color = props.diffuse;
  2262. this.material = new THREE.MeshPhongMaterial( props );
  2263. break;
  2264. case 'lambert':
  2265. default:
  2266. if (props.diffuse != undefined) props.color = props.diffuse;
  2267. this.material = new THREE.MeshLambertMaterial( props );
  2268. break;
  2269. }
  2270. return this.material;
  2271. };
  2272. function Surface ( effect ) {
  2273. this.effect = effect;
  2274. this.init_from = null;
  2275. this.format = null;
  2276. };
  2277. Surface.prototype.parse = function ( element ) {
  2278. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2279. var child = element.childNodes[ i ];
  2280. if ( child.nodeType != 1 ) continue;
  2281. switch ( child.nodeName ) {
  2282. case 'init_from':
  2283. this.init_from = child.textContent;
  2284. break;
  2285. case 'format':
  2286. this.format = child.textContent;
  2287. break;
  2288. default:
  2289. console.log( "unhandled Surface prop: " + child.nodeName );
  2290. break;
  2291. }
  2292. }
  2293. return this;
  2294. };
  2295. function Sampler2D ( effect ) {
  2296. this.effect = effect;
  2297. this.source = null;
  2298. this.wrap_s = null;
  2299. this.wrap_t = null;
  2300. this.minfilter = null;
  2301. this.magfilter = null;
  2302. this.mipfilter = null;
  2303. };
  2304. Sampler2D.prototype.parse = function ( element ) {
  2305. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2306. var child = element.childNodes[ i ];
  2307. if ( child.nodeType != 1 ) continue;
  2308. switch ( child.nodeName ) {
  2309. case 'source':
  2310. this.source = child.textContent;
  2311. break;
  2312. case 'minfilter':
  2313. this.minfilter = child.textContent;
  2314. break;
  2315. case 'magfilter':
  2316. this.magfilter = child.textContent;
  2317. break;
  2318. case 'mipfilter':
  2319. this.mipfilter = child.textContent;
  2320. break;
  2321. case 'wrap_s':
  2322. this.wrap_s = child.textContent;
  2323. break;
  2324. case 'wrap_t':
  2325. this.wrap_t = child.textContent;
  2326. break;
  2327. default:
  2328. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  2329. break;
  2330. }
  2331. }
  2332. return this;
  2333. };
  2334. function Effect () {
  2335. this.id = "";
  2336. this.name = "";
  2337. this.shader = null;
  2338. this.surface = {};
  2339. this.sampler = {};
  2340. };
  2341. Effect.prototype.create = function () {
  2342. if ( this.shader === null ) {
  2343. return null;
  2344. }
  2345. };
  2346. Effect.prototype.parse = function ( element ) {
  2347. this.id = element.getAttribute( 'id' );
  2348. this.name = element.getAttribute( 'name' );
  2349. extractDoubleSided( this, element );
  2350. this.shader = null;
  2351. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2352. var child = element.childNodes[ i ];
  2353. if ( child.nodeType != 1 ) continue;
  2354. switch ( child.nodeName ) {
  2355. case 'profile_COMMON':
  2356. this.parseTechnique( this.parseProfileCOMMON( child ) );
  2357. break;
  2358. default:
  2359. break;
  2360. }
  2361. }
  2362. return this;
  2363. };
  2364. Effect.prototype.parseNewparam = function ( element ) {
  2365. var sid = element.getAttribute( 'sid' );
  2366. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2367. var child = element.childNodes[ i ];
  2368. if ( child.nodeType != 1 ) continue;
  2369. switch ( child.nodeName ) {
  2370. case 'surface':
  2371. this.surface[sid] = ( new Surface( this ) ).parse( child );
  2372. break;
  2373. case 'sampler2D':
  2374. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  2375. break;
  2376. case 'extra':
  2377. break;
  2378. default:
  2379. console.log( child.nodeName );
  2380. break;
  2381. }
  2382. }
  2383. };
  2384. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2385. var technique;
  2386. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2387. var child = element.childNodes[ i ];
  2388. if ( child.nodeType != 1 ) continue;
  2389. switch ( child.nodeName ) {
  2390. case 'profile_COMMON':
  2391. this.parseProfileCOMMON( child );
  2392. break;
  2393. case 'technique':
  2394. technique = child;
  2395. break;
  2396. case 'newparam':
  2397. this.parseNewparam( child );
  2398. break;
  2399. case 'image':
  2400. var _image = ( new _Image() ).parse( child );
  2401. images[ _image.id ] = _image;
  2402. break;
  2403. case 'extra':
  2404. break;
  2405. default:
  2406. console.log( child.nodeName );
  2407. break;
  2408. }
  2409. }
  2410. return technique;
  2411. };
  2412. Effect.prototype.parseTechnique = function ( element ) {
  2413. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2414. var child = element.childNodes[i];
  2415. if ( child.nodeType != 1 ) continue;
  2416. switch ( child.nodeName ) {
  2417. case 'constant':
  2418. case 'lambert':
  2419. case 'blinn':
  2420. case 'phong':
  2421. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2422. break;
  2423. case 'extra':
  2424. this.parseExtra(child);
  2425. break;
  2426. default:
  2427. break;
  2428. }
  2429. }
  2430. };
  2431. Effect.prototype.parseExtra = function ( element ) {
  2432. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2433. var child = element.childNodes[i];
  2434. if ( child.nodeType != 1 ) continue;
  2435. switch ( child.nodeName ) {
  2436. case 'technique':
  2437. this.parseExtraTechnique( child );
  2438. break;
  2439. default:
  2440. break;
  2441. }
  2442. }
  2443. };
  2444. Effect.prototype.parseExtraTechnique = function ( element ) {
  2445. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2446. var child = element.childNodes[i];
  2447. if ( child.nodeType != 1 ) continue;
  2448. switch ( child.nodeName ) {
  2449. case 'bump':
  2450. this.shader.parse( element );
  2451. break;
  2452. default:
  2453. break;
  2454. }
  2455. }
  2456. };
  2457. function InstanceEffect () {
  2458. this.url = "";
  2459. };
  2460. InstanceEffect.prototype.parse = function ( element ) {
  2461. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2462. return this;
  2463. };
  2464. function Animation() {
  2465. this.id = "";
  2466. this.name = "";
  2467. this.source = {};
  2468. this.sampler = [];
  2469. this.channel = [];
  2470. };
  2471. Animation.prototype.parse = function ( element ) {
  2472. this.id = element.getAttribute( 'id' );
  2473. this.name = element.getAttribute( 'name' );
  2474. this.source = {};
  2475. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2476. var child = element.childNodes[ i ];
  2477. if ( child.nodeType != 1 ) continue;
  2478. switch ( child.nodeName ) {
  2479. case 'animation':
  2480. var anim = ( new Animation() ).parse( child );
  2481. for ( var src in anim.source ) {
  2482. this.source[ src ] = anim.source[ src ];
  2483. }
  2484. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2485. this.channel.push( anim.channel[ j ] );
  2486. this.sampler.push( anim.sampler[ j ] );
  2487. }
  2488. break;
  2489. case 'source':
  2490. var src = ( new Source() ).parse( child );
  2491. this.source[ src.id ] = src;
  2492. break;
  2493. case 'sampler':
  2494. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2495. break;
  2496. case 'channel':
  2497. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2498. break;
  2499. default:
  2500. break;
  2501. }
  2502. }
  2503. return this;
  2504. };
  2505. function Channel( animation ) {
  2506. this.animation = animation;
  2507. this.source = "";
  2508. this.target = "";
  2509. this.fullSid = null;
  2510. this.sid = null;
  2511. this.dotSyntax = null;
  2512. this.arrSyntax = null;
  2513. this.arrIndices = null;
  2514. this.member = null;
  2515. };
  2516. Channel.prototype.parse = function ( element ) {
  2517. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2518. this.target = element.getAttribute( 'target' );
  2519. var parts = this.target.split( '/' );
  2520. var id = parts.shift();
  2521. var sid = parts.shift();
  2522. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2523. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2524. if ( dotSyntax ) {
  2525. parts = sid.split(".");
  2526. this.sid = parts.shift();
  2527. this.member = parts.shift();
  2528. } else if ( arrSyntax ) {
  2529. var arrIndices = sid.split("(");
  2530. this.sid = arrIndices.shift();
  2531. for (var j = 0; j < arrIndices.length; j ++ ) {
  2532. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2533. }
  2534. this.arrIndices = arrIndices;
  2535. } else {
  2536. this.sid = sid;
  2537. }
  2538. this.fullSid = sid;
  2539. this.dotSyntax = dotSyntax;
  2540. this.arrSyntax = arrSyntax;
  2541. return this;
  2542. };
  2543. function Sampler ( animation ) {
  2544. this.id = "";
  2545. this.animation = animation;
  2546. this.inputs = [];
  2547. this.input = null;
  2548. this.output = null;
  2549. this.strideOut = null;
  2550. this.interpolation = null;
  2551. this.startTime = null;
  2552. this.endTime = null;
  2553. this.duration = 0;
  2554. };
  2555. Sampler.prototype.parse = function ( element ) {
  2556. this.id = element.getAttribute( 'id' );
  2557. this.inputs = [];
  2558. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2559. var child = element.childNodes[ i ];
  2560. if ( child.nodeType != 1 ) continue;
  2561. switch ( child.nodeName ) {
  2562. case 'input':
  2563. this.inputs.push( (new Input()).parse( child ) );
  2564. break;
  2565. default:
  2566. break;
  2567. }
  2568. }
  2569. return this;
  2570. };
  2571. Sampler.prototype.create = function () {
  2572. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2573. var input = this.inputs[ i ];
  2574. var source = this.animation.source[ input.source ];
  2575. switch ( input.semantic ) {
  2576. case 'INPUT':
  2577. this.input = source.read();
  2578. break;
  2579. case 'OUTPUT':
  2580. this.output = source.read();
  2581. this.strideOut = source.accessor.stride;
  2582. break;
  2583. case 'INTERPOLATION':
  2584. this.interpolation = source.read();
  2585. break;
  2586. case 'IN_TANGENT':
  2587. break;
  2588. case 'OUT_TANGENT':
  2589. break;
  2590. default:
  2591. console.log(input.semantic);
  2592. break;
  2593. }
  2594. }
  2595. this.startTime = 0;
  2596. this.endTime = 0;
  2597. this.duration = 0;
  2598. if ( this.input.length ) {
  2599. this.startTime = 100000000;
  2600. this.endTime = -100000000;
  2601. for ( var i = 0; i < this.input.length; i ++ ) {
  2602. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2603. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2604. }
  2605. this.duration = this.endTime - this.startTime;
  2606. }
  2607. };
  2608. Sampler.prototype.getData = function ( type, ndx, member ) {
  2609. var data;
  2610. if ( type === 'matrix' && this.strideOut === 16 ) {
  2611. data = this.output[ ndx ];
  2612. } else if ( this.strideOut > 1 ) {
  2613. data = [];
  2614. ndx *= this.strideOut;
  2615. for ( var i = 0; i < this.strideOut; ++ i ) {
  2616. data[ i ] = this.output[ ndx + i ];
  2617. }
  2618. if ( this.strideOut === 3 ) {
  2619. switch ( type ) {
  2620. case 'rotate':
  2621. case 'translate':
  2622. fixCoords( data, -1 );
  2623. break;
  2624. case 'scale':
  2625. fixCoords( data, 1 );
  2626. break;
  2627. }
  2628. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2629. fixCoords( data, -1 );
  2630. }
  2631. } else {
  2632. data = this.output[ ndx ];
  2633. if ( member && type === 'translate' ) {
  2634. data = getConvertedTranslation( member, data );
  2635. }
  2636. }
  2637. return data;
  2638. };
  2639. function Key ( time ) {
  2640. this.targets = [];
  2641. this.time = time;
  2642. };
  2643. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2644. this.targets.push( {
  2645. sid: fullSid,
  2646. member: member,
  2647. transform: transform,
  2648. data: data
  2649. } );
  2650. };
  2651. Key.prototype.apply = function ( opt_sid ) {
  2652. for ( var i = 0; i < this.targets.length; ++ i ) {
  2653. var target = this.targets[ i ];
  2654. if ( !opt_sid || target.sid === opt_sid ) {
  2655. target.transform.update( target.data, target.member );
  2656. }
  2657. }
  2658. };
  2659. Key.prototype.getTarget = function ( fullSid ) {
  2660. for ( var i = 0; i < this.targets.length; ++ i ) {
  2661. if ( this.targets[ i ].sid === fullSid ) {
  2662. return this.targets[ i ];
  2663. }
  2664. }
  2665. return null;
  2666. };
  2667. Key.prototype.hasTarget = function ( fullSid ) {
  2668. for ( var i = 0; i < this.targets.length; ++ i ) {
  2669. if ( this.targets[ i ].sid === fullSid ) {
  2670. return true;
  2671. }
  2672. }
  2673. return false;
  2674. };
  2675. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2676. Key.prototype.interpolate = function ( nextKey, time ) {
  2677. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  2678. var target = this.targets[ i ],
  2679. nextTarget = nextKey.getTarget( target.sid ),
  2680. data;
  2681. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2682. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2683. nextData = nextTarget.data,
  2684. prevData = target.data;
  2685. if ( scale < 0 ) scale = 0;
  2686. if ( scale > 1 ) scale = 1;
  2687. if ( prevData.length ) {
  2688. data = [];
  2689. for ( var j = 0; j < prevData.length; ++ j ) {
  2690. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2691. }
  2692. } else {
  2693. data = prevData + ( nextData - prevData ) * scale;
  2694. }
  2695. } else {
  2696. data = target.data;
  2697. }
  2698. target.transform.update( data, target.member );
  2699. }
  2700. };
  2701. // Camera
  2702. function Camera() {
  2703. this.id = "";
  2704. this.name = "";
  2705. this.technique = "";
  2706. };
  2707. Camera.prototype.parse = function ( element ) {
  2708. this.id = element.getAttribute( 'id' );
  2709. this.name = element.getAttribute( 'name' );
  2710. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2711. var child = element.childNodes[ i ];
  2712. if ( child.nodeType != 1 ) continue;
  2713. switch ( child.nodeName ) {
  2714. case 'optics':
  2715. this.parseOptics( child );
  2716. break;
  2717. default:
  2718. break;
  2719. }
  2720. }
  2721. return this;
  2722. };
  2723. Camera.prototype.parseOptics = function ( element ) {
  2724. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2725. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  2726. var technique = element.childNodes[ i ];
  2727. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2728. this.technique = technique.childNodes[ j ].nodeName;
  2729. if ( this.technique === 'perspective' ) {
  2730. var perspective = technique.childNodes[ j ];
  2731. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2732. var param = perspective.childNodes[ k ];
  2733. switch ( param.nodeName ) {
  2734. case 'yfov':
  2735. this.yfov = param.textContent;
  2736. break;
  2737. case 'xfov':
  2738. this.xfov = param.textContent;
  2739. break;
  2740. case 'znear':
  2741. this.znear = param.textContent;
  2742. break;
  2743. case 'zfar':
  2744. this.zfar = param.textContent;
  2745. break;
  2746. case 'aspect_ratio':
  2747. this.aspect_ratio = param.textContent;
  2748. break;
  2749. }
  2750. }
  2751. } else if ( this.technique === 'orthographic' ) {
  2752. var orthographic = technique.childNodes[ j ];
  2753. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2754. var param = orthographic.childNodes[ k ];
  2755. switch ( param.nodeName ) {
  2756. case 'xmag':
  2757. this.xmag = param.textContent;
  2758. break;
  2759. case 'ymag':
  2760. this.ymag = param.textContent;
  2761. break;
  2762. case 'znear':
  2763. this.znear = param.textContent;
  2764. break;
  2765. case 'zfar':
  2766. this.zfar = param.textContent;
  2767. break;
  2768. case 'aspect_ratio':
  2769. this.aspect_ratio = param.textContent;
  2770. break;
  2771. }
  2772. }
  2773. }
  2774. }
  2775. }
  2776. }
  2777. return this;
  2778. };
  2779. function InstanceCamera() {
  2780. this.url = "";
  2781. };
  2782. InstanceCamera.prototype.parse = function ( element ) {
  2783. this.url = element.getAttribute('url').replace(/^#/, '');
  2784. return this;
  2785. };
  2786. // Light
  2787. function Light() {
  2788. this.id = "";
  2789. this.name = "";
  2790. this.technique = "";
  2791. };
  2792. Light.prototype.parse = function ( element ) {
  2793. this.id = element.getAttribute( 'id' );
  2794. this.name = element.getAttribute( 'name' );
  2795. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2796. var child = element.childNodes[ i ];
  2797. if ( child.nodeType != 1 ) continue;
  2798. switch ( child.nodeName ) {
  2799. case 'technique_common':
  2800. this.parseCommon( child );
  2801. break;
  2802. case 'technique':
  2803. this.parseTechnique( child );
  2804. break;
  2805. default:
  2806. break;
  2807. }
  2808. }
  2809. return this;
  2810. };
  2811. Light.prototype.parseCommon = function ( element ) {
  2812. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2813. switch ( element.childNodes[ i ].nodeName ) {
  2814. case 'directional':
  2815. case 'point':
  2816. case 'spot':
  2817. case 'ambient':
  2818. this.technique = element.childNodes[ i ].nodeName;
  2819. var light = element.childNodes[ i ];
  2820. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  2821. var child = light.childNodes[j];
  2822. switch ( child.nodeName ) {
  2823. case 'color':
  2824. var rgba = _floats( child.textContent );
  2825. this.color = new THREE.Color(0);
  2826. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2827. this.color.a = rgba[3];
  2828. break;
  2829. case 'falloff_angle':
  2830. this.falloff_angle = parseFloat( child.textContent );
  2831. break;
  2832. case 'quadratic_attenuation':
  2833. var f = parseFloat( child.textContent );
  2834. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  2835. }
  2836. }
  2837. }
  2838. }
  2839. return this;
  2840. };
  2841. Light.prototype.parseTechnique = function ( element ) {
  2842. this.profile = element.getAttribute( 'profile' );
  2843. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2844. var child = element.childNodes[ i ];
  2845. switch ( child.nodeName ) {
  2846. case 'intensity':
  2847. this.intensity = parseFloat(child.textContent);
  2848. break;
  2849. }
  2850. }
  2851. return this;
  2852. };
  2853. function InstanceLight() {
  2854. this.url = "";
  2855. };
  2856. InstanceLight.prototype.parse = function ( element ) {
  2857. this.url = element.getAttribute('url').replace(/^#/, '');
  2858. return this;
  2859. };
  2860. function KinematicsModel( ) {
  2861. this.id = '';
  2862. this.name = '';
  2863. this.joints = [];
  2864. this.links = [];
  2865. }
  2866. KinematicsModel.prototype.parse = function( element ) {
  2867. this.id = element.getAttribute('id');
  2868. this.name = element.getAttribute('name');
  2869. this.joints = [];
  2870. this.links = [];
  2871. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2872. var child = element.childNodes[ i ];
  2873. if ( child.nodeType != 1 ) continue;
  2874. switch ( child.nodeName ) {
  2875. case 'technique_common':
  2876. this.parseCommon(child);
  2877. break;
  2878. default:
  2879. break;
  2880. }
  2881. }
  2882. return this;
  2883. };
  2884. KinematicsModel.prototype.parseCommon = function( element ) {
  2885. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2886. var child = element.childNodes[ i ];
  2887. if ( child.nodeType != 1 ) continue;
  2888. switch ( element.childNodes[ i ].nodeName ) {
  2889. case 'joint':
  2890. this.joints.push( (new Joint()).parse(child) );
  2891. break;
  2892. case 'link':
  2893. this.links.push( (new Link()).parse(child) );
  2894. break;
  2895. default:
  2896. break;
  2897. }
  2898. }
  2899. return this;
  2900. };
  2901. function Joint( ) {
  2902. this.sid = '';
  2903. this.name = '';
  2904. this.axis = new THREE.Vector3();
  2905. this.limits = {
  2906. min: 0,
  2907. max: 0
  2908. };
  2909. this.type = '';
  2910. this.static = false;
  2911. this.zeroPosition = 0.0;
  2912. this.middlePosition = 0.0;
  2913. }
  2914. Joint.prototype.parse = function( element ) {
  2915. this.sid = element.getAttribute('sid');
  2916. this.name = element.getAttribute('name');
  2917. this.axis = new THREE.Vector3();
  2918. this.limits = {
  2919. min: 0,
  2920. max: 0
  2921. };
  2922. this.type = '';
  2923. this.static = false;
  2924. this.zeroPosition = 0.0;
  2925. this.middlePosition = 0.0;
  2926. var axisElement = element.querySelector('axis');
  2927. var _axis = _floats(axisElement.textContent);
  2928. this.axis = getConvertedVec3(_axis, 0);
  2929. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  2930. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  2931. this.limits = {
  2932. min: min,
  2933. max: max
  2934. };
  2935. var jointTypes = [ 'prismatic', 'revolute' ];
  2936. for (var i = 0; i < jointTypes.length; i ++ ) {
  2937. var type = jointTypes[ i ];
  2938. var jointElement = element.querySelector(type);
  2939. if ( jointElement ) {
  2940. this.type = type;
  2941. }
  2942. }
  2943. // if the min is equal to or somehow greater than the max, consider the joint static
  2944. if ( this.limits.min >= this.limits.max ) {
  2945. this.static = true;
  2946. }
  2947. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  2948. return this;
  2949. };
  2950. function Link( ) {
  2951. this.sid = '';
  2952. this.name = '';
  2953. this.transforms = [];
  2954. this.attachments = [];
  2955. }
  2956. Link.prototype.parse = function( element ) {
  2957. this.sid = element.getAttribute('sid');
  2958. this.name = element.getAttribute('name');
  2959. this.transforms = [];
  2960. this.attachments = [];
  2961. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2962. var child = element.childNodes[ i ];
  2963. if ( child.nodeType != 1 ) continue;
  2964. switch ( child.nodeName ) {
  2965. case 'attachment_full':
  2966. this.attachments.push( (new Attachment()).parse(child) );
  2967. break;
  2968. case 'rotate':
  2969. case 'translate':
  2970. case 'matrix':
  2971. this.transforms.push( (new Transform()).parse(child) );
  2972. break;
  2973. default:
  2974. break;
  2975. }
  2976. }
  2977. return this;
  2978. };
  2979. function Attachment( ) {
  2980. this.joint = '';
  2981. this.transforms = [];
  2982. this.links = [];
  2983. }
  2984. Attachment.prototype.parse = function( element ) {
  2985. this.joint = element.getAttribute('joint').split('/').pop();
  2986. this.links = [];
  2987. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2988. var child = element.childNodes[ i ];
  2989. if ( child.nodeType != 1 ) continue;
  2990. switch ( child.nodeName ) {
  2991. case 'link':
  2992. this.links.push( (new Link()).parse(child) );
  2993. break;
  2994. case 'rotate':
  2995. case 'translate':
  2996. case 'matrix':
  2997. this.transforms.push( (new Transform()).parse(child) );
  2998. break;
  2999. default:
  3000. break;
  3001. }
  3002. }
  3003. return this;
  3004. };
  3005. function _source( element ) {
  3006. var id = element.getAttribute( 'id' );
  3007. if ( sources[ id ] != undefined ) {
  3008. return sources[ id ];
  3009. }
  3010. sources[ id ] = ( new Source(id )).parse( element );
  3011. return sources[ id ];
  3012. };
  3013. function _nsResolver( nsPrefix ) {
  3014. if ( nsPrefix === "dae" ) {
  3015. return "http://www.collada.org/2005/11/COLLADASchema";
  3016. }
  3017. return null;
  3018. };
  3019. function _bools( str ) {
  3020. var raw = _strings( str );
  3021. var data = [];
  3022. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3023. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  3024. }
  3025. return data;
  3026. };
  3027. function _floats( str ) {
  3028. var raw = _strings(str);
  3029. var data = [];
  3030. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3031. data.push( parseFloat( raw[ i ] ) );
  3032. }
  3033. return data;
  3034. };
  3035. function _ints( str ) {
  3036. var raw = _strings( str );
  3037. var data = [];
  3038. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3039. data.push( parseInt( raw[ i ], 10 ) );
  3040. }
  3041. return data;
  3042. };
  3043. function _strings( str ) {
  3044. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  3045. };
  3046. function _trimString( str ) {
  3047. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  3048. };
  3049. function _attr_as_float( element, name, defaultValue ) {
  3050. if ( element.hasAttribute( name ) ) {
  3051. return parseFloat( element.getAttribute( name ) );
  3052. } else {
  3053. return defaultValue;
  3054. }
  3055. };
  3056. function _attr_as_int( element, name, defaultValue ) {
  3057. if ( element.hasAttribute( name ) ) {
  3058. return parseInt( element.getAttribute( name ), 10) ;
  3059. } else {
  3060. return defaultValue;
  3061. }
  3062. };
  3063. function _attr_as_string( element, name, defaultValue ) {
  3064. if ( element.hasAttribute( name ) ) {
  3065. return element.getAttribute( name );
  3066. } else {
  3067. return defaultValue;
  3068. }
  3069. };
  3070. function _format_float( f, num ) {
  3071. if ( f === undefined ) {
  3072. var s = '0.';
  3073. while ( s.length < num + 2 ) {
  3074. s += '0';
  3075. }
  3076. return s;
  3077. }
  3078. num = num || 2;
  3079. var parts = f.toString().split( '.' );
  3080. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  3081. while ( parts[ 1 ].length < num ) {
  3082. parts[ 1 ] += '0';
  3083. }
  3084. return parts.join( '.' );
  3085. };
  3086. function loadTextureImage ( texture, url ) {
  3087. loader = new THREE.ImageLoader();
  3088. loader.load( url, function ( image ) {
  3089. texture.image = image;
  3090. texture.needsUpdate = true;
  3091. } );
  3092. };
  3093. function extractDoubleSided( obj, element ) {
  3094. obj.doubleSided = false;
  3095. var node = element.querySelectorAll('extra double_sided')[0];
  3096. if ( node ) {
  3097. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  3098. obj.doubleSided = true;
  3099. }
  3100. }
  3101. };
  3102. // Up axis conversion
  3103. function setUpConversion() {
  3104. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3105. upConversion = null;
  3106. } else {
  3107. switch ( colladaUp ) {
  3108. case 'X':
  3109. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  3110. break;
  3111. case 'Y':
  3112. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  3113. break;
  3114. case 'Z':
  3115. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  3116. break;
  3117. }
  3118. }
  3119. };
  3120. function fixCoords( data, sign ) {
  3121. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3122. return;
  3123. }
  3124. switch ( upConversion ) {
  3125. case 'XtoY':
  3126. var tmp = data[ 0 ];
  3127. data[ 0 ] = sign * data[ 1 ];
  3128. data[ 1 ] = tmp;
  3129. break;
  3130. case 'XtoZ':
  3131. var tmp = data[ 2 ];
  3132. data[ 2 ] = data[ 1 ];
  3133. data[ 1 ] = data[ 0 ];
  3134. data[ 0 ] = tmp;
  3135. break;
  3136. case 'YtoX':
  3137. var tmp = data[ 0 ];
  3138. data[ 0 ] = data[ 1 ];
  3139. data[ 1 ] = sign * tmp;
  3140. break;
  3141. case 'YtoZ':
  3142. var tmp = data[ 1 ];
  3143. data[ 1 ] = sign * data[ 2 ];
  3144. data[ 2 ] = tmp;
  3145. break;
  3146. case 'ZtoX':
  3147. var tmp = data[ 0 ];
  3148. data[ 0 ] = data[ 1 ];
  3149. data[ 1 ] = data[ 2 ];
  3150. data[ 2 ] = tmp;
  3151. break;
  3152. case 'ZtoY':
  3153. var tmp = data[ 1 ];
  3154. data[ 1 ] = data[ 2 ];
  3155. data[ 2 ] = sign * tmp;
  3156. break;
  3157. }
  3158. };
  3159. function getConvertedTranslation( axis, data ) {
  3160. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3161. return data;
  3162. }
  3163. switch ( axis ) {
  3164. case 'X':
  3165. data = upConversion === 'XtoY' ? data * -1 : data;
  3166. break;
  3167. case 'Y':
  3168. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  3169. break;
  3170. case 'Z':
  3171. data = upConversion === 'ZtoY' ? data * -1 : data ;
  3172. break;
  3173. default:
  3174. break;
  3175. }
  3176. return data;
  3177. };
  3178. function getConvertedVec3( data, offset ) {
  3179. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  3180. fixCoords( arr, -1 );
  3181. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  3182. };
  3183. function getConvertedMat4( data ) {
  3184. if ( options.convertUpAxis ) {
  3185. // First fix rotation and scale
  3186. // Columns first
  3187. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  3188. fixCoords( arr, -1 );
  3189. data[ 0 ] = arr[ 0 ];
  3190. data[ 4 ] = arr[ 1 ];
  3191. data[ 8 ] = arr[ 2 ];
  3192. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  3193. fixCoords( arr, -1 );
  3194. data[ 1 ] = arr[ 0 ];
  3195. data[ 5 ] = arr[ 1 ];
  3196. data[ 9 ] = arr[ 2 ];
  3197. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  3198. fixCoords( arr, -1 );
  3199. data[ 2 ] = arr[ 0 ];
  3200. data[ 6 ] = arr[ 1 ];
  3201. data[ 10 ] = arr[ 2 ];
  3202. // Rows second
  3203. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  3204. fixCoords( arr, -1 );
  3205. data[ 0 ] = arr[ 0 ];
  3206. data[ 1 ] = arr[ 1 ];
  3207. data[ 2 ] = arr[ 2 ];
  3208. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  3209. fixCoords( arr, -1 );
  3210. data[ 4 ] = arr[ 0 ];
  3211. data[ 5 ] = arr[ 1 ];
  3212. data[ 6 ] = arr[ 2 ];
  3213. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  3214. fixCoords( arr, -1 );
  3215. data[ 8 ] = arr[ 0 ];
  3216. data[ 9 ] = arr[ 1 ];
  3217. data[ 10 ] = arr[ 2 ];
  3218. // Now fix translation
  3219. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  3220. fixCoords( arr, -1 );
  3221. data[ 3 ] = arr[ 0 ];
  3222. data[ 7 ] = arr[ 1 ];
  3223. data[ 11 ] = arr[ 2 ];
  3224. }
  3225. return new THREE.Matrix4().set(
  3226. data[0], data[1], data[2], data[3],
  3227. data[4], data[5], data[6], data[7],
  3228. data[8], data[9], data[10], data[11],
  3229. data[12], data[13], data[14], data[15]
  3230. );
  3231. };
  3232. function getConvertedIndex( index ) {
  3233. if ( index > -1 && index < 3 ) {
  3234. var members = [ 'X', 'Y', 'Z' ],
  3235. indices = { X: 0, Y: 1, Z: 2 };
  3236. index = getConvertedMember( members[ index ] );
  3237. index = indices[ index ];
  3238. }
  3239. return index;
  3240. };
  3241. function getConvertedMember( member ) {
  3242. if ( options.convertUpAxis ) {
  3243. switch ( member ) {
  3244. case 'X':
  3245. switch ( upConversion ) {
  3246. case 'XtoY':
  3247. case 'XtoZ':
  3248. case 'YtoX':
  3249. member = 'Y';
  3250. break;
  3251. case 'ZtoX':
  3252. member = 'Z';
  3253. break;
  3254. }
  3255. break;
  3256. case 'Y':
  3257. switch ( upConversion ) {
  3258. case 'XtoY':
  3259. case 'YtoX':
  3260. case 'ZtoX':
  3261. member = 'X';
  3262. break;
  3263. case 'XtoZ':
  3264. case 'YtoZ':
  3265. case 'ZtoY':
  3266. member = 'Z';
  3267. break;
  3268. }
  3269. break;
  3270. case 'Z':
  3271. switch ( upConversion ) {
  3272. case 'XtoZ':
  3273. member = 'X';
  3274. break;
  3275. case 'YtoZ':
  3276. case 'ZtoX':
  3277. case 'ZtoY':
  3278. member = 'Y';
  3279. break;
  3280. }
  3281. break;
  3282. }
  3283. }
  3284. return member;
  3285. };
  3286. return {
  3287. load: load,
  3288. parse: parse,
  3289. setPreferredShading: setPreferredShading,
  3290. applySkin: applySkin,
  3291. geometries : geometries,
  3292. options: options
  3293. };
  3294. };