ColladaLoader.js 98 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504
  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. THREE.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. THREE.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. THREE.log( "could not find skin controller!" );
  283. return;
  284. }
  285. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  286. THREE.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. THREE.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. THREE.log( 'ColladaLoader: Could not find skin controller.' );
  428. return;
  429. }
  430. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  431. THREE.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. THREE.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. THREE.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. THREE.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  549. } else if ( joint.static ) {
  550. THREE.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. THREE.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. THREE.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. THREE.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. }
  729. if ( skinController !== undefined ) {
  730. applySkin( geom, skinController );
  731. if ( geom.morphTargets.length > 0 ) {
  732. material.morphTargets = true;
  733. material.skinning = false;
  734. } else {
  735. material.morphTargets = false;
  736. material.skinning = true;
  737. }
  738. mesh = new THREE.SkinnedMesh( geom, material, false );
  739. //mesh.skeleton = skinController.skeleton;
  740. //mesh.skinController = controllers[ skinController.url ];
  741. //mesh.skinInstanceController = skinController;
  742. mesh.name = 'skin_' + skins.length;
  743. //mesh.animationHandle.setKey(0);
  744. skins.push( mesh );
  745. } else if ( morphController !== undefined ) {
  746. createMorph( geom, morphController );
  747. material.morphTargets = true;
  748. mesh = new THREE.Mesh( geom, material );
  749. mesh.name = 'morph_' + morphs.length;
  750. morphs.push( mesh );
  751. } else {
  752. if ( geom.isLineStrip === true ) {
  753. mesh = new THREE.Line( geom );
  754. } else {
  755. mesh = new THREE.Mesh( geom, material );
  756. }
  757. }
  758. obj.add(mesh);
  759. }
  760. }
  761. for ( i = 0; i < node.cameras.length; i ++ ) {
  762. var instance_camera = node.cameras[i];
  763. var cparams = cameras[instance_camera.url];
  764. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  765. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  766. obj.add(cam);
  767. }
  768. for ( i = 0; i < node.lights.length; i ++ ) {
  769. var light = null;
  770. var instance_light = node.lights[i];
  771. var lparams = lights[instance_light.url];
  772. if ( lparams && lparams.technique ) {
  773. var color = lparams.color.getHex();
  774. var intensity = lparams.intensity;
  775. var distance = lparams.distance;
  776. var angle = lparams.falloff_angle;
  777. var exponent; // Intentionally undefined, don't know what this is yet
  778. switch ( lparams.technique ) {
  779. case 'directional':
  780. light = new THREE.DirectionalLight( color, intensity, distance );
  781. light.position.set(0, 0, 1);
  782. break;
  783. case 'point':
  784. light = new THREE.PointLight( color, intensity, distance );
  785. break;
  786. case 'spot':
  787. light = new THREE.SpotLight( color, intensity, distance, angle, exponent );
  788. light.position.set(0, 0, 1);
  789. break;
  790. case 'ambient':
  791. light = new THREE.AmbientLight( color );
  792. break;
  793. }
  794. }
  795. if (light) {
  796. obj.add(light);
  797. }
  798. }
  799. obj.name = node.name || node.id || "";
  800. obj.colladaId = node.id || "";
  801. obj.layer = node.layer || "";
  802. obj.matrix = node.matrix;
  803. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  804. if ( options.centerGeometry && obj.geometry ) {
  805. var delta = obj.geometry.center();
  806. delta.multiply( obj.scale );
  807. delta.applyQuaternion( obj.quaternion );
  808. obj.position.sub( delta );
  809. }
  810. for ( i = 0; i < node.nodes.length; i ++ ) {
  811. obj.add( createSceneGraph( node.nodes[i], node ) );
  812. }
  813. return obj;
  814. }
  815. function getJointId( skin, id ) {
  816. for ( var i = 0; i < skin.joints.length; i ++ ) {
  817. if ( skin.joints[ i ] === id ) {
  818. return i;
  819. }
  820. }
  821. }
  822. function getLibraryNode( id ) {
  823. var nodes = COLLADA.querySelectorAll('library_nodes node');
  824. for ( var i = 0; i < nodes.length; i++ ) {
  825. var attObj = nodes[i].attributes.getNamedItem('id');
  826. if ( attObj && attObj.value === id ) {
  827. return nodes[i];
  828. }
  829. }
  830. return undefined;
  831. }
  832. function getChannelsForNode ( node ) {
  833. var channels = [];
  834. var startTime = 1000000;
  835. var endTime = -1000000;
  836. for ( var id in animations ) {
  837. var animation = animations[id];
  838. for ( var i = 0; i < animation.channel.length; i ++ ) {
  839. var channel = animation.channel[i];
  840. var sampler = animation.sampler[i];
  841. var id = channel.target.split('/')[0];
  842. if ( id == node.id ) {
  843. sampler.create();
  844. channel.sampler = sampler;
  845. startTime = Math.min(startTime, sampler.startTime);
  846. endTime = Math.max(endTime, sampler.endTime);
  847. channels.push(channel);
  848. }
  849. }
  850. }
  851. if ( channels.length ) {
  852. node.startTime = startTime;
  853. node.endTime = endTime;
  854. }
  855. return channels;
  856. }
  857. function calcFrameDuration( node ) {
  858. var minT = 10000000;
  859. for ( var i = 0; i < node.channels.length; i ++ ) {
  860. var sampler = node.channels[i].sampler;
  861. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  862. var t0 = sampler.input[ j ];
  863. var t1 = sampler.input[ j + 1 ];
  864. minT = Math.min( minT, t1 - t0 );
  865. }
  866. }
  867. return minT;
  868. }
  869. function calcMatrixAt( node, t ) {
  870. var animated = {};
  871. var i, j;
  872. for ( i = 0; i < node.channels.length; i ++ ) {
  873. var channel = node.channels[ i ];
  874. animated[ channel.sid ] = channel;
  875. }
  876. var matrix = new THREE.Matrix4();
  877. for ( i = 0; i < node.transforms.length; i ++ ) {
  878. var transform = node.transforms[ i ];
  879. var channel = animated[ transform.sid ];
  880. if ( channel !== undefined ) {
  881. var sampler = channel.sampler;
  882. var value;
  883. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  884. if ( sampler.input[ j + 1 ] > t ) {
  885. value = sampler.output[ j ];
  886. //THREE.log(value.flatten)
  887. break;
  888. }
  889. }
  890. if ( value !== undefined ) {
  891. if ( value instanceof THREE.Matrix4 ) {
  892. matrix.multiplyMatrices( matrix, value );
  893. } else {
  894. // FIXME: handle other types
  895. matrix.multiplyMatrices( matrix, transform.matrix );
  896. }
  897. } else {
  898. matrix.multiplyMatrices( matrix, transform.matrix );
  899. }
  900. } else {
  901. matrix.multiplyMatrices( matrix, transform.matrix );
  902. }
  903. }
  904. return matrix;
  905. }
  906. function bakeAnimations ( node ) {
  907. if ( node.channels && node.channels.length ) {
  908. var keys = [],
  909. sids = [];
  910. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  911. var channel = node.channels[i],
  912. fullSid = channel.fullSid,
  913. sampler = channel.sampler,
  914. input = sampler.input,
  915. transform = node.getTransformBySid( channel.sid ),
  916. member;
  917. if ( channel.arrIndices ) {
  918. member = [];
  919. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  920. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  921. }
  922. } else {
  923. member = getConvertedMember( channel.member );
  924. }
  925. if ( transform ) {
  926. if ( sids.indexOf( fullSid ) === -1 ) {
  927. sids.push( fullSid );
  928. }
  929. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  930. var time = input[j],
  931. data = sampler.getData( transform.type, j, member ),
  932. key = findKey( keys, time );
  933. if ( !key ) {
  934. key = new Key( time );
  935. var timeNdx = findTimeNdx( keys, time );
  936. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  937. }
  938. key.addTarget( fullSid, transform, member, data );
  939. }
  940. } else {
  941. THREE.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  942. }
  943. }
  944. // post process
  945. for ( var i = 0; i < sids.length; i ++ ) {
  946. var sid = sids[ i ];
  947. for ( var j = 0; j < keys.length; j ++ ) {
  948. var key = keys[ j ];
  949. if ( !key.hasTarget( sid ) ) {
  950. interpolateKeys( keys, key, j, sid );
  951. }
  952. }
  953. }
  954. node.keys = keys;
  955. node.sids = sids;
  956. }
  957. }
  958. function findKey ( keys, time) {
  959. var retVal = null;
  960. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  961. var key = keys[i];
  962. if ( key.time === time ) {
  963. retVal = key;
  964. } else if ( key.time > time ) {
  965. break;
  966. }
  967. }
  968. return retVal;
  969. }
  970. function findTimeNdx ( keys, time) {
  971. var ndx = -1;
  972. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  973. var key = keys[i];
  974. if ( key.time >= time ) {
  975. ndx = i;
  976. }
  977. }
  978. return ndx;
  979. }
  980. function interpolateKeys ( keys, key, ndx, fullSid ) {
  981. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  982. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  983. if ( prevKey && nextKey ) {
  984. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  985. prevTarget = prevKey.getTarget( fullSid ),
  986. nextData = nextKey.getTarget( fullSid ).data,
  987. prevData = prevTarget.data,
  988. data;
  989. if ( prevTarget.type === 'matrix' ) {
  990. data = prevData;
  991. } else if ( prevData.length ) {
  992. data = [];
  993. for ( var i = 0; i < prevData.length; ++ i ) {
  994. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  995. }
  996. } else {
  997. data = prevData + ( nextData - prevData ) * scale;
  998. }
  999. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  1000. }
  1001. }
  1002. // Get next key with given sid
  1003. function getNextKeyWith( keys, fullSid, ndx ) {
  1004. for ( ; ndx < keys.length; ndx ++ ) {
  1005. var key = keys[ ndx ];
  1006. if ( key.hasTarget( fullSid ) ) {
  1007. return key;
  1008. }
  1009. }
  1010. return null;
  1011. }
  1012. // Get previous key with given sid
  1013. function getPrevKeyWith( keys, fullSid, ndx ) {
  1014. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  1015. for ( ; ndx >= 0; ndx -- ) {
  1016. var key = keys[ ndx ];
  1017. if ( key.hasTarget( fullSid ) ) {
  1018. return key;
  1019. }
  1020. }
  1021. return null;
  1022. }
  1023. function _Image() {
  1024. this.id = "";
  1025. this.init_from = "";
  1026. }
  1027. _Image.prototype.parse = function(element) {
  1028. this.id = element.getAttribute('id');
  1029. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1030. var child = element.childNodes[ i ];
  1031. if ( child.nodeName === 'init_from' ) {
  1032. this.init_from = child.textContent;
  1033. }
  1034. }
  1035. return this;
  1036. };
  1037. function Controller() {
  1038. this.id = "";
  1039. this.name = "";
  1040. this.type = "";
  1041. this.skin = null;
  1042. this.morph = null;
  1043. }
  1044. Controller.prototype.parse = function( element ) {
  1045. this.id = element.getAttribute('id');
  1046. this.name = element.getAttribute('name');
  1047. this.type = "none";
  1048. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1049. var child = element.childNodes[ i ];
  1050. switch ( child.nodeName ) {
  1051. case 'skin':
  1052. this.skin = (new Skin()).parse(child);
  1053. this.type = child.nodeName;
  1054. break;
  1055. case 'morph':
  1056. this.morph = (new Morph()).parse(child);
  1057. this.type = child.nodeName;
  1058. break;
  1059. default:
  1060. break;
  1061. }
  1062. }
  1063. return this;
  1064. };
  1065. function Morph() {
  1066. this.method = null;
  1067. this.source = null;
  1068. this.targets = null;
  1069. this.weights = null;
  1070. }
  1071. Morph.prototype.parse = function( element ) {
  1072. var sources = {};
  1073. var inputs = [];
  1074. var i;
  1075. this.method = element.getAttribute( 'method' );
  1076. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1077. for ( i = 0; i < element.childNodes.length; i ++ ) {
  1078. var child = element.childNodes[ i ];
  1079. if ( child.nodeType != 1 ) continue;
  1080. switch ( child.nodeName ) {
  1081. case 'source':
  1082. var source = ( new Source() ).parse( child );
  1083. sources[ source.id ] = source;
  1084. break;
  1085. case 'targets':
  1086. inputs = this.parseInputs( child );
  1087. break;
  1088. default:
  1089. THREE.log( child.nodeName );
  1090. break;
  1091. }
  1092. }
  1093. for ( i = 0; i < inputs.length; i ++ ) {
  1094. var input = inputs[ i ];
  1095. var source = sources[ input.source ];
  1096. switch ( input.semantic ) {
  1097. case 'MORPH_TARGET':
  1098. this.targets = source.read();
  1099. break;
  1100. case 'MORPH_WEIGHT':
  1101. this.weights = source.read();
  1102. break;
  1103. default:
  1104. break;
  1105. }
  1106. }
  1107. return this;
  1108. };
  1109. Morph.prototype.parseInputs = function(element) {
  1110. var inputs = [];
  1111. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1112. var child = element.childNodes[i];
  1113. if ( child.nodeType != 1) continue;
  1114. switch ( child.nodeName ) {
  1115. case 'input':
  1116. inputs.push( (new Input()).parse(child) );
  1117. break;
  1118. default:
  1119. break;
  1120. }
  1121. }
  1122. return inputs;
  1123. };
  1124. function Skin() {
  1125. this.source = "";
  1126. this.bindShapeMatrix = null;
  1127. this.invBindMatrices = [];
  1128. this.joints = [];
  1129. this.weights = [];
  1130. }
  1131. Skin.prototype.parse = function( element ) {
  1132. var sources = {};
  1133. var joints, weights;
  1134. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1135. this.invBindMatrices = [];
  1136. this.joints = [];
  1137. this.weights = [];
  1138. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1139. var child = element.childNodes[i];
  1140. if ( child.nodeType != 1 ) continue;
  1141. switch ( child.nodeName ) {
  1142. case 'bind_shape_matrix':
  1143. var f = _floats(child.textContent);
  1144. this.bindShapeMatrix = getConvertedMat4( f );
  1145. break;
  1146. case 'source':
  1147. var src = new Source().parse(child);
  1148. sources[ src.id ] = src;
  1149. break;
  1150. case 'joints':
  1151. joints = child;
  1152. break;
  1153. case 'vertex_weights':
  1154. weights = child;
  1155. break;
  1156. default:
  1157. THREE.log( child.nodeName );
  1158. break;
  1159. }
  1160. }
  1161. this.parseJoints( joints, sources );
  1162. this.parseWeights( weights, sources );
  1163. return this;
  1164. };
  1165. Skin.prototype.parseJoints = function ( element, sources ) {
  1166. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1167. var child = element.childNodes[ i ];
  1168. if ( child.nodeType != 1 ) continue;
  1169. switch ( child.nodeName ) {
  1170. case 'input':
  1171. var input = ( new Input() ).parse( child );
  1172. var source = sources[ input.source ];
  1173. if ( input.semantic === 'JOINT' ) {
  1174. this.joints = source.read();
  1175. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  1176. this.invBindMatrices = source.read();
  1177. }
  1178. break;
  1179. default:
  1180. break;
  1181. }
  1182. }
  1183. };
  1184. Skin.prototype.parseWeights = function ( element, sources ) {
  1185. var v, vcount, inputs = [];
  1186. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1187. var child = element.childNodes[ i ];
  1188. if ( child.nodeType != 1 ) continue;
  1189. switch ( child.nodeName ) {
  1190. case 'input':
  1191. inputs.push( ( new Input() ).parse( child ) );
  1192. break;
  1193. case 'v':
  1194. v = _ints( child.textContent );
  1195. break;
  1196. case 'vcount':
  1197. vcount = _ints( child.textContent );
  1198. break;
  1199. default:
  1200. break;
  1201. }
  1202. }
  1203. var index = 0;
  1204. for ( var i = 0; i < vcount.length; i ++ ) {
  1205. var numBones = vcount[i];
  1206. var vertex_weights = [];
  1207. for ( var j = 0; j < numBones; j ++ ) {
  1208. var influence = {};
  1209. for ( var k = 0; k < inputs.length; k ++ ) {
  1210. var input = inputs[ k ];
  1211. var value = v[ index + input.offset ];
  1212. switch ( input.semantic ) {
  1213. case 'JOINT':
  1214. influence.joint = value;//this.joints[value];
  1215. break;
  1216. case 'WEIGHT':
  1217. influence.weight = sources[ input.source ].data[ value ];
  1218. break;
  1219. default:
  1220. break;
  1221. }
  1222. }
  1223. vertex_weights.push( influence );
  1224. index += inputs.length;
  1225. }
  1226. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  1227. vertex_weights[ j ].index = i;
  1228. }
  1229. this.weights.push( vertex_weights );
  1230. }
  1231. };
  1232. function VisualScene () {
  1233. this.id = "";
  1234. this.name = "";
  1235. this.nodes = [];
  1236. this.scene = new THREE.Group();
  1237. }
  1238. VisualScene.prototype.getChildById = function( id, recursive ) {
  1239. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1240. var node = this.nodes[ i ].getChildById( id, recursive );
  1241. if ( node ) {
  1242. return node;
  1243. }
  1244. }
  1245. return null;
  1246. };
  1247. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  1248. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1249. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  1250. if ( node ) {
  1251. return node;
  1252. }
  1253. }
  1254. return null;
  1255. };
  1256. VisualScene.prototype.parse = function( element ) {
  1257. this.id = element.getAttribute( 'id' );
  1258. this.name = element.getAttribute( 'name' );
  1259. this.nodes = [];
  1260. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1261. var child = element.childNodes[ i ];
  1262. if ( child.nodeType != 1 ) continue;
  1263. switch ( child.nodeName ) {
  1264. case 'node':
  1265. this.nodes.push( ( new Node() ).parse( child ) );
  1266. break;
  1267. default:
  1268. break;
  1269. }
  1270. }
  1271. return this;
  1272. };
  1273. function Node() {
  1274. this.id = "";
  1275. this.name = "";
  1276. this.sid = "";
  1277. this.nodes = [];
  1278. this.controllers = [];
  1279. this.transforms = [];
  1280. this.geometries = [];
  1281. this.channels = [];
  1282. this.matrix = new THREE.Matrix4();
  1283. }
  1284. Node.prototype.getChannelForTransform = function( transformSid ) {
  1285. for ( var i = 0; i < this.channels.length; i ++ ) {
  1286. var channel = this.channels[i];
  1287. var parts = channel.target.split('/');
  1288. var id = parts.shift();
  1289. var sid = parts.shift();
  1290. var dotSyntax = (sid.indexOf(".") >= 0);
  1291. var arrSyntax = (sid.indexOf("(") >= 0);
  1292. var arrIndices;
  1293. var member;
  1294. if ( dotSyntax ) {
  1295. parts = sid.split(".");
  1296. sid = parts.shift();
  1297. member = parts.shift();
  1298. } else if ( arrSyntax ) {
  1299. arrIndices = sid.split("(");
  1300. sid = arrIndices.shift();
  1301. for ( var j = 0; j < arrIndices.length; j ++ ) {
  1302. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  1303. }
  1304. }
  1305. if ( sid === transformSid ) {
  1306. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  1307. return channel;
  1308. }
  1309. }
  1310. return null;
  1311. };
  1312. Node.prototype.getChildById = function ( id, recursive ) {
  1313. if ( this.id === id ) {
  1314. return this;
  1315. }
  1316. if ( recursive ) {
  1317. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1318. var n = this.nodes[ i ].getChildById( id, recursive );
  1319. if ( n ) {
  1320. return n;
  1321. }
  1322. }
  1323. }
  1324. return null;
  1325. };
  1326. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1327. if ( this.sid === sid ) {
  1328. return this;
  1329. }
  1330. if ( recursive ) {
  1331. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1332. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1333. if ( n ) {
  1334. return n;
  1335. }
  1336. }
  1337. }
  1338. return null;
  1339. };
  1340. Node.prototype.getTransformBySid = function ( sid ) {
  1341. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1342. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  1343. }
  1344. return null;
  1345. };
  1346. Node.prototype.parse = function( element ) {
  1347. var url;
  1348. this.id = element.getAttribute('id');
  1349. this.sid = element.getAttribute('sid');
  1350. this.name = element.getAttribute('name');
  1351. this.type = element.getAttribute('type');
  1352. this.layer = element.getAttribute('layer');
  1353. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  1354. this.nodes = [];
  1355. this.transforms = [];
  1356. this.geometries = [];
  1357. this.cameras = [];
  1358. this.lights = [];
  1359. this.controllers = [];
  1360. this.matrix = new THREE.Matrix4();
  1361. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1362. var child = element.childNodes[ i ];
  1363. if ( child.nodeType != 1 ) continue;
  1364. switch ( child.nodeName ) {
  1365. case 'node':
  1366. this.nodes.push( ( new Node() ).parse( child ) );
  1367. break;
  1368. case 'instance_camera':
  1369. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1370. break;
  1371. case 'instance_controller':
  1372. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1373. break;
  1374. case 'instance_geometry':
  1375. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1376. break;
  1377. case 'instance_light':
  1378. this.lights.push( ( new InstanceLight() ).parse( child ) );
  1379. break;
  1380. case 'instance_node':
  1381. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1382. var iNode = getLibraryNode( url );
  1383. if ( iNode ) {
  1384. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1385. }
  1386. break;
  1387. case 'rotate':
  1388. case 'translate':
  1389. case 'scale':
  1390. case 'matrix':
  1391. case 'lookat':
  1392. case 'skew':
  1393. this.transforms.push( ( new Transform() ).parse( child ) );
  1394. break;
  1395. case 'extra':
  1396. break;
  1397. default:
  1398. THREE.log( child.nodeName );
  1399. break;
  1400. }
  1401. }
  1402. this.channels = getChannelsForNode( this );
  1403. bakeAnimations( this );
  1404. this.updateMatrix();
  1405. return this;
  1406. };
  1407. Node.prototype.updateMatrix = function () {
  1408. this.matrix.identity();
  1409. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1410. this.transforms[ i ].apply( this.matrix );
  1411. }
  1412. };
  1413. function Transform () {
  1414. this.sid = "";
  1415. this.type = "";
  1416. this.data = [];
  1417. this.obj = null;
  1418. }
  1419. Transform.prototype.parse = function ( element ) {
  1420. this.sid = element.getAttribute( 'sid' );
  1421. this.type = element.nodeName;
  1422. this.data = _floats( element.textContent );
  1423. this.convert();
  1424. return this;
  1425. };
  1426. Transform.prototype.convert = function () {
  1427. switch ( this.type ) {
  1428. case 'matrix':
  1429. this.obj = getConvertedMat4( this.data );
  1430. break;
  1431. case 'rotate':
  1432. this.angle = THREE.Math.degToRad( this.data[3] );
  1433. case 'translate':
  1434. fixCoords( this.data, -1 );
  1435. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1436. break;
  1437. case 'scale':
  1438. fixCoords( this.data, 1 );
  1439. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1440. break;
  1441. default:
  1442. THREE.log( 'Can not convert Transform of type ' + this.type );
  1443. break;
  1444. }
  1445. };
  1446. Transform.prototype.apply = function () {
  1447. var m1 = new THREE.Matrix4();
  1448. return function ( matrix ) {
  1449. switch ( this.type ) {
  1450. case 'matrix':
  1451. matrix.multiply( this.obj );
  1452. break;
  1453. case 'translate':
  1454. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  1455. break;
  1456. case 'rotate':
  1457. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  1458. break;
  1459. case 'scale':
  1460. matrix.scale( this.obj );
  1461. break;
  1462. }
  1463. };
  1464. }();
  1465. Transform.prototype.update = function ( data, member ) {
  1466. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1467. switch ( this.type ) {
  1468. case 'matrix':
  1469. if ( ! member ) {
  1470. this.obj.copy( data );
  1471. } else if ( member.length === 1 ) {
  1472. switch ( member[ 0 ] ) {
  1473. case 0:
  1474. this.obj.n11 = data[ 0 ];
  1475. this.obj.n21 = data[ 1 ];
  1476. this.obj.n31 = data[ 2 ];
  1477. this.obj.n41 = data[ 3 ];
  1478. break;
  1479. case 1:
  1480. this.obj.n12 = data[ 0 ];
  1481. this.obj.n22 = data[ 1 ];
  1482. this.obj.n32 = data[ 2 ];
  1483. this.obj.n42 = data[ 3 ];
  1484. break;
  1485. case 2:
  1486. this.obj.n13 = data[ 0 ];
  1487. this.obj.n23 = data[ 1 ];
  1488. this.obj.n33 = data[ 2 ];
  1489. this.obj.n43 = data[ 3 ];
  1490. break;
  1491. case 3:
  1492. this.obj.n14 = data[ 0 ];
  1493. this.obj.n24 = data[ 1 ];
  1494. this.obj.n34 = data[ 2 ];
  1495. this.obj.n44 = data[ 3 ];
  1496. break;
  1497. }
  1498. } else if ( member.length === 2 ) {
  1499. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1500. this.obj[ propName ] = data;
  1501. } else {
  1502. THREE.log('Incorrect addressing of matrix in transform.');
  1503. }
  1504. break;
  1505. case 'translate':
  1506. case 'scale':
  1507. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1508. member = members[ member[ 0 ] ];
  1509. }
  1510. switch ( member ) {
  1511. case 'X':
  1512. this.obj.x = data;
  1513. break;
  1514. case 'Y':
  1515. this.obj.y = data;
  1516. break;
  1517. case 'Z':
  1518. this.obj.z = data;
  1519. break;
  1520. default:
  1521. this.obj.x = data[ 0 ];
  1522. this.obj.y = data[ 1 ];
  1523. this.obj.z = data[ 2 ];
  1524. break;
  1525. }
  1526. break;
  1527. case 'rotate':
  1528. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1529. member = members[ member[ 0 ] ];
  1530. }
  1531. switch ( member ) {
  1532. case 'X':
  1533. this.obj.x = data;
  1534. break;
  1535. case 'Y':
  1536. this.obj.y = data;
  1537. break;
  1538. case 'Z':
  1539. this.obj.z = data;
  1540. break;
  1541. case 'ANGLE':
  1542. this.angle = THREE.Math.degToRad( data );
  1543. break;
  1544. default:
  1545. this.obj.x = data[ 0 ];
  1546. this.obj.y = data[ 1 ];
  1547. this.obj.z = data[ 2 ];
  1548. this.angle = THREE.Math.degToRad( data[ 3 ] );
  1549. break;
  1550. }
  1551. break;
  1552. }
  1553. };
  1554. function InstanceController() {
  1555. this.url = "";
  1556. this.skeleton = [];
  1557. this.instance_material = [];
  1558. }
  1559. InstanceController.prototype.parse = function ( element ) {
  1560. this.url = element.getAttribute('url').replace(/^#/, '');
  1561. this.skeleton = [];
  1562. this.instance_material = [];
  1563. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1564. var child = element.childNodes[ i ];
  1565. if ( child.nodeType !== 1 ) continue;
  1566. switch ( child.nodeName ) {
  1567. case 'skeleton':
  1568. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1569. break;
  1570. case 'bind_material':
  1571. var instances = child.querySelectorAll('instance_material');
  1572. for ( var j = 0; j < instances.length; j ++ ) {
  1573. var instance = instances[j];
  1574. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1575. }
  1576. break;
  1577. case 'extra':
  1578. break;
  1579. default:
  1580. break;
  1581. }
  1582. }
  1583. return this;
  1584. };
  1585. function InstanceMaterial () {
  1586. this.symbol = "";
  1587. this.target = "";
  1588. }
  1589. InstanceMaterial.prototype.parse = function ( element ) {
  1590. this.symbol = element.getAttribute('symbol');
  1591. this.target = element.getAttribute('target').replace(/^#/, '');
  1592. return this;
  1593. };
  1594. function InstanceGeometry() {
  1595. this.url = "";
  1596. this.instance_material = [];
  1597. }
  1598. InstanceGeometry.prototype.parse = function ( element ) {
  1599. this.url = element.getAttribute('url').replace(/^#/, '');
  1600. this.instance_material = [];
  1601. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1602. var child = element.childNodes[i];
  1603. if ( child.nodeType != 1 ) continue;
  1604. if ( child.nodeName === 'bind_material' ) {
  1605. var instances = child.querySelectorAll('instance_material');
  1606. for ( var j = 0; j < instances.length; j ++ ) {
  1607. var instance = instances[j];
  1608. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1609. }
  1610. break;
  1611. }
  1612. }
  1613. return this;
  1614. };
  1615. function Geometry() {
  1616. this.id = "";
  1617. this.mesh = null;
  1618. }
  1619. Geometry.prototype.parse = function ( element ) {
  1620. this.id = element.getAttribute('id');
  1621. extractDoubleSided( this, element );
  1622. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1623. var child = element.childNodes[i];
  1624. switch ( child.nodeName ) {
  1625. case 'mesh':
  1626. this.mesh = (new Mesh(this)).parse(child);
  1627. break;
  1628. case 'extra':
  1629. // THREE.log( child );
  1630. break;
  1631. default:
  1632. break;
  1633. }
  1634. }
  1635. return this;
  1636. };
  1637. function Mesh( geometry ) {
  1638. this.geometry = geometry.id;
  1639. this.primitives = [];
  1640. this.vertices = null;
  1641. this.geometry3js = null;
  1642. }
  1643. Mesh.prototype.parse = function ( element ) {
  1644. this.primitives = [];
  1645. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1646. var child = element.childNodes[ i ];
  1647. switch ( child.nodeName ) {
  1648. case 'source':
  1649. _source( child );
  1650. break;
  1651. case 'vertices':
  1652. this.vertices = ( new Vertices() ).parse( child );
  1653. break;
  1654. case 'linestrips':
  1655. this.primitives.push( ( new LineStrips().parse( child ) ) );
  1656. break;
  1657. case 'triangles':
  1658. this.primitives.push( ( new Triangles().parse( child ) ) );
  1659. break;
  1660. case 'polygons':
  1661. this.primitives.push( ( new Polygons().parse( child ) ) );
  1662. break;
  1663. case 'polylist':
  1664. this.primitives.push( ( new Polylist().parse( child ) ) );
  1665. break;
  1666. default:
  1667. break;
  1668. }
  1669. }
  1670. this.geometry3js = new THREE.Geometry();
  1671. if ( this.vertices === null ) {
  1672. // TODO (mrdoob): Study case when this is null (carrier.dae)
  1673. return this;
  1674. }
  1675. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1676. for ( var i = 0; i < vertexData.length; i += 3 ) {
  1677. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1678. }
  1679. for ( var i = 0; i < this.primitives.length; i ++ ) {
  1680. var primitive = this.primitives[ i ];
  1681. primitive.setVertices( this.vertices );
  1682. this.handlePrimitive( primitive, this.geometry3js );
  1683. }
  1684. if ( this.geometry3js.calcNormals ) {
  1685. this.geometry3js.computeVertexNormals();
  1686. delete this.geometry3js.calcNormals;
  1687. }
  1688. return this;
  1689. };
  1690. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  1691. if ( primitive instanceof LineStrips ) {
  1692. // TODO: Handle indices. Maybe easier with BufferGeometry?
  1693. geom.isLineStrip = true;
  1694. return;
  1695. }
  1696. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1697. var input, index, idx32;
  1698. var source, numParams;
  1699. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1700. var texture_sets = [];
  1701. for ( j = 0; j < inputs.length; j ++ ) {
  1702. input = inputs[ j ];
  1703. var offset = input.offset + 1;
  1704. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  1705. switch ( input.semantic ) {
  1706. case 'TEXCOORD':
  1707. texture_sets.push( input.set );
  1708. break;
  1709. }
  1710. }
  1711. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  1712. var p = pList[ pCount ], i = 0;
  1713. while ( i < p.length ) {
  1714. var vs = [];
  1715. var ns = [];
  1716. var ts = null;
  1717. var cs = [];
  1718. if ( primitive.vcount ) {
  1719. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1720. } else {
  1721. vcount = p.length / maxOffset;
  1722. }
  1723. for ( j = 0; j < vcount; j ++ ) {
  1724. for ( k = 0; k < inputs.length; k ++ ) {
  1725. input = inputs[ k ];
  1726. source = sources[ input.source ];
  1727. index = p[ i + ( j * maxOffset ) + input.offset ];
  1728. numParams = source.accessor.params.length;
  1729. idx32 = index * numParams;
  1730. switch ( input.semantic ) {
  1731. case 'VERTEX':
  1732. vs.push( index );
  1733. break;
  1734. case 'NORMAL':
  1735. ns.push( getConvertedVec3( source.data, idx32 ) );
  1736. break;
  1737. case 'TEXCOORD':
  1738. ts = ts || { };
  1739. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1740. // invert the V
  1741. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1742. break;
  1743. case 'COLOR':
  1744. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1745. break;
  1746. default:
  1747. break;
  1748. }
  1749. }
  1750. }
  1751. if ( ns.length === 0 ) {
  1752. // check the vertices inputs
  1753. input = this.vertices.input.NORMAL;
  1754. if ( input ) {
  1755. source = sources[ input.source ];
  1756. numParams = source.accessor.params.length;
  1757. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1758. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1759. }
  1760. } else {
  1761. geom.calcNormals = true;
  1762. }
  1763. }
  1764. if ( !ts ) {
  1765. ts = { };
  1766. // check the vertices inputs
  1767. input = this.vertices.input.TEXCOORD;
  1768. if ( input ) {
  1769. texture_sets.push( input.set );
  1770. source = sources[ input.source ];
  1771. numParams = source.accessor.params.length;
  1772. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1773. idx32 = vs[ ndx ] * numParams;
  1774. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1775. // invert the V
  1776. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1777. }
  1778. }
  1779. }
  1780. if ( cs.length === 0 ) {
  1781. // check the vertices inputs
  1782. input = this.vertices.input.COLOR;
  1783. if ( input ) {
  1784. source = sources[ input.source ];
  1785. numParams = source.accessor.params.length;
  1786. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1787. idx32 = vs[ ndx ] * numParams;
  1788. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1789. }
  1790. }
  1791. }
  1792. var face = null, faces = [], uv, uvArr;
  1793. if ( vcount === 3 ) {
  1794. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1795. } else if ( vcount === 4 ) {
  1796. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], [ ns[0].clone(), ns[1].clone(), ns[3].clone() ], cs.length ? [ cs[0], cs[1], cs[3] ] : new THREE.Color() ) );
  1797. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], [ ns[1].clone(), ns[2].clone(), ns[3].clone() ], cs.length ? [ cs[1], cs[2], cs[3] ] : new THREE.Color() ) );
  1798. } else if ( vcount > 4 && options.subdivideFaces ) {
  1799. var clr = cs.length ? cs : new THREE.Color(),
  1800. vec1, vec2, vec3, v1, v2, norm;
  1801. // subdivide into multiple Face3s
  1802. for ( k = 1; k < vcount - 1; ) {
  1803. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ], clr ) );
  1804. }
  1805. }
  1806. if ( faces.length ) {
  1807. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  1808. face = faces[ndx];
  1809. face.daeMaterial = primitive.material;
  1810. geom.faces.push( face );
  1811. for ( k = 0; k < texture_sets.length; k ++ ) {
  1812. uv = ts[ texture_sets[k] ];
  1813. if ( vcount > 4 ) {
  1814. // Grab the right UVs for the vertices in this face
  1815. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  1816. } else if ( vcount === 4 ) {
  1817. if ( ndx === 0 ) {
  1818. uvArr = [ uv[0], uv[1], uv[3] ];
  1819. } else {
  1820. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  1821. }
  1822. } else {
  1823. uvArr = [ uv[0], uv[1], uv[2] ];
  1824. }
  1825. if ( geom.faceVertexUvs[k] === undefined ) {
  1826. geom.faceVertexUvs[k] = [];
  1827. }
  1828. geom.faceVertexUvs[k].push( uvArr );
  1829. }
  1830. }
  1831. } else {
  1832. THREE.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1833. }
  1834. i += maxOffset * vcount;
  1835. }
  1836. }
  1837. };
  1838. function Polygons () {
  1839. this.material = "";
  1840. this.count = 0;
  1841. this.inputs = [];
  1842. this.vcount = null;
  1843. this.p = [];
  1844. this.geometry = new THREE.Geometry();
  1845. }
  1846. Polygons.prototype.setVertices = function ( vertices ) {
  1847. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1848. if ( this.inputs[ i ].source === vertices.id ) {
  1849. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1850. }
  1851. }
  1852. };
  1853. Polygons.prototype.parse = function ( element ) {
  1854. this.material = element.getAttribute( 'material' );
  1855. this.count = _attr_as_int( element, 'count', 0 );
  1856. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1857. var child = element.childNodes[ i ];
  1858. switch ( child.nodeName ) {
  1859. case 'input':
  1860. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1861. break;
  1862. case 'vcount':
  1863. this.vcount = _ints( child.textContent );
  1864. break;
  1865. case 'p':
  1866. this.p.push( _ints( child.textContent ) );
  1867. break;
  1868. case 'ph':
  1869. THREE.warn( 'polygon holes not yet supported!' );
  1870. break;
  1871. default:
  1872. break;
  1873. }
  1874. }
  1875. return this;
  1876. };
  1877. function Polylist () {
  1878. Polygons.call( this );
  1879. this.vcount = [];
  1880. }
  1881. Polylist.prototype = Object.create( Polygons.prototype );
  1882. Polylist.prototype.constructor = Polylist;
  1883. function LineStrips() {
  1884. Polygons.call( this );
  1885. this.vcount = 1;
  1886. }
  1887. LineStrips.prototype = Object.create( Polygons.prototype );
  1888. LineStrips.prototype.constructor = LineStrips;
  1889. function Triangles () {
  1890. Polygons.call( this );
  1891. this.vcount = 3;
  1892. }
  1893. Triangles.prototype = Object.create( Polygons.prototype );
  1894. Triangles.prototype.constructor = Triangles;
  1895. function Accessor() {
  1896. this.source = "";
  1897. this.count = 0;
  1898. this.stride = 0;
  1899. this.params = [];
  1900. }
  1901. Accessor.prototype.parse = function ( element ) {
  1902. this.params = [];
  1903. this.source = element.getAttribute( 'source' );
  1904. this.count = _attr_as_int( element, 'count', 0 );
  1905. this.stride = _attr_as_int( element, 'stride', 0 );
  1906. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1907. var child = element.childNodes[ i ];
  1908. if ( child.nodeName === 'param' ) {
  1909. var param = {};
  1910. param[ 'name' ] = child.getAttribute( 'name' );
  1911. param[ 'type' ] = child.getAttribute( 'type' );
  1912. this.params.push( param );
  1913. }
  1914. }
  1915. return this;
  1916. };
  1917. function Vertices() {
  1918. this.input = {};
  1919. }
  1920. Vertices.prototype.parse = function ( element ) {
  1921. this.id = element.getAttribute('id');
  1922. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1923. if ( element.childNodes[i].nodeName === 'input' ) {
  1924. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1925. this.input[ input.semantic ] = input;
  1926. }
  1927. }
  1928. return this;
  1929. };
  1930. function Input () {
  1931. this.semantic = "";
  1932. this.offset = 0;
  1933. this.source = "";
  1934. this.set = 0;
  1935. }
  1936. Input.prototype.parse = function ( element ) {
  1937. this.semantic = element.getAttribute('semantic');
  1938. this.source = element.getAttribute('source').replace(/^#/, '');
  1939. this.set = _attr_as_int(element, 'set', -1);
  1940. this.offset = _attr_as_int(element, 'offset', 0);
  1941. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  1942. this.set = 0;
  1943. }
  1944. return this;
  1945. };
  1946. function Source ( id ) {
  1947. this.id = id;
  1948. this.type = null;
  1949. }
  1950. Source.prototype.parse = function ( element ) {
  1951. this.id = element.getAttribute( 'id' );
  1952. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1953. var child = element.childNodes[i];
  1954. switch ( child.nodeName ) {
  1955. case 'bool_array':
  1956. this.data = _bools( child.textContent );
  1957. this.type = child.nodeName;
  1958. break;
  1959. case 'float_array':
  1960. this.data = _floats( child.textContent );
  1961. this.type = child.nodeName;
  1962. break;
  1963. case 'int_array':
  1964. this.data = _ints( child.textContent );
  1965. this.type = child.nodeName;
  1966. break;
  1967. case 'IDREF_array':
  1968. case 'Name_array':
  1969. this.data = _strings( child.textContent );
  1970. this.type = child.nodeName;
  1971. break;
  1972. case 'technique_common':
  1973. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1974. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  1975. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1976. break;
  1977. }
  1978. }
  1979. break;
  1980. default:
  1981. // THREE.log(child.nodeName);
  1982. break;
  1983. }
  1984. }
  1985. return this;
  1986. };
  1987. Source.prototype.read = function () {
  1988. var result = [];
  1989. //for (var i = 0; i < this.accessor.params.length; i++) {
  1990. var param = this.accessor.params[ 0 ];
  1991. //THREE.log(param.name + " " + param.type);
  1992. switch ( param.type ) {
  1993. case 'IDREF':
  1994. case 'Name': case 'name':
  1995. case 'float':
  1996. return this.data;
  1997. case 'float4x4':
  1998. for ( var j = 0; j < this.data.length; j += 16 ) {
  1999. var s = this.data.slice( j, j + 16 );
  2000. var m = getConvertedMat4( s );
  2001. result.push( m );
  2002. }
  2003. break;
  2004. default:
  2005. THREE.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  2006. break;
  2007. }
  2008. //}
  2009. return result;
  2010. };
  2011. function Material () {
  2012. this.id = "";
  2013. this.name = "";
  2014. this.instance_effect = null;
  2015. }
  2016. Material.prototype.parse = function ( element ) {
  2017. this.id = element.getAttribute( 'id' );
  2018. this.name = element.getAttribute( 'name' );
  2019. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2020. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  2021. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  2022. break;
  2023. }
  2024. }
  2025. return this;
  2026. };
  2027. function ColorOrTexture () {
  2028. this.color = new THREE.Color();
  2029. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  2030. this.color.a = 1.0;
  2031. this.texture = null;
  2032. this.texcoord = null;
  2033. this.texOpts = null;
  2034. }
  2035. ColorOrTexture.prototype.isColor = function () {
  2036. return ( this.texture === null );
  2037. };
  2038. ColorOrTexture.prototype.isTexture = function () {
  2039. return ( this.texture != null );
  2040. };
  2041. ColorOrTexture.prototype.parse = function ( element ) {
  2042. if (element.nodeName === 'transparent') {
  2043. this.opaque = element.getAttribute('opaque');
  2044. }
  2045. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2046. var child = element.childNodes[ i ];
  2047. if ( child.nodeType != 1 ) continue;
  2048. switch ( child.nodeName ) {
  2049. case 'color':
  2050. var rgba = _floats( child.textContent );
  2051. this.color = new THREE.Color();
  2052. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2053. this.color.a = rgba[3];
  2054. break;
  2055. case 'texture':
  2056. this.texture = child.getAttribute('texture');
  2057. this.texcoord = child.getAttribute('texcoord');
  2058. // Defaults from:
  2059. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  2060. this.texOpts = {
  2061. offsetU: 0,
  2062. offsetV: 0,
  2063. repeatU: 1,
  2064. repeatV: 1,
  2065. wrapU: 1,
  2066. wrapV: 1
  2067. };
  2068. this.parseTexture( child );
  2069. break;
  2070. default:
  2071. break;
  2072. }
  2073. }
  2074. return this;
  2075. };
  2076. ColorOrTexture.prototype.parseTexture = function ( element ) {
  2077. if ( ! element.childNodes ) return this;
  2078. // This should be supported by Maya, 3dsMax, and MotionBuilder
  2079. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  2080. element = element.childNodes[1];
  2081. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  2082. element = element.childNodes[1];
  2083. }
  2084. }
  2085. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2086. var child = element.childNodes[ i ];
  2087. switch ( child.nodeName ) {
  2088. case 'offsetU':
  2089. case 'offsetV':
  2090. case 'repeatU':
  2091. case 'repeatV':
  2092. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  2093. break;
  2094. case 'wrapU':
  2095. case 'wrapV':
  2096. // some dae have a value of true which becomes NaN via parseInt
  2097. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  2098. this.texOpts[ child.nodeName ] = 1;
  2099. } else {
  2100. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  2101. }
  2102. break;
  2103. default:
  2104. this.texOpts[ child.nodeName ] = child.textContent;
  2105. break;
  2106. }
  2107. }
  2108. return this;
  2109. };
  2110. function Shader ( type, effect ) {
  2111. this.type = type;
  2112. this.effect = effect;
  2113. this.material = null;
  2114. }
  2115. Shader.prototype.parse = function ( element ) {
  2116. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2117. var child = element.childNodes[ i ];
  2118. if ( child.nodeType != 1 ) continue;
  2119. switch ( child.nodeName ) {
  2120. case 'emission':
  2121. case 'diffuse':
  2122. case 'specular':
  2123. case 'transparent':
  2124. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  2125. break;
  2126. case 'bump':
  2127. // If 'bumptype' is 'heightfield', create a 'bump' property
  2128. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  2129. // (Default to 'bump')
  2130. var bumpType = child.getAttribute( 'bumptype' );
  2131. if ( bumpType ) {
  2132. if ( bumpType.toLowerCase() === "heightfield" ) {
  2133. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2134. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  2135. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  2136. } else {
  2137. THREE.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  2138. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2139. }
  2140. } else {
  2141. THREE.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  2142. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2143. }
  2144. break;
  2145. case 'shininess':
  2146. case 'reflectivity':
  2147. case 'index_of_refraction':
  2148. case 'transparency':
  2149. var f = child.querySelectorAll('float');
  2150. if ( f.length > 0 )
  2151. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  2152. break;
  2153. default:
  2154. break;
  2155. }
  2156. }
  2157. this.create();
  2158. return this;
  2159. };
  2160. Shader.prototype.create = function() {
  2161. var props = {};
  2162. var transparent = false;
  2163. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  2164. // convert transparent color RBG to average value
  2165. var transparentColor = this['transparent'];
  2166. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  2167. if (transparencyLevel > 0) {
  2168. transparent = true;
  2169. props[ 'transparent' ] = true;
  2170. props[ 'opacity' ] = 1 - transparencyLevel;
  2171. }
  2172. }
  2173. var keys = {
  2174. 'diffuse':'map',
  2175. 'ambient':'lightMap',
  2176. 'specular':'specularMap',
  2177. 'emission':'emissionMap',
  2178. 'bump':'bumpMap',
  2179. 'normal':'normalMap'
  2180. };
  2181. for ( var prop in this ) {
  2182. switch ( prop ) {
  2183. case 'ambient':
  2184. case 'emission':
  2185. case 'diffuse':
  2186. case 'specular':
  2187. case 'bump':
  2188. case 'normal':
  2189. var cot = this[ prop ];
  2190. if ( cot instanceof ColorOrTexture ) {
  2191. if ( cot.isTexture() ) {
  2192. var samplerId = cot.texture;
  2193. var surfaceId = this.effect.sampler[samplerId];
  2194. if ( surfaceId !== undefined && surfaceId.source !== undefined ) {
  2195. var surface = this.effect.surface[surfaceId.source];
  2196. if ( surface !== undefined ) {
  2197. var image = images[ surface.init_from ];
  2198. if ( image ) {
  2199. var url = baseUrl + image.init_from;
  2200. var texture;
  2201. var loader = THREE.Loader.Handlers.get( url );
  2202. if ( loader !== null ) {
  2203. texture = loader.load( url );
  2204. } else {
  2205. texture = new THREE.Texture();
  2206. loadTextureImage( texture, url );
  2207. }
  2208. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2209. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2210. texture.offset.x = cot.texOpts.offsetU;
  2211. texture.offset.y = cot.texOpts.offsetV;
  2212. texture.repeat.x = cot.texOpts.repeatU;
  2213. texture.repeat.y = cot.texOpts.repeatV;
  2214. props[keys[prop]] = texture;
  2215. // Texture with baked lighting?
  2216. if (prop === 'emission') props['emissive'] = 0xffffff;
  2217. }
  2218. }
  2219. }
  2220. } else if ( prop === 'diffuse' || !transparent ) {
  2221. if ( prop === 'emission' ) {
  2222. props[ 'emissive' ] = cot.color.getHex();
  2223. } else {
  2224. props[ prop ] = cot.color.getHex();
  2225. }
  2226. }
  2227. }
  2228. break;
  2229. case 'shininess':
  2230. props[ prop ] = this[ prop ];
  2231. break;
  2232. case 'reflectivity':
  2233. props[ prop ] = this[ prop ];
  2234. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  2235. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  2236. break;
  2237. case 'index_of_refraction':
  2238. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  2239. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  2240. break;
  2241. case 'transparency':
  2242. // gets figured out up top
  2243. break;
  2244. default:
  2245. break;
  2246. }
  2247. }
  2248. props[ 'shading' ] = preferredShading;
  2249. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  2250. switch ( this.type ) {
  2251. case 'constant':
  2252. if (props.emissive != undefined) props.color = props.emissive;
  2253. this.material = new THREE.MeshBasicMaterial( props );
  2254. break;
  2255. case 'phong':
  2256. case 'blinn':
  2257. if (props.diffuse != undefined) props.color = props.diffuse;
  2258. this.material = new THREE.MeshPhongMaterial( props );
  2259. break;
  2260. case 'lambert':
  2261. default:
  2262. if (props.diffuse != undefined) props.color = props.diffuse;
  2263. this.material = new THREE.MeshLambertMaterial( props );
  2264. break;
  2265. }
  2266. return this.material;
  2267. };
  2268. function Surface ( effect ) {
  2269. this.effect = effect;
  2270. this.init_from = null;
  2271. this.format = null;
  2272. }
  2273. Surface.prototype.parse = function ( element ) {
  2274. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2275. var child = element.childNodes[ i ];
  2276. if ( child.nodeType != 1 ) continue;
  2277. switch ( child.nodeName ) {
  2278. case 'init_from':
  2279. this.init_from = child.textContent;
  2280. break;
  2281. case 'format':
  2282. this.format = child.textContent;
  2283. break;
  2284. default:
  2285. THREE.log( "unhandled Surface prop: " + child.nodeName );
  2286. break;
  2287. }
  2288. }
  2289. return this;
  2290. };
  2291. function Sampler2D ( effect ) {
  2292. this.effect = effect;
  2293. this.source = null;
  2294. this.wrap_s = null;
  2295. this.wrap_t = null;
  2296. this.minfilter = null;
  2297. this.magfilter = null;
  2298. this.mipfilter = null;
  2299. }
  2300. Sampler2D.prototype.parse = function ( element ) {
  2301. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2302. var child = element.childNodes[ i ];
  2303. if ( child.nodeType != 1 ) continue;
  2304. switch ( child.nodeName ) {
  2305. case 'source':
  2306. this.source = child.textContent;
  2307. break;
  2308. case 'minfilter':
  2309. this.minfilter = child.textContent;
  2310. break;
  2311. case 'magfilter':
  2312. this.magfilter = child.textContent;
  2313. break;
  2314. case 'mipfilter':
  2315. this.mipfilter = child.textContent;
  2316. break;
  2317. case 'wrap_s':
  2318. this.wrap_s = child.textContent;
  2319. break;
  2320. case 'wrap_t':
  2321. this.wrap_t = child.textContent;
  2322. break;
  2323. default:
  2324. THREE.log( "unhandled Sampler2D prop: " + child.nodeName );
  2325. break;
  2326. }
  2327. }
  2328. return this;
  2329. };
  2330. function Effect () {
  2331. this.id = "";
  2332. this.name = "";
  2333. this.shader = null;
  2334. this.surface = {};
  2335. this.sampler = {};
  2336. }
  2337. Effect.prototype.create = function () {
  2338. if ( this.shader === null ) {
  2339. return null;
  2340. }
  2341. };
  2342. Effect.prototype.parse = function ( element ) {
  2343. this.id = element.getAttribute( 'id' );
  2344. this.name = element.getAttribute( 'name' );
  2345. extractDoubleSided( this, element );
  2346. this.shader = null;
  2347. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2348. var child = element.childNodes[ i ];
  2349. if ( child.nodeType != 1 ) continue;
  2350. switch ( child.nodeName ) {
  2351. case 'profile_COMMON':
  2352. this.parseTechnique( this.parseProfileCOMMON( child ) );
  2353. break;
  2354. default:
  2355. break;
  2356. }
  2357. }
  2358. return this;
  2359. };
  2360. Effect.prototype.parseNewparam = function ( element ) {
  2361. var sid = element.getAttribute( 'sid' );
  2362. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2363. var child = element.childNodes[ i ];
  2364. if ( child.nodeType != 1 ) continue;
  2365. switch ( child.nodeName ) {
  2366. case 'surface':
  2367. this.surface[sid] = ( new Surface( this ) ).parse( child );
  2368. break;
  2369. case 'sampler2D':
  2370. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  2371. break;
  2372. case 'extra':
  2373. break;
  2374. default:
  2375. THREE.log( child.nodeName );
  2376. break;
  2377. }
  2378. }
  2379. };
  2380. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2381. var technique;
  2382. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2383. var child = element.childNodes[ i ];
  2384. if ( child.nodeType != 1 ) continue;
  2385. switch ( child.nodeName ) {
  2386. case 'profile_COMMON':
  2387. this.parseProfileCOMMON( child );
  2388. break;
  2389. case 'technique':
  2390. technique = child;
  2391. break;
  2392. case 'newparam':
  2393. this.parseNewparam( child );
  2394. break;
  2395. case 'image':
  2396. var _image = ( new _Image() ).parse( child );
  2397. images[ _image.id ] = _image;
  2398. break;
  2399. case 'extra':
  2400. break;
  2401. default:
  2402. THREE.log( child.nodeName );
  2403. break;
  2404. }
  2405. }
  2406. return technique;
  2407. };
  2408. Effect.prototype.parseTechnique = function ( element ) {
  2409. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2410. var child = element.childNodes[i];
  2411. if ( child.nodeType != 1 ) continue;
  2412. switch ( child.nodeName ) {
  2413. case 'constant':
  2414. case 'lambert':
  2415. case 'blinn':
  2416. case 'phong':
  2417. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2418. break;
  2419. case 'extra':
  2420. this.parseExtra(child);
  2421. break;
  2422. default:
  2423. break;
  2424. }
  2425. }
  2426. };
  2427. Effect.prototype.parseExtra = function ( element ) {
  2428. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2429. var child = element.childNodes[i];
  2430. if ( child.nodeType != 1 ) continue;
  2431. switch ( child.nodeName ) {
  2432. case 'technique':
  2433. this.parseExtraTechnique( child );
  2434. break;
  2435. default:
  2436. break;
  2437. }
  2438. }
  2439. };
  2440. Effect.prototype.parseExtraTechnique = function ( element ) {
  2441. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2442. var child = element.childNodes[i];
  2443. if ( child.nodeType != 1 ) continue;
  2444. switch ( child.nodeName ) {
  2445. case 'bump':
  2446. this.shader.parse( element );
  2447. break;
  2448. default:
  2449. break;
  2450. }
  2451. }
  2452. };
  2453. function InstanceEffect () {
  2454. this.url = "";
  2455. }
  2456. InstanceEffect.prototype.parse = function ( element ) {
  2457. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2458. return this;
  2459. };
  2460. function Animation() {
  2461. this.id = "";
  2462. this.name = "";
  2463. this.source = {};
  2464. this.sampler = [];
  2465. this.channel = [];
  2466. }
  2467. Animation.prototype.parse = function ( element ) {
  2468. this.id = element.getAttribute( 'id' );
  2469. this.name = element.getAttribute( 'name' );
  2470. this.source = {};
  2471. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2472. var child = element.childNodes[ i ];
  2473. if ( child.nodeType != 1 ) continue;
  2474. switch ( child.nodeName ) {
  2475. case 'animation':
  2476. var anim = ( new Animation() ).parse( child );
  2477. for ( var src in anim.source ) {
  2478. this.source[ src ] = anim.source[ src ];
  2479. }
  2480. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2481. this.channel.push( anim.channel[ j ] );
  2482. this.sampler.push( anim.sampler[ j ] );
  2483. }
  2484. break;
  2485. case 'source':
  2486. var src = ( new Source() ).parse( child );
  2487. this.source[ src.id ] = src;
  2488. break;
  2489. case 'sampler':
  2490. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2491. break;
  2492. case 'channel':
  2493. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2494. break;
  2495. default:
  2496. break;
  2497. }
  2498. }
  2499. return this;
  2500. };
  2501. function Channel( animation ) {
  2502. this.animation = animation;
  2503. this.source = "";
  2504. this.target = "";
  2505. this.fullSid = null;
  2506. this.sid = null;
  2507. this.dotSyntax = null;
  2508. this.arrSyntax = null;
  2509. this.arrIndices = null;
  2510. this.member = null;
  2511. }
  2512. Channel.prototype.parse = function ( element ) {
  2513. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2514. this.target = element.getAttribute( 'target' );
  2515. var parts = this.target.split( '/' );
  2516. var id = parts.shift();
  2517. var sid = parts.shift();
  2518. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2519. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2520. if ( dotSyntax ) {
  2521. parts = sid.split(".");
  2522. this.sid = parts.shift();
  2523. this.member = parts.shift();
  2524. } else if ( arrSyntax ) {
  2525. var arrIndices = sid.split("(");
  2526. this.sid = arrIndices.shift();
  2527. for (var j = 0; j < arrIndices.length; j ++ ) {
  2528. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2529. }
  2530. this.arrIndices = arrIndices;
  2531. } else {
  2532. this.sid = sid;
  2533. }
  2534. this.fullSid = sid;
  2535. this.dotSyntax = dotSyntax;
  2536. this.arrSyntax = arrSyntax;
  2537. return this;
  2538. };
  2539. function Sampler ( animation ) {
  2540. this.id = "";
  2541. this.animation = animation;
  2542. this.inputs = [];
  2543. this.input = null;
  2544. this.output = null;
  2545. this.strideOut = null;
  2546. this.interpolation = null;
  2547. this.startTime = null;
  2548. this.endTime = null;
  2549. this.duration = 0;
  2550. }
  2551. Sampler.prototype.parse = function ( element ) {
  2552. this.id = element.getAttribute( 'id' );
  2553. this.inputs = [];
  2554. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2555. var child = element.childNodes[ i ];
  2556. if ( child.nodeType != 1 ) continue;
  2557. switch ( child.nodeName ) {
  2558. case 'input':
  2559. this.inputs.push( (new Input()).parse( child ) );
  2560. break;
  2561. default:
  2562. break;
  2563. }
  2564. }
  2565. return this;
  2566. };
  2567. Sampler.prototype.create = function () {
  2568. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2569. var input = this.inputs[ i ];
  2570. var source = this.animation.source[ input.source ];
  2571. switch ( input.semantic ) {
  2572. case 'INPUT':
  2573. this.input = source.read();
  2574. break;
  2575. case 'OUTPUT':
  2576. this.output = source.read();
  2577. this.strideOut = source.accessor.stride;
  2578. break;
  2579. case 'INTERPOLATION':
  2580. this.interpolation = source.read();
  2581. break;
  2582. case 'IN_TANGENT':
  2583. break;
  2584. case 'OUT_TANGENT':
  2585. break;
  2586. default:
  2587. THREE.log(input.semantic);
  2588. break;
  2589. }
  2590. }
  2591. this.startTime = 0;
  2592. this.endTime = 0;
  2593. this.duration = 0;
  2594. if ( this.input.length ) {
  2595. this.startTime = 100000000;
  2596. this.endTime = -100000000;
  2597. for ( var i = 0; i < this.input.length; i ++ ) {
  2598. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2599. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2600. }
  2601. this.duration = this.endTime - this.startTime;
  2602. }
  2603. };
  2604. Sampler.prototype.getData = function ( type, ndx, member ) {
  2605. var data;
  2606. if ( type === 'matrix' && this.strideOut === 16 ) {
  2607. data = this.output[ ndx ];
  2608. } else if ( this.strideOut > 1 ) {
  2609. data = [];
  2610. ndx *= this.strideOut;
  2611. for ( var i = 0; i < this.strideOut; ++ i ) {
  2612. data[ i ] = this.output[ ndx + i ];
  2613. }
  2614. if ( this.strideOut === 3 ) {
  2615. switch ( type ) {
  2616. case 'rotate':
  2617. case 'translate':
  2618. fixCoords( data, -1 );
  2619. break;
  2620. case 'scale':
  2621. fixCoords( data, 1 );
  2622. break;
  2623. }
  2624. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2625. fixCoords( data, -1 );
  2626. }
  2627. } else {
  2628. data = this.output[ ndx ];
  2629. if ( member && type === 'translate' ) {
  2630. data = getConvertedTranslation( member, data );
  2631. }
  2632. }
  2633. return data;
  2634. };
  2635. function Key ( time ) {
  2636. this.targets = [];
  2637. this.time = time;
  2638. }
  2639. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2640. this.targets.push( {
  2641. sid: fullSid,
  2642. member: member,
  2643. transform: transform,
  2644. data: data
  2645. } );
  2646. };
  2647. Key.prototype.apply = function ( opt_sid ) {
  2648. for ( var i = 0; i < this.targets.length; ++ i ) {
  2649. var target = this.targets[ i ];
  2650. if ( !opt_sid || target.sid === opt_sid ) {
  2651. target.transform.update( target.data, target.member );
  2652. }
  2653. }
  2654. };
  2655. Key.prototype.getTarget = function ( fullSid ) {
  2656. for ( var i = 0; i < this.targets.length; ++ i ) {
  2657. if ( this.targets[ i ].sid === fullSid ) {
  2658. return this.targets[ i ];
  2659. }
  2660. }
  2661. return null;
  2662. };
  2663. Key.prototype.hasTarget = function ( fullSid ) {
  2664. for ( var i = 0; i < this.targets.length; ++ i ) {
  2665. if ( this.targets[ i ].sid === fullSid ) {
  2666. return true;
  2667. }
  2668. }
  2669. return false;
  2670. };
  2671. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2672. Key.prototype.interpolate = function ( nextKey, time ) {
  2673. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  2674. var target = this.targets[ i ],
  2675. nextTarget = nextKey.getTarget( target.sid ),
  2676. data;
  2677. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2678. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2679. nextData = nextTarget.data,
  2680. prevData = target.data;
  2681. if ( scale < 0 ) scale = 0;
  2682. if ( scale > 1 ) scale = 1;
  2683. if ( prevData.length ) {
  2684. data = [];
  2685. for ( var j = 0; j < prevData.length; ++ j ) {
  2686. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2687. }
  2688. } else {
  2689. data = prevData + ( nextData - prevData ) * scale;
  2690. }
  2691. } else {
  2692. data = target.data;
  2693. }
  2694. target.transform.update( data, target.member );
  2695. }
  2696. };
  2697. // Camera
  2698. function Camera() {
  2699. this.id = "";
  2700. this.name = "";
  2701. this.technique = "";
  2702. }
  2703. Camera.prototype.parse = function ( element ) {
  2704. this.id = element.getAttribute( 'id' );
  2705. this.name = element.getAttribute( 'name' );
  2706. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2707. var child = element.childNodes[ i ];
  2708. if ( child.nodeType != 1 ) continue;
  2709. switch ( child.nodeName ) {
  2710. case 'optics':
  2711. this.parseOptics( child );
  2712. break;
  2713. default:
  2714. break;
  2715. }
  2716. }
  2717. return this;
  2718. };
  2719. Camera.prototype.parseOptics = function ( element ) {
  2720. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2721. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  2722. var technique = element.childNodes[ i ];
  2723. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2724. this.technique = technique.childNodes[ j ].nodeName;
  2725. if ( this.technique === 'perspective' ) {
  2726. var perspective = technique.childNodes[ j ];
  2727. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2728. var param = perspective.childNodes[ k ];
  2729. switch ( param.nodeName ) {
  2730. case 'yfov':
  2731. this.yfov = param.textContent;
  2732. break;
  2733. case 'xfov':
  2734. this.xfov = param.textContent;
  2735. break;
  2736. case 'znear':
  2737. this.znear = param.textContent;
  2738. break;
  2739. case 'zfar':
  2740. this.zfar = param.textContent;
  2741. break;
  2742. case 'aspect_ratio':
  2743. this.aspect_ratio = param.textContent;
  2744. break;
  2745. }
  2746. }
  2747. } else if ( this.technique === 'orthographic' ) {
  2748. var orthographic = technique.childNodes[ j ];
  2749. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2750. var param = orthographic.childNodes[ k ];
  2751. switch ( param.nodeName ) {
  2752. case 'xmag':
  2753. this.xmag = param.textContent;
  2754. break;
  2755. case 'ymag':
  2756. this.ymag = param.textContent;
  2757. break;
  2758. case 'znear':
  2759. this.znear = param.textContent;
  2760. break;
  2761. case 'zfar':
  2762. this.zfar = param.textContent;
  2763. break;
  2764. case 'aspect_ratio':
  2765. this.aspect_ratio = param.textContent;
  2766. break;
  2767. }
  2768. }
  2769. }
  2770. }
  2771. }
  2772. }
  2773. return this;
  2774. };
  2775. function InstanceCamera() {
  2776. this.url = "";
  2777. }
  2778. InstanceCamera.prototype.parse = function ( element ) {
  2779. this.url = element.getAttribute('url').replace(/^#/, '');
  2780. return this;
  2781. };
  2782. // Light
  2783. function Light() {
  2784. this.id = "";
  2785. this.name = "";
  2786. this.technique = "";
  2787. }
  2788. Light.prototype.parse = function ( element ) {
  2789. this.id = element.getAttribute( 'id' );
  2790. this.name = element.getAttribute( 'name' );
  2791. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2792. var child = element.childNodes[ i ];
  2793. if ( child.nodeType != 1 ) continue;
  2794. switch ( child.nodeName ) {
  2795. case 'technique_common':
  2796. this.parseCommon( child );
  2797. break;
  2798. case 'technique':
  2799. this.parseTechnique( child );
  2800. break;
  2801. default:
  2802. break;
  2803. }
  2804. }
  2805. return this;
  2806. };
  2807. Light.prototype.parseCommon = function ( element ) {
  2808. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2809. switch ( element.childNodes[ i ].nodeName ) {
  2810. case 'directional':
  2811. case 'point':
  2812. case 'spot':
  2813. case 'ambient':
  2814. this.technique = element.childNodes[ i ].nodeName;
  2815. var light = element.childNodes[ i ];
  2816. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  2817. var child = light.childNodes[j];
  2818. switch ( child.nodeName ) {
  2819. case 'color':
  2820. var rgba = _floats( child.textContent );
  2821. this.color = new THREE.Color(0);
  2822. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2823. this.color.a = rgba[3];
  2824. break;
  2825. case 'falloff_angle':
  2826. this.falloff_angle = parseFloat( child.textContent );
  2827. break;
  2828. case 'quadratic_attenuation':
  2829. var f = parseFloat( child.textContent );
  2830. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  2831. }
  2832. }
  2833. }
  2834. }
  2835. return this;
  2836. };
  2837. Light.prototype.parseTechnique = function ( element ) {
  2838. this.profile = element.getAttribute( 'profile' );
  2839. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2840. var child = element.childNodes[ i ];
  2841. switch ( child.nodeName ) {
  2842. case 'intensity':
  2843. this.intensity = parseFloat(child.textContent);
  2844. break;
  2845. }
  2846. }
  2847. return this;
  2848. };
  2849. function InstanceLight() {
  2850. this.url = "";
  2851. }
  2852. InstanceLight.prototype.parse = function ( element ) {
  2853. this.url = element.getAttribute('url').replace(/^#/, '');
  2854. return this;
  2855. };
  2856. function KinematicsModel( ) {
  2857. this.id = '';
  2858. this.name = '';
  2859. this.joints = [];
  2860. this.links = [];
  2861. }
  2862. KinematicsModel.prototype.parse = function( element ) {
  2863. this.id = element.getAttribute('id');
  2864. this.name = element.getAttribute('name');
  2865. this.joints = [];
  2866. this.links = [];
  2867. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2868. var child = element.childNodes[ i ];
  2869. if ( child.nodeType != 1 ) continue;
  2870. switch ( child.nodeName ) {
  2871. case 'technique_common':
  2872. this.parseCommon(child);
  2873. break;
  2874. default:
  2875. break;
  2876. }
  2877. }
  2878. return this;
  2879. };
  2880. KinematicsModel.prototype.parseCommon = function( element ) {
  2881. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2882. var child = element.childNodes[ i ];
  2883. if ( child.nodeType != 1 ) continue;
  2884. switch ( element.childNodes[ i ].nodeName ) {
  2885. case 'joint':
  2886. this.joints.push( (new Joint()).parse(child) );
  2887. break;
  2888. case 'link':
  2889. this.links.push( (new Link()).parse(child) );
  2890. break;
  2891. default:
  2892. break;
  2893. }
  2894. }
  2895. return this;
  2896. };
  2897. function Joint( ) {
  2898. this.sid = '';
  2899. this.name = '';
  2900. this.axis = new THREE.Vector3();
  2901. this.limits = {
  2902. min: 0,
  2903. max: 0
  2904. };
  2905. this.type = '';
  2906. this.static = false;
  2907. this.zeroPosition = 0.0;
  2908. this.middlePosition = 0.0;
  2909. }
  2910. Joint.prototype.parse = function( element ) {
  2911. this.sid = element.getAttribute('sid');
  2912. this.name = element.getAttribute('name');
  2913. this.axis = new THREE.Vector3();
  2914. this.limits = {
  2915. min: 0,
  2916. max: 0
  2917. };
  2918. this.type = '';
  2919. this.static = false;
  2920. this.zeroPosition = 0.0;
  2921. this.middlePosition = 0.0;
  2922. var axisElement = element.querySelector('axis');
  2923. var _axis = _floats(axisElement.textContent);
  2924. this.axis = getConvertedVec3(_axis, 0);
  2925. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  2926. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  2927. this.limits = {
  2928. min: min,
  2929. max: max
  2930. };
  2931. var jointTypes = [ 'prismatic', 'revolute' ];
  2932. for (var i = 0; i < jointTypes.length; i ++ ) {
  2933. var type = jointTypes[ i ];
  2934. var jointElement = element.querySelector(type);
  2935. if ( jointElement ) {
  2936. this.type = type;
  2937. }
  2938. }
  2939. // if the min is equal to or somehow greater than the max, consider the joint static
  2940. if ( this.limits.min >= this.limits.max ) {
  2941. this.static = true;
  2942. }
  2943. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  2944. return this;
  2945. };
  2946. function Link( ) {
  2947. this.sid = '';
  2948. this.name = '';
  2949. this.transforms = [];
  2950. this.attachments = [];
  2951. }
  2952. Link.prototype.parse = function( element ) {
  2953. this.sid = element.getAttribute('sid');
  2954. this.name = element.getAttribute('name');
  2955. this.transforms = [];
  2956. this.attachments = [];
  2957. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2958. var child = element.childNodes[ i ];
  2959. if ( child.nodeType != 1 ) continue;
  2960. switch ( child.nodeName ) {
  2961. case 'attachment_full':
  2962. this.attachments.push( (new Attachment()).parse(child) );
  2963. break;
  2964. case 'rotate':
  2965. case 'translate':
  2966. case 'matrix':
  2967. this.transforms.push( (new Transform()).parse(child) );
  2968. break;
  2969. default:
  2970. break;
  2971. }
  2972. }
  2973. return this;
  2974. };
  2975. function Attachment( ) {
  2976. this.joint = '';
  2977. this.transforms = [];
  2978. this.links = [];
  2979. }
  2980. Attachment.prototype.parse = function( element ) {
  2981. this.joint = element.getAttribute('joint').split('/').pop();
  2982. this.links = [];
  2983. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2984. var child = element.childNodes[ i ];
  2985. if ( child.nodeType != 1 ) continue;
  2986. switch ( child.nodeName ) {
  2987. case 'link':
  2988. this.links.push( (new Link()).parse(child) );
  2989. break;
  2990. case 'rotate':
  2991. case 'translate':
  2992. case 'matrix':
  2993. this.transforms.push( (new Transform()).parse(child) );
  2994. break;
  2995. default:
  2996. break;
  2997. }
  2998. }
  2999. return this;
  3000. };
  3001. function _source( element ) {
  3002. var id = element.getAttribute( 'id' );
  3003. if ( sources[ id ] != undefined ) {
  3004. return sources[ id ];
  3005. }
  3006. sources[ id ] = ( new Source(id )).parse( element );
  3007. return sources[ id ];
  3008. }
  3009. function _nsResolver( nsPrefix ) {
  3010. if ( nsPrefix === "dae" ) {
  3011. return "http://www.collada.org/2005/11/COLLADASchema";
  3012. }
  3013. return null;
  3014. }
  3015. function _bools( str ) {
  3016. var raw = _strings( str );
  3017. var data = [];
  3018. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3019. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  3020. }
  3021. return data;
  3022. }
  3023. function _floats( str ) {
  3024. var raw = _strings(str);
  3025. var data = [];
  3026. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3027. data.push( parseFloat( raw[ i ] ) );
  3028. }
  3029. return data;
  3030. }
  3031. function _ints( str ) {
  3032. var raw = _strings( str );
  3033. var data = [];
  3034. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3035. data.push( parseInt( raw[ i ], 10 ) );
  3036. }
  3037. return data;
  3038. }
  3039. function _strings( str ) {
  3040. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  3041. }
  3042. function _trimString( str ) {
  3043. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  3044. }
  3045. function _attr_as_float( element, name, defaultValue ) {
  3046. if ( element.hasAttribute( name ) ) {
  3047. return parseFloat( element.getAttribute( name ) );
  3048. } else {
  3049. return defaultValue;
  3050. }
  3051. }
  3052. function _attr_as_int( element, name, defaultValue ) {
  3053. if ( element.hasAttribute( name ) ) {
  3054. return parseInt( element.getAttribute( name ), 10) ;
  3055. } else {
  3056. return defaultValue;
  3057. }
  3058. }
  3059. function _attr_as_string( element, name, defaultValue ) {
  3060. if ( element.hasAttribute( name ) ) {
  3061. return element.getAttribute( name );
  3062. } else {
  3063. return defaultValue;
  3064. }
  3065. }
  3066. function _format_float( f, num ) {
  3067. if ( f === undefined ) {
  3068. var s = '0.';
  3069. while ( s.length < num + 2 ) {
  3070. s += '0';
  3071. }
  3072. return s;
  3073. }
  3074. num = num || 2;
  3075. var parts = f.toString().split( '.' );
  3076. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  3077. while ( parts[ 1 ].length < num ) {
  3078. parts[ 1 ] += '0';
  3079. }
  3080. return parts.join( '.' );
  3081. }
  3082. function loadTextureImage ( texture, url ) {
  3083. loader = new THREE.ImageLoader();
  3084. loader.load( url, function ( image ) {
  3085. texture.image = image;
  3086. texture.needsUpdate = true;
  3087. } );
  3088. }
  3089. function extractDoubleSided( obj, element ) {
  3090. obj.doubleSided = false;
  3091. var node = element.querySelectorAll('extra double_sided')[0];
  3092. if ( node ) {
  3093. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  3094. obj.doubleSided = true;
  3095. }
  3096. }
  3097. }
  3098. // Up axis conversion
  3099. function setUpConversion() {
  3100. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3101. upConversion = null;
  3102. } else {
  3103. switch ( colladaUp ) {
  3104. case 'X':
  3105. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  3106. break;
  3107. case 'Y':
  3108. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  3109. break;
  3110. case 'Z':
  3111. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  3112. break;
  3113. }
  3114. }
  3115. }
  3116. function fixCoords( data, sign ) {
  3117. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3118. return;
  3119. }
  3120. switch ( upConversion ) {
  3121. case 'XtoY':
  3122. var tmp = data[ 0 ];
  3123. data[ 0 ] = sign * data[ 1 ];
  3124. data[ 1 ] = tmp;
  3125. break;
  3126. case 'XtoZ':
  3127. var tmp = data[ 2 ];
  3128. data[ 2 ] = data[ 1 ];
  3129. data[ 1 ] = data[ 0 ];
  3130. data[ 0 ] = tmp;
  3131. break;
  3132. case 'YtoX':
  3133. var tmp = data[ 0 ];
  3134. data[ 0 ] = data[ 1 ];
  3135. data[ 1 ] = sign * tmp;
  3136. break;
  3137. case 'YtoZ':
  3138. var tmp = data[ 1 ];
  3139. data[ 1 ] = sign * data[ 2 ];
  3140. data[ 2 ] = tmp;
  3141. break;
  3142. case 'ZtoX':
  3143. var tmp = data[ 0 ];
  3144. data[ 0 ] = data[ 1 ];
  3145. data[ 1 ] = data[ 2 ];
  3146. data[ 2 ] = tmp;
  3147. break;
  3148. case 'ZtoY':
  3149. var tmp = data[ 1 ];
  3150. data[ 1 ] = data[ 2 ];
  3151. data[ 2 ] = sign * tmp;
  3152. break;
  3153. }
  3154. }
  3155. function getConvertedTranslation( axis, data ) {
  3156. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3157. return data;
  3158. }
  3159. switch ( axis ) {
  3160. case 'X':
  3161. data = upConversion === 'XtoY' ? data * -1 : data;
  3162. break;
  3163. case 'Y':
  3164. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  3165. break;
  3166. case 'Z':
  3167. data = upConversion === 'ZtoY' ? data * -1 : data ;
  3168. break;
  3169. default:
  3170. break;
  3171. }
  3172. return data;
  3173. }
  3174. function getConvertedVec3( data, offset ) {
  3175. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  3176. fixCoords( arr, -1 );
  3177. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  3178. }
  3179. function getConvertedMat4( data ) {
  3180. if ( options.convertUpAxis ) {
  3181. // First fix rotation and scale
  3182. // Columns first
  3183. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  3184. fixCoords( arr, -1 );
  3185. data[ 0 ] = arr[ 0 ];
  3186. data[ 4 ] = arr[ 1 ];
  3187. data[ 8 ] = arr[ 2 ];
  3188. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  3189. fixCoords( arr, -1 );
  3190. data[ 1 ] = arr[ 0 ];
  3191. data[ 5 ] = arr[ 1 ];
  3192. data[ 9 ] = arr[ 2 ];
  3193. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  3194. fixCoords( arr, -1 );
  3195. data[ 2 ] = arr[ 0 ];
  3196. data[ 6 ] = arr[ 1 ];
  3197. data[ 10 ] = arr[ 2 ];
  3198. // Rows second
  3199. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  3200. fixCoords( arr, -1 );
  3201. data[ 0 ] = arr[ 0 ];
  3202. data[ 1 ] = arr[ 1 ];
  3203. data[ 2 ] = arr[ 2 ];
  3204. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  3205. fixCoords( arr, -1 );
  3206. data[ 4 ] = arr[ 0 ];
  3207. data[ 5 ] = arr[ 1 ];
  3208. data[ 6 ] = arr[ 2 ];
  3209. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  3210. fixCoords( arr, -1 );
  3211. data[ 8 ] = arr[ 0 ];
  3212. data[ 9 ] = arr[ 1 ];
  3213. data[ 10 ] = arr[ 2 ];
  3214. // Now fix translation
  3215. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  3216. fixCoords( arr, -1 );
  3217. data[ 3 ] = arr[ 0 ];
  3218. data[ 7 ] = arr[ 1 ];
  3219. data[ 11 ] = arr[ 2 ];
  3220. }
  3221. return new THREE.Matrix4().set(
  3222. data[0], data[1], data[2], data[3],
  3223. data[4], data[5], data[6], data[7],
  3224. data[8], data[9], data[10], data[11],
  3225. data[12], data[13], data[14], data[15]
  3226. );
  3227. }
  3228. function getConvertedIndex( index ) {
  3229. if ( index > -1 && index < 3 ) {
  3230. var members = [ 'X', 'Y', 'Z' ],
  3231. indices = { X: 0, Y: 1, Z: 2 };
  3232. index = getConvertedMember( members[ index ] );
  3233. index = indices[ index ];
  3234. }
  3235. return index;
  3236. }
  3237. function getConvertedMember( member ) {
  3238. if ( options.convertUpAxis ) {
  3239. switch ( member ) {
  3240. case 'X':
  3241. switch ( upConversion ) {
  3242. case 'XtoY':
  3243. case 'XtoZ':
  3244. case 'YtoX':
  3245. member = 'Y';
  3246. break;
  3247. case 'ZtoX':
  3248. member = 'Z';
  3249. break;
  3250. }
  3251. break;
  3252. case 'Y':
  3253. switch ( upConversion ) {
  3254. case 'XtoY':
  3255. case 'YtoX':
  3256. case 'ZtoX':
  3257. member = 'X';
  3258. break;
  3259. case 'XtoZ':
  3260. case 'YtoZ':
  3261. case 'ZtoY':
  3262. member = 'Z';
  3263. break;
  3264. }
  3265. break;
  3266. case 'Z':
  3267. switch ( upConversion ) {
  3268. case 'XtoZ':
  3269. member = 'X';
  3270. break;
  3271. case 'YtoZ':
  3272. case 'ZtoX':
  3273. case 'ZtoY':
  3274. member = 'Y';
  3275. break;
  3276. }
  3277. break;
  3278. }
  3279. }
  3280. return member;
  3281. }
  3282. return {
  3283. load: load,
  3284. parse: parse,
  3285. setPreferredShading: setPreferredShading,
  3286. applySkin: applySkin,
  3287. geometries : geometries,
  3288. options: options
  3289. };
  3290. };