ColladaLoader.js 78 KB

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