ColladaLoader.js 78 KB

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