ColladaLoader.js 78 KB

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