2
0

ColladaLoader.js 98 KB

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