2
0

ColladaLoader.js 98 KB

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