ColladaLoader.js 78 KB

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