ColladaLoader.js 98 KB

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