ColladaLoader.js 78 KB

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