ColladaLoader.js 78 KB

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