ColladaLoader.js 98 KB

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