ColladaLoader.js 82 KB

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