ColladaLoader.js 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800
  1. ( function () {
  2. class ColladaLoader extends THREE.Loader {
  3. constructor( manager ) {
  4. super( manager );
  5. }
  6. load( url, onLoad, onProgress, onError ) {
  7. const scope = this;
  8. const path = scope.path === '' ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  9. const loader = new THREE.FileLoader( scope.manager );
  10. loader.setPath( scope.path );
  11. loader.setRequestHeader( scope.requestHeader );
  12. loader.setWithCredentials( scope.withCredentials );
  13. loader.load( url, function ( text ) {
  14. try {
  15. onLoad( scope.parse( text, path ) );
  16. } catch ( e ) {
  17. if ( onError ) {
  18. onError( e );
  19. } else {
  20. console.error( e );
  21. }
  22. scope.manager.itemError( url );
  23. }
  24. }, onProgress, onError );
  25. }
  26. parse( text, path ) {
  27. function getElementsByTagName( xml, name ) {
  28. // Non recursive xml.getElementsByTagName() ...
  29. const array = [];
  30. const childNodes = xml.childNodes;
  31. for ( let i = 0, l = childNodes.length; i < l; i ++ ) {
  32. const child = childNodes[ i ];
  33. if ( child.nodeName === name ) {
  34. array.push( child );
  35. }
  36. }
  37. return array;
  38. }
  39. function parseStrings( text ) {
  40. if ( text.length === 0 ) return [];
  41. const parts = text.trim().split( /\s+/ );
  42. const array = new Array( parts.length );
  43. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  44. array[ i ] = parts[ i ];
  45. }
  46. return array;
  47. }
  48. function parseFloats( text ) {
  49. if ( text.length === 0 ) return [];
  50. const parts = text.trim().split( /\s+/ );
  51. const array = new Array( parts.length );
  52. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  53. array[ i ] = parseFloat( parts[ i ] );
  54. }
  55. return array;
  56. }
  57. function parseInts( text ) {
  58. if ( text.length === 0 ) return [];
  59. const parts = text.trim().split( /\s+/ );
  60. const array = new Array( parts.length );
  61. for ( let i = 0, l = parts.length; i < l; i ++ ) {
  62. array[ i ] = parseInt( parts[ i ] );
  63. }
  64. return array;
  65. }
  66. function parseId( text ) {
  67. return text.substring( 1 );
  68. }
  69. function generateId() {
  70. return 'three_default_' + count ++;
  71. }
  72. function isEmpty( object ) {
  73. return Object.keys( object ).length === 0;
  74. } // asset
  75. function parseAsset( xml ) {
  76. return {
  77. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  78. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  79. };
  80. }
  81. function parseAssetUnit( xml ) {
  82. if ( xml !== undefined && xml.hasAttribute( 'meter' ) === true ) {
  83. return parseFloat( xml.getAttribute( 'meter' ) );
  84. } else {
  85. return 1; // default 1 meter
  86. }
  87. }
  88. function parseAssetUpAxis( xml ) {
  89. return xml !== undefined ? xml.textContent : 'Y_UP';
  90. } // library
  91. function parseLibrary( xml, libraryName, nodeName, parser ) {
  92. const library = getElementsByTagName( xml, libraryName )[ 0 ];
  93. if ( library !== undefined ) {
  94. const elements = getElementsByTagName( library, nodeName );
  95. for ( let i = 0; i < elements.length; i ++ ) {
  96. parser( elements[ i ] );
  97. }
  98. }
  99. }
  100. function buildLibrary( data, builder ) {
  101. for ( const name in data ) {
  102. const object = data[ name ];
  103. object.build = builder( data[ name ] );
  104. }
  105. } // get
  106. function getBuild( data, builder ) {
  107. if ( data.build !== undefined ) return data.build;
  108. data.build = builder( data );
  109. return data.build;
  110. } // animation
  111. function parseAnimation( xml ) {
  112. const data = {
  113. sources: {},
  114. samplers: {},
  115. channels: {}
  116. };
  117. let hasChildren = false;
  118. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  119. const child = xml.childNodes[ i ];
  120. if ( child.nodeType !== 1 ) continue;
  121. let id;
  122. switch ( child.nodeName ) {
  123. case 'source':
  124. id = child.getAttribute( 'id' );
  125. data.sources[ id ] = parseSource( child );
  126. break;
  127. case 'sampler':
  128. id = child.getAttribute( 'id' );
  129. data.samplers[ id ] = parseAnimationSampler( child );
  130. break;
  131. case 'channel':
  132. id = child.getAttribute( 'target' );
  133. data.channels[ id ] = parseAnimationChannel( child );
  134. break;
  135. case 'animation':
  136. // hierarchy of related animations
  137. parseAnimation( child );
  138. hasChildren = true;
  139. break;
  140. default:
  141. console.log( child );
  142. }
  143. }
  144. if ( hasChildren === false ) {
  145. // since 'id' attributes can be optional, it's necessary to generate a UUID for unqiue assignment
  146. library.animations[ xml.getAttribute( 'id' ) || THREE.MathUtils.generateUUID() ] = data;
  147. }
  148. }
  149. function parseAnimationSampler( xml ) {
  150. const data = {
  151. inputs: {}
  152. };
  153. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  154. const child = xml.childNodes[ i ];
  155. if ( child.nodeType !== 1 ) continue;
  156. switch ( child.nodeName ) {
  157. case 'input':
  158. const id = parseId( child.getAttribute( 'source' ) );
  159. const semantic = child.getAttribute( 'semantic' );
  160. data.inputs[ semantic ] = id;
  161. break;
  162. }
  163. }
  164. return data;
  165. }
  166. function parseAnimationChannel( xml ) {
  167. const data = {};
  168. const target = xml.getAttribute( 'target' ); // parsing SID Addressing Syntax
  169. let parts = target.split( '/' );
  170. const id = parts.shift();
  171. let sid = parts.shift(); // check selection syntax
  172. const arraySyntax = sid.indexOf( '(' ) !== - 1;
  173. const memberSyntax = sid.indexOf( '.' ) !== - 1;
  174. if ( memberSyntax ) {
  175. // member selection access
  176. parts = sid.split( '.' );
  177. sid = parts.shift();
  178. data.member = parts.shift();
  179. } else if ( arraySyntax ) {
  180. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  181. const indices = sid.split( '(' );
  182. sid = indices.shift();
  183. for ( let i = 0; i < indices.length; i ++ ) {
  184. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  185. }
  186. data.indices = indices;
  187. }
  188. data.id = id;
  189. data.sid = sid;
  190. data.arraySyntax = arraySyntax;
  191. data.memberSyntax = memberSyntax;
  192. data.sampler = parseId( xml.getAttribute( 'source' ) );
  193. return data;
  194. }
  195. function buildAnimation( data ) {
  196. const tracks = [];
  197. const channels = data.channels;
  198. const samplers = data.samplers;
  199. const sources = data.sources;
  200. for ( const target in channels ) {
  201. if ( channels.hasOwnProperty( target ) ) {
  202. const channel = channels[ target ];
  203. const sampler = samplers[ channel.sampler ];
  204. const inputId = sampler.inputs.INPUT;
  205. const outputId = sampler.inputs.OUTPUT;
  206. const inputSource = sources[ inputId ];
  207. const outputSource = sources[ outputId ];
  208. const animation = buildAnimationChannel( channel, inputSource, outputSource );
  209. createKeyframeTracks( animation, tracks );
  210. }
  211. }
  212. return tracks;
  213. }
  214. function getAnimation( id ) {
  215. return getBuild( library.animations[ id ], buildAnimation );
  216. }
  217. function buildAnimationChannel( channel, inputSource, outputSource ) {
  218. const node = library.nodes[ channel.id ];
  219. const object3D = getNode( node.id );
  220. const transform = node.transforms[ channel.sid ];
  221. const defaultMatrix = node.matrix.clone().transpose();
  222. let time, stride;
  223. let i, il, j, jl;
  224. const data = {}; // the collada spec allows the animation of data in various ways.
  225. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  226. switch ( transform ) {
  227. case 'matrix':
  228. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  229. time = inputSource.array[ i ];
  230. stride = i * outputSource.stride;
  231. if ( data[ time ] === undefined ) data[ time ] = {};
  232. if ( channel.arraySyntax === true ) {
  233. const value = outputSource.array[ stride ];
  234. const index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  235. data[ time ][ index ] = value;
  236. } else {
  237. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  238. data[ time ][ j ] = outputSource.array[ stride + j ];
  239. }
  240. }
  241. }
  242. break;
  243. case 'translate':
  244. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  245. break;
  246. case 'rotate':
  247. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  248. break;
  249. case 'scale':
  250. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  251. break;
  252. }
  253. const keyframes = prepareAnimationData( data, defaultMatrix );
  254. const animation = {
  255. name: object3D.uuid,
  256. keyframes: keyframes
  257. };
  258. return animation;
  259. }
  260. function prepareAnimationData( data, defaultMatrix ) {
  261. const keyframes = []; // transfer data into a sortable array
  262. for ( const time in data ) {
  263. keyframes.push( {
  264. time: parseFloat( time ),
  265. value: data[ time ]
  266. } );
  267. } // ensure keyframes are sorted by time
  268. keyframes.sort( ascending ); // now we clean up all animation data, so we can use them for keyframe tracks
  269. for ( let i = 0; i < 16; i ++ ) {
  270. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  271. }
  272. return keyframes; // array sort function
  273. function ascending( a, b ) {
  274. return a.time - b.time;
  275. }
  276. }
  277. const position = new THREE.Vector3();
  278. const scale = new THREE.Vector3();
  279. const quaternion = new THREE.Quaternion();
  280. function createKeyframeTracks( animation, tracks ) {
  281. const keyframes = animation.keyframes;
  282. const name = animation.name;
  283. const times = [];
  284. const positionData = [];
  285. const quaternionData = [];
  286. const scaleData = [];
  287. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  288. const keyframe = keyframes[ i ];
  289. const time = keyframe.time;
  290. const value = keyframe.value;
  291. matrix.fromArray( value ).transpose();
  292. matrix.decompose( position, quaternion, scale );
  293. times.push( time );
  294. positionData.push( position.x, position.y, position.z );
  295. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  296. scaleData.push( scale.x, scale.y, scale.z );
  297. }
  298. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  299. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  300. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  301. return tracks;
  302. }
  303. function transformAnimationData( keyframes, property, defaultValue ) {
  304. let keyframe;
  305. let empty = true;
  306. let i, l; // check, if values of a property are missing in our keyframes
  307. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  308. keyframe = keyframes[ i ];
  309. if ( keyframe.value[ property ] === undefined ) {
  310. keyframe.value[ property ] = null; // mark as missing
  311. } else {
  312. empty = false;
  313. }
  314. }
  315. if ( empty === true ) {
  316. // no values at all, so we set a default value
  317. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  318. keyframe = keyframes[ i ];
  319. keyframe.value[ property ] = defaultValue;
  320. }
  321. } else {
  322. // filling gaps
  323. createMissingKeyframes( keyframes, property );
  324. }
  325. }
  326. function createMissingKeyframes( keyframes, property ) {
  327. let prev, next;
  328. for ( let i = 0, l = keyframes.length; i < l; i ++ ) {
  329. const keyframe = keyframes[ i ];
  330. if ( keyframe.value[ property ] === null ) {
  331. prev = getPrev( keyframes, i, property );
  332. next = getNext( keyframes, i, property );
  333. if ( prev === null ) {
  334. keyframe.value[ property ] = next.value[ property ];
  335. continue;
  336. }
  337. if ( next === null ) {
  338. keyframe.value[ property ] = prev.value[ property ];
  339. continue;
  340. }
  341. interpolate( keyframe, prev, next, property );
  342. }
  343. }
  344. }
  345. function getPrev( keyframes, i, property ) {
  346. while ( i >= 0 ) {
  347. const keyframe = keyframes[ i ];
  348. if ( keyframe.value[ property ] !== null ) return keyframe;
  349. i --;
  350. }
  351. return null;
  352. }
  353. function getNext( keyframes, i, property ) {
  354. while ( i < keyframes.length ) {
  355. const keyframe = keyframes[ i ];
  356. if ( keyframe.value[ property ] !== null ) return keyframe;
  357. i ++;
  358. }
  359. return null;
  360. }
  361. function interpolate( key, prev, next, property ) {
  362. if ( next.time - prev.time === 0 ) {
  363. key.value[ property ] = prev.value[ property ];
  364. return;
  365. }
  366. key.value[ property ] = ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) + prev.value[ property ];
  367. } // animation clips
  368. function parseAnimationClip( xml ) {
  369. const data = {
  370. name: xml.getAttribute( 'id' ) || 'default',
  371. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  372. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  373. animations: []
  374. };
  375. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  376. const child = xml.childNodes[ i ];
  377. if ( child.nodeType !== 1 ) continue;
  378. switch ( child.nodeName ) {
  379. case 'instance_animation':
  380. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  381. break;
  382. }
  383. }
  384. library.clips[ xml.getAttribute( 'id' ) ] = data;
  385. }
  386. function buildAnimationClip( data ) {
  387. const tracks = [];
  388. const name = data.name;
  389. const duration = data.end - data.start || - 1;
  390. const animations = data.animations;
  391. for ( let i = 0, il = animations.length; i < il; i ++ ) {
  392. const animationTracks = getAnimation( animations[ i ] );
  393. for ( let j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  394. tracks.push( animationTracks[ j ] );
  395. }
  396. }
  397. return new THREE.AnimationClip( name, duration, tracks );
  398. }
  399. function getAnimationClip( id ) {
  400. return getBuild( library.clips[ id ], buildAnimationClip );
  401. } // controller
  402. function parseController( xml ) {
  403. const data = {};
  404. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  405. const child = xml.childNodes[ i ];
  406. if ( child.nodeType !== 1 ) continue;
  407. switch ( child.nodeName ) {
  408. case 'skin':
  409. // there is exactly one skin per controller
  410. data.id = parseId( child.getAttribute( 'source' ) );
  411. data.skin = parseSkin( child );
  412. break;
  413. case 'morph':
  414. data.id = parseId( child.getAttribute( 'source' ) );
  415. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  416. break;
  417. }
  418. }
  419. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  420. }
  421. function parseSkin( xml ) {
  422. const data = {
  423. sources: {}
  424. };
  425. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  426. const child = xml.childNodes[ i ];
  427. if ( child.nodeType !== 1 ) continue;
  428. switch ( child.nodeName ) {
  429. case 'bind_shape_matrix':
  430. data.bindShapeMatrix = parseFloats( child.textContent );
  431. break;
  432. case 'source':
  433. const id = child.getAttribute( 'id' );
  434. data.sources[ id ] = parseSource( child );
  435. break;
  436. case 'joints':
  437. data.joints = parseJoints( child );
  438. break;
  439. case 'vertex_weights':
  440. data.vertexWeights = parseVertexWeights( child );
  441. break;
  442. }
  443. }
  444. return data;
  445. }
  446. function parseJoints( xml ) {
  447. const data = {
  448. inputs: {}
  449. };
  450. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  451. const child = xml.childNodes[ i ];
  452. if ( child.nodeType !== 1 ) continue;
  453. switch ( child.nodeName ) {
  454. case 'input':
  455. const semantic = child.getAttribute( 'semantic' );
  456. const id = parseId( child.getAttribute( 'source' ) );
  457. data.inputs[ semantic ] = id;
  458. break;
  459. }
  460. }
  461. return data;
  462. }
  463. function parseVertexWeights( xml ) {
  464. const data = {
  465. inputs: {}
  466. };
  467. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  468. const child = xml.childNodes[ i ];
  469. if ( child.nodeType !== 1 ) continue;
  470. switch ( child.nodeName ) {
  471. case 'input':
  472. const semantic = child.getAttribute( 'semantic' );
  473. const id = parseId( child.getAttribute( 'source' ) );
  474. const offset = parseInt( child.getAttribute( 'offset' ) );
  475. data.inputs[ semantic ] = {
  476. id: id,
  477. offset: offset
  478. };
  479. break;
  480. case 'vcount':
  481. data.vcount = parseInts( child.textContent );
  482. break;
  483. case 'v':
  484. data.v = parseInts( child.textContent );
  485. break;
  486. }
  487. }
  488. return data;
  489. }
  490. function buildController( data ) {
  491. const build = {
  492. id: data.id
  493. };
  494. const geometry = library.geometries[ build.id ];
  495. if ( data.skin !== undefined ) {
  496. build.skin = buildSkin( data.skin ); // we enhance the 'sources' property of the corresponding geometry with our skin data
  497. geometry.sources.skinIndices = build.skin.indices;
  498. geometry.sources.skinWeights = build.skin.weights;
  499. }
  500. return build;
  501. }
  502. function buildSkin( data ) {
  503. const BONE_LIMIT = 4;
  504. const build = {
  505. joints: [],
  506. // this must be an array to preserve the joint order
  507. indices: {
  508. array: [],
  509. stride: BONE_LIMIT
  510. },
  511. weights: {
  512. array: [],
  513. stride: BONE_LIMIT
  514. }
  515. };
  516. const sources = data.sources;
  517. const vertexWeights = data.vertexWeights;
  518. const vcount = vertexWeights.vcount;
  519. const v = vertexWeights.v;
  520. const jointOffset = vertexWeights.inputs.JOINT.offset;
  521. const weightOffset = vertexWeights.inputs.WEIGHT.offset;
  522. const jointSource = data.sources[ data.joints.inputs.JOINT ];
  523. const inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  524. const weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  525. let stride = 0;
  526. let i, j, l; // procces skin data for each vertex
  527. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  528. const jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  529. const vertexSkinData = [];
  530. for ( j = 0; j < jointCount; j ++ ) {
  531. const skinIndex = v[ stride + jointOffset ];
  532. const weightId = v[ stride + weightOffset ];
  533. const skinWeight = weights[ weightId ];
  534. vertexSkinData.push( {
  535. index: skinIndex,
  536. weight: skinWeight
  537. } );
  538. stride += 2;
  539. } // we sort the joints in descending order based on the weights.
  540. // this ensures, we only procced the most important joints of the vertex
  541. vertexSkinData.sort( descending ); // now we provide for each vertex a set of four index and weight values.
  542. // the order of the skin data matches the order of vertices
  543. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  544. const d = vertexSkinData[ j ];
  545. if ( d !== undefined ) {
  546. build.indices.array.push( d.index );
  547. build.weights.array.push( d.weight );
  548. } else {
  549. build.indices.array.push( 0 );
  550. build.weights.array.push( 0 );
  551. }
  552. }
  553. } // setup bind matrix
  554. if ( data.bindShapeMatrix ) {
  555. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  556. } else {
  557. build.bindMatrix = new THREE.Matrix4().identity();
  558. } // process bones and inverse bind matrix data
  559. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  560. const name = jointSource.array[ i ];
  561. const boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  562. build.joints.push( {
  563. name: name,
  564. boneInverse: boneInverse
  565. } );
  566. }
  567. return build; // array sort function
  568. function descending( a, b ) {
  569. return b.weight - a.weight;
  570. }
  571. }
  572. function getController( id ) {
  573. return getBuild( library.controllers[ id ], buildController );
  574. } // image
  575. function parseImage( xml ) {
  576. const data = {
  577. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  578. };
  579. library.images[ xml.getAttribute( 'id' ) ] = data;
  580. }
  581. function buildImage( data ) {
  582. if ( data.build !== undefined ) return data.build;
  583. return data.init_from;
  584. }
  585. function getImage( id ) {
  586. const data = library.images[ id ];
  587. if ( data !== undefined ) {
  588. return getBuild( data, buildImage );
  589. }
  590. console.warn( 'THREE.ColladaLoader: Couldn\'t find image with ID:', id );
  591. return null;
  592. } // effect
  593. function parseEffect( xml ) {
  594. const data = {};
  595. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  596. const child = xml.childNodes[ i ];
  597. if ( child.nodeType !== 1 ) continue;
  598. switch ( child.nodeName ) {
  599. case 'profile_COMMON':
  600. data.profile = parseEffectProfileCOMMON( child );
  601. break;
  602. }
  603. }
  604. library.effects[ xml.getAttribute( 'id' ) ] = data;
  605. }
  606. function parseEffectProfileCOMMON( xml ) {
  607. const data = {
  608. surfaces: {},
  609. samplers: {}
  610. };
  611. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  612. const child = xml.childNodes[ i ];
  613. if ( child.nodeType !== 1 ) continue;
  614. switch ( child.nodeName ) {
  615. case 'newparam':
  616. parseEffectNewparam( child, data );
  617. break;
  618. case 'technique':
  619. data.technique = parseEffectTechnique( child );
  620. break;
  621. case 'extra':
  622. data.extra = parseEffectExtra( child );
  623. break;
  624. }
  625. }
  626. return data;
  627. }
  628. function parseEffectNewparam( xml, data ) {
  629. const sid = xml.getAttribute( 'sid' );
  630. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  631. const child = xml.childNodes[ i ];
  632. if ( child.nodeType !== 1 ) continue;
  633. switch ( child.nodeName ) {
  634. case 'surface':
  635. data.surfaces[ sid ] = parseEffectSurface( child );
  636. break;
  637. case 'sampler2D':
  638. data.samplers[ sid ] = parseEffectSampler( child );
  639. break;
  640. }
  641. }
  642. }
  643. function parseEffectSurface( xml ) {
  644. const data = {};
  645. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  646. const child = xml.childNodes[ i ];
  647. if ( child.nodeType !== 1 ) continue;
  648. switch ( child.nodeName ) {
  649. case 'init_from':
  650. data.init_from = child.textContent;
  651. break;
  652. }
  653. }
  654. return data;
  655. }
  656. function parseEffectSampler( xml ) {
  657. const data = {};
  658. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  659. const child = xml.childNodes[ i ];
  660. if ( child.nodeType !== 1 ) continue;
  661. switch ( child.nodeName ) {
  662. case 'source':
  663. data.source = child.textContent;
  664. break;
  665. }
  666. }
  667. return data;
  668. }
  669. function parseEffectTechnique( xml ) {
  670. const data = {};
  671. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  672. const child = xml.childNodes[ i ];
  673. if ( child.nodeType !== 1 ) continue;
  674. switch ( child.nodeName ) {
  675. case 'constant':
  676. case 'lambert':
  677. case 'blinn':
  678. case 'phong':
  679. data.type = child.nodeName;
  680. data.parameters = parseEffectParameters( child );
  681. break;
  682. case 'extra':
  683. data.extra = parseEffectExtra( child );
  684. break;
  685. }
  686. }
  687. return data;
  688. }
  689. function parseEffectParameters( xml ) {
  690. const data = {};
  691. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  692. const child = xml.childNodes[ i ];
  693. if ( child.nodeType !== 1 ) continue;
  694. switch ( child.nodeName ) {
  695. case 'emission':
  696. case 'diffuse':
  697. case 'specular':
  698. case 'bump':
  699. case 'ambient':
  700. case 'shininess':
  701. case 'transparency':
  702. data[ child.nodeName ] = parseEffectParameter( child );
  703. break;
  704. case 'transparent':
  705. data[ child.nodeName ] = {
  706. opaque: child.getAttribute( 'opaque' ),
  707. data: parseEffectParameter( child )
  708. };
  709. break;
  710. }
  711. }
  712. return data;
  713. }
  714. function parseEffectParameter( xml ) {
  715. const data = {};
  716. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  717. const child = xml.childNodes[ i ];
  718. if ( child.nodeType !== 1 ) continue;
  719. switch ( child.nodeName ) {
  720. case 'color':
  721. data[ child.nodeName ] = parseFloats( child.textContent );
  722. break;
  723. case 'float':
  724. data[ child.nodeName ] = parseFloat( child.textContent );
  725. break;
  726. case 'texture':
  727. data[ child.nodeName ] = {
  728. id: child.getAttribute( 'texture' ),
  729. extra: parseEffectParameterTexture( child )
  730. };
  731. break;
  732. }
  733. }
  734. return data;
  735. }
  736. function parseEffectParameterTexture( xml ) {
  737. const data = {
  738. technique: {}
  739. };
  740. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  741. const child = xml.childNodes[ i ];
  742. if ( child.nodeType !== 1 ) continue;
  743. switch ( child.nodeName ) {
  744. case 'extra':
  745. parseEffectParameterTextureExtra( child, data );
  746. break;
  747. }
  748. }
  749. return data;
  750. }
  751. function parseEffectParameterTextureExtra( xml, data ) {
  752. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  753. const child = xml.childNodes[ i ];
  754. if ( child.nodeType !== 1 ) continue;
  755. switch ( child.nodeName ) {
  756. case 'technique':
  757. parseEffectParameterTextureExtraTechnique( child, data );
  758. break;
  759. }
  760. }
  761. }
  762. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  763. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  764. const child = xml.childNodes[ i ];
  765. if ( child.nodeType !== 1 ) continue;
  766. switch ( child.nodeName ) {
  767. case 'repeatU':
  768. case 'repeatV':
  769. case 'offsetU':
  770. case 'offsetV':
  771. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  772. break;
  773. case 'wrapU':
  774. case 'wrapV':
  775. // some files have values for wrapU/wrapV which become NaN via parseInt
  776. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  777. data.technique[ child.nodeName ] = 1;
  778. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  779. data.technique[ child.nodeName ] = 0;
  780. } else {
  781. data.technique[ child.nodeName ] = parseInt( child.textContent );
  782. }
  783. break;
  784. case 'bump':
  785. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  786. break;
  787. }
  788. }
  789. }
  790. function parseEffectExtra( xml ) {
  791. const data = {};
  792. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  793. const child = xml.childNodes[ i ];
  794. if ( child.nodeType !== 1 ) continue;
  795. switch ( child.nodeName ) {
  796. case 'technique':
  797. data.technique = parseEffectExtraTechnique( child );
  798. break;
  799. }
  800. }
  801. return data;
  802. }
  803. function parseEffectExtraTechnique( xml ) {
  804. const data = {};
  805. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  806. const child = xml.childNodes[ i ];
  807. if ( child.nodeType !== 1 ) continue;
  808. switch ( child.nodeName ) {
  809. case 'double_sided':
  810. data[ child.nodeName ] = parseInt( child.textContent );
  811. break;
  812. case 'bump':
  813. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  814. break;
  815. }
  816. }
  817. return data;
  818. }
  819. function parseEffectExtraTechniqueBump( xml ) {
  820. var data = {};
  821. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  822. var child = xml.childNodes[ i ];
  823. if ( child.nodeType !== 1 ) continue;
  824. switch ( child.nodeName ) {
  825. case 'texture':
  826. data[ child.nodeName ] = {
  827. id: child.getAttribute( 'texture' ),
  828. texcoord: child.getAttribute( 'texcoord' ),
  829. extra: parseEffectParameterTexture( child )
  830. };
  831. break;
  832. }
  833. }
  834. return data;
  835. }
  836. function buildEffect( data ) {
  837. return data;
  838. }
  839. function getEffect( id ) {
  840. return getBuild( library.effects[ id ], buildEffect );
  841. } // material
  842. function parseMaterial( xml ) {
  843. const data = {
  844. name: xml.getAttribute( 'name' )
  845. };
  846. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  847. const child = xml.childNodes[ i ];
  848. if ( child.nodeType !== 1 ) continue;
  849. switch ( child.nodeName ) {
  850. case 'instance_effect':
  851. data.url = parseId( child.getAttribute( 'url' ) );
  852. break;
  853. }
  854. }
  855. library.materials[ xml.getAttribute( 'id' ) ] = data;
  856. }
  857. function getTextureLoader( image ) {
  858. let loader;
  859. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  860. extension = extension.toLowerCase();
  861. switch ( extension ) {
  862. case 'tga':
  863. loader = tgaLoader;
  864. break;
  865. default:
  866. loader = textureLoader;
  867. }
  868. return loader;
  869. }
  870. function buildMaterial( data ) {
  871. const effect = getEffect( data.url );
  872. const technique = effect.profile.technique;
  873. let material;
  874. switch ( technique.type ) {
  875. case 'phong':
  876. case 'blinn':
  877. material = new THREE.MeshPhongMaterial();
  878. break;
  879. case 'lambert':
  880. material = new THREE.MeshLambertMaterial();
  881. break;
  882. default:
  883. material = new THREE.MeshBasicMaterial();
  884. break;
  885. }
  886. material.name = data.name || '';
  887. function getTexture( textureObject ) {
  888. const sampler = effect.profile.samplers[ textureObject.id ];
  889. let image = null; // get image
  890. if ( sampler !== undefined ) {
  891. const surface = effect.profile.surfaces[ sampler.source ];
  892. image = getImage( surface.init_from );
  893. } else {
  894. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  895. image = getImage( textureObject.id );
  896. } // create texture if image is avaiable
  897. if ( image !== null ) {
  898. const loader = getTextureLoader( image );
  899. if ( loader !== undefined ) {
  900. const texture = loader.load( image );
  901. const extra = textureObject.extra;
  902. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  903. const technique = extra.technique;
  904. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  905. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  906. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  907. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  908. } else {
  909. texture.wrapS = THREE.RepeatWrapping;
  910. texture.wrapT = THREE.RepeatWrapping;
  911. }
  912. return texture;
  913. } else {
  914. console.warn( 'THREE.ColladaLoader: THREE.Loader for texture %s not found.', image );
  915. return null;
  916. }
  917. } else {
  918. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  919. return null;
  920. }
  921. }
  922. const parameters = technique.parameters;
  923. for ( const key in parameters ) {
  924. const parameter = parameters[ key ];
  925. switch ( key ) {
  926. case 'diffuse':
  927. if ( parameter.color ) material.color.fromArray( parameter.color );
  928. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  929. break;
  930. case 'specular':
  931. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  932. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  933. break;
  934. case 'bump':
  935. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  936. break;
  937. case 'ambient':
  938. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture );
  939. break;
  940. case 'shininess':
  941. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  942. break;
  943. case 'emission':
  944. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  945. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  946. break;
  947. }
  948. } //
  949. let transparent = parameters[ 'transparent' ];
  950. let transparency = parameters[ 'transparency' ]; // <transparency> does not exist but <transparent>
  951. if ( transparency === undefined && transparent ) {
  952. transparency = {
  953. float: 1
  954. };
  955. } // <transparent> does not exist but <transparency>
  956. if ( transparent === undefined && transparency ) {
  957. transparent = {
  958. opaque: 'A_ONE',
  959. data: {
  960. color: [ 1, 1, 1, 1 ]
  961. }
  962. };
  963. }
  964. if ( transparent && transparency ) {
  965. // handle case if a texture exists but no color
  966. if ( transparent.data.texture ) {
  967. // we do not set an alpha map (see #13792)
  968. material.transparent = true;
  969. } else {
  970. const color = transparent.data.color;
  971. switch ( transparent.opaque ) {
  972. case 'A_ONE':
  973. material.opacity = color[ 3 ] * transparency.float;
  974. break;
  975. case 'RGB_ZERO':
  976. material.opacity = 1 - color[ 0 ] * transparency.float;
  977. break;
  978. case 'A_ZERO':
  979. material.opacity = 1 - color[ 3 ] * transparency.float;
  980. break;
  981. case 'RGB_ONE':
  982. material.opacity = color[ 0 ] * transparency.float;
  983. break;
  984. default:
  985. material.opacity = 1 - transparency.float;
  986. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  987. }
  988. if ( material.opacity < 1 ) material.transparent = true;
  989. }
  990. } //
  991. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  992. const techniques = technique.extra.technique;
  993. for ( const k in techniques ) {
  994. const v = techniques[ k ];
  995. switch ( k ) {
  996. case 'double_sided':
  997. material.side = v === 1 ? THREE.DoubleSide : THREE.FrontSide;
  998. break;
  999. case 'bump':
  1000. material.normalMap = getTexture( v.texture );
  1001. material.normalScale = new THREE.Vector2( 1, 1 );
  1002. break;
  1003. }
  1004. }
  1005. }
  1006. return material;
  1007. }
  1008. function getMaterial( id ) {
  1009. return getBuild( library.materials[ id ], buildMaterial );
  1010. } // camera
  1011. function parseCamera( xml ) {
  1012. const data = {
  1013. name: xml.getAttribute( 'name' )
  1014. };
  1015. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1016. const child = xml.childNodes[ i ];
  1017. if ( child.nodeType !== 1 ) continue;
  1018. switch ( child.nodeName ) {
  1019. case 'optics':
  1020. data.optics = parseCameraOptics( child );
  1021. break;
  1022. }
  1023. }
  1024. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  1025. }
  1026. function parseCameraOptics( xml ) {
  1027. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1028. const child = xml.childNodes[ i ];
  1029. switch ( child.nodeName ) {
  1030. case 'technique_common':
  1031. return parseCameraTechnique( child );
  1032. }
  1033. }
  1034. return {};
  1035. }
  1036. function parseCameraTechnique( xml ) {
  1037. const data = {};
  1038. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1039. const child = xml.childNodes[ i ];
  1040. switch ( child.nodeName ) {
  1041. case 'perspective':
  1042. case 'orthographic':
  1043. data.technique = child.nodeName;
  1044. data.parameters = parseCameraParameters( child );
  1045. break;
  1046. }
  1047. }
  1048. return data;
  1049. }
  1050. function parseCameraParameters( xml ) {
  1051. const data = {};
  1052. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1053. const child = xml.childNodes[ i ];
  1054. switch ( child.nodeName ) {
  1055. case 'xfov':
  1056. case 'yfov':
  1057. case 'xmag':
  1058. case 'ymag':
  1059. case 'znear':
  1060. case 'zfar':
  1061. case 'aspect_ratio':
  1062. data[ child.nodeName ] = parseFloat( child.textContent );
  1063. break;
  1064. }
  1065. }
  1066. return data;
  1067. }
  1068. function buildCamera( data ) {
  1069. let camera;
  1070. switch ( data.optics.technique ) {
  1071. case 'perspective':
  1072. camera = new THREE.PerspectiveCamera( data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar );
  1073. break;
  1074. case 'orthographic':
  1075. let ymag = data.optics.parameters.ymag;
  1076. let xmag = data.optics.parameters.xmag;
  1077. const aspectRatio = data.optics.parameters.aspect_ratio;
  1078. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1079. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1080. xmag *= 0.5;
  1081. ymag *= 0.5;
  1082. camera = new THREE.OrthographicCamera( - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1083. data.optics.parameters.znear, data.optics.parameters.zfar );
  1084. break;
  1085. default:
  1086. camera = new THREE.PerspectiveCamera();
  1087. break;
  1088. }
  1089. camera.name = data.name || '';
  1090. return camera;
  1091. }
  1092. function getCamera( id ) {
  1093. const data = library.cameras[ id ];
  1094. if ( data !== undefined ) {
  1095. return getBuild( data, buildCamera );
  1096. }
  1097. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1098. return null;
  1099. } // light
  1100. function parseLight( xml ) {
  1101. let data = {};
  1102. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1103. const child = xml.childNodes[ i ];
  1104. if ( child.nodeType !== 1 ) continue;
  1105. switch ( child.nodeName ) {
  1106. case 'technique_common':
  1107. data = parseLightTechnique( child );
  1108. break;
  1109. }
  1110. }
  1111. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1112. }
  1113. function parseLightTechnique( xml ) {
  1114. const data = {};
  1115. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1116. const child = xml.childNodes[ i ];
  1117. if ( child.nodeType !== 1 ) continue;
  1118. switch ( child.nodeName ) {
  1119. case 'directional':
  1120. case 'point':
  1121. case 'spot':
  1122. case 'ambient':
  1123. data.technique = child.nodeName;
  1124. data.parameters = parseLightParameters( child );
  1125. }
  1126. }
  1127. return data;
  1128. }
  1129. function parseLightParameters( xml ) {
  1130. const data = {};
  1131. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1132. const child = xml.childNodes[ i ];
  1133. if ( child.nodeType !== 1 ) continue;
  1134. switch ( child.nodeName ) {
  1135. case 'color':
  1136. const array = parseFloats( child.textContent );
  1137. data.color = new THREE.Color().fromArray( array );
  1138. break;
  1139. case 'falloff_angle':
  1140. data.falloffAngle = parseFloat( child.textContent );
  1141. break;
  1142. case 'quadratic_attenuation':
  1143. const f = parseFloat( child.textContent );
  1144. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1145. break;
  1146. }
  1147. }
  1148. return data;
  1149. }
  1150. function buildLight( data ) {
  1151. let light;
  1152. switch ( data.technique ) {
  1153. case 'directional':
  1154. light = new THREE.DirectionalLight();
  1155. break;
  1156. case 'point':
  1157. light = new THREE.PointLight();
  1158. break;
  1159. case 'spot':
  1160. light = new THREE.SpotLight();
  1161. break;
  1162. case 'ambient':
  1163. light = new THREE.AmbientLight();
  1164. break;
  1165. }
  1166. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1167. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1168. return light;
  1169. }
  1170. function getLight( id ) {
  1171. const data = library.lights[ id ];
  1172. if ( data !== undefined ) {
  1173. return getBuild( data, buildLight );
  1174. }
  1175. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1176. return null;
  1177. } // geometry
  1178. function parseGeometry( xml ) {
  1179. const data = {
  1180. name: xml.getAttribute( 'name' ),
  1181. sources: {},
  1182. vertices: {},
  1183. primitives: []
  1184. };
  1185. const mesh = getElementsByTagName( xml, 'mesh' )[ 0 ]; // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  1186. if ( mesh === undefined ) return;
  1187. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1188. const child = mesh.childNodes[ i ];
  1189. if ( child.nodeType !== 1 ) continue;
  1190. const id = child.getAttribute( 'id' );
  1191. switch ( child.nodeName ) {
  1192. case 'source':
  1193. data.sources[ id ] = parseSource( child );
  1194. break;
  1195. case 'vertices':
  1196. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1197. data.vertices = parseGeometryVertices( child );
  1198. break;
  1199. case 'polygons':
  1200. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1201. break;
  1202. case 'lines':
  1203. case 'linestrips':
  1204. case 'polylist':
  1205. case 'triangles':
  1206. data.primitives.push( parseGeometryPrimitive( child ) );
  1207. break;
  1208. default:
  1209. console.log( child );
  1210. }
  1211. }
  1212. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1213. }
  1214. function parseSource( xml ) {
  1215. const data = {
  1216. array: [],
  1217. stride: 3
  1218. };
  1219. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1220. const child = xml.childNodes[ i ];
  1221. if ( child.nodeType !== 1 ) continue;
  1222. switch ( child.nodeName ) {
  1223. case 'float_array':
  1224. data.array = parseFloats( child.textContent );
  1225. break;
  1226. case 'Name_array':
  1227. data.array = parseStrings( child.textContent );
  1228. break;
  1229. case 'technique_common':
  1230. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1231. if ( accessor !== undefined ) {
  1232. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1233. }
  1234. break;
  1235. }
  1236. }
  1237. return data;
  1238. }
  1239. function parseGeometryVertices( xml ) {
  1240. const data = {};
  1241. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1242. const child = xml.childNodes[ i ];
  1243. if ( child.nodeType !== 1 ) continue;
  1244. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1245. }
  1246. return data;
  1247. }
  1248. function parseGeometryPrimitive( xml ) {
  1249. const primitive = {
  1250. type: xml.nodeName,
  1251. material: xml.getAttribute( 'material' ),
  1252. count: parseInt( xml.getAttribute( 'count' ) ),
  1253. inputs: {},
  1254. stride: 0,
  1255. hasUV: false
  1256. };
  1257. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1258. const child = xml.childNodes[ i ];
  1259. if ( child.nodeType !== 1 ) continue;
  1260. switch ( child.nodeName ) {
  1261. case 'input':
  1262. const id = parseId( child.getAttribute( 'source' ) );
  1263. const semantic = child.getAttribute( 'semantic' );
  1264. const offset = parseInt( child.getAttribute( 'offset' ) );
  1265. const set = parseInt( child.getAttribute( 'set' ) );
  1266. const inputname = set > 0 ? semantic + set : semantic;
  1267. primitive.inputs[ inputname ] = {
  1268. id: id,
  1269. offset: offset
  1270. };
  1271. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1272. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1273. break;
  1274. case 'vcount':
  1275. primitive.vcount = parseInts( child.textContent );
  1276. break;
  1277. case 'p':
  1278. primitive.p = parseInts( child.textContent );
  1279. break;
  1280. }
  1281. }
  1282. return primitive;
  1283. }
  1284. function groupPrimitives( primitives ) {
  1285. const build = {};
  1286. for ( let i = 0; i < primitives.length; i ++ ) {
  1287. const primitive = primitives[ i ];
  1288. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1289. build[ primitive.type ].push( primitive );
  1290. }
  1291. return build;
  1292. }
  1293. function checkUVCoordinates( primitives ) {
  1294. let count = 0;
  1295. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1296. const primitive = primitives[ i ];
  1297. if ( primitive.hasUV === true ) {
  1298. count ++;
  1299. }
  1300. }
  1301. if ( count > 0 && count < primitives.length ) {
  1302. primitives.uvsNeedsFix = true;
  1303. }
  1304. }
  1305. function buildGeometry( data ) {
  1306. const build = {};
  1307. const sources = data.sources;
  1308. const vertices = data.vertices;
  1309. const primitives = data.primitives;
  1310. if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives
  1311. // first, we group all primitives by their type
  1312. const groupedPrimitives = groupPrimitives( primitives );
  1313. for ( const type in groupedPrimitives ) {
  1314. const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1315. checkUVCoordinates( primitiveType ); // third, create a buffer geometry for each type of primitives
  1316. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1317. }
  1318. return build;
  1319. }
  1320. function buildGeometryType( primitives, sources, vertices ) {
  1321. const build = {};
  1322. const position = {
  1323. array: [],
  1324. stride: 0
  1325. };
  1326. const normal = {
  1327. array: [],
  1328. stride: 0
  1329. };
  1330. const uv = {
  1331. array: [],
  1332. stride: 0
  1333. };
  1334. const uv2 = {
  1335. array: [],
  1336. stride: 0
  1337. };
  1338. const color = {
  1339. array: [],
  1340. stride: 0
  1341. };
  1342. const skinIndex = {
  1343. array: [],
  1344. stride: 4
  1345. };
  1346. const skinWeight = {
  1347. array: [],
  1348. stride: 4
  1349. };
  1350. const geometry = new THREE.BufferGeometry();
  1351. const materialKeys = [];
  1352. let start = 0;
  1353. for ( let p = 0; p < primitives.length; p ++ ) {
  1354. const primitive = primitives[ p ];
  1355. const inputs = primitive.inputs; // groups
  1356. let count = 0;
  1357. switch ( primitive.type ) {
  1358. case 'lines':
  1359. case 'linestrips':
  1360. count = primitive.count * 2;
  1361. break;
  1362. case 'triangles':
  1363. count = primitive.count * 3;
  1364. break;
  1365. case 'polylist':
  1366. for ( let g = 0; g < primitive.count; g ++ ) {
  1367. const vc = primitive.vcount[ g ];
  1368. switch ( vc ) {
  1369. case 3:
  1370. count += 3; // single triangle
  1371. break;
  1372. case 4:
  1373. count += 6; // quad, subdivided into two triangles
  1374. break;
  1375. default:
  1376. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1377. break;
  1378. }
  1379. }
  1380. break;
  1381. default:
  1382. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  1383. }
  1384. geometry.addGroup( start, count, p );
  1385. start += count; // material
  1386. if ( primitive.material ) {
  1387. materialKeys.push( primitive.material );
  1388. } // geometry data
  1389. for ( const name in inputs ) {
  1390. const input = inputs[ name ];
  1391. switch ( name ) {
  1392. case 'VERTEX':
  1393. for ( const key in vertices ) {
  1394. const id = vertices[ key ];
  1395. switch ( key ) {
  1396. case 'POSITION':
  1397. const prevLength = position.array.length;
  1398. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1399. position.stride = sources[ id ].stride;
  1400. if ( sources.skinWeights && sources.skinIndices ) {
  1401. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1402. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1403. } // see #3803
  1404. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1405. const count = ( position.array.length - prevLength ) / position.stride;
  1406. for ( let i = 0; i < count; i ++ ) {
  1407. // fill missing uv coordinates
  1408. uv.array.push( 0, 0 );
  1409. }
  1410. }
  1411. break;
  1412. case 'NORMAL':
  1413. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1414. normal.stride = sources[ id ].stride;
  1415. break;
  1416. case 'COLOR':
  1417. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1418. color.stride = sources[ id ].stride;
  1419. break;
  1420. case 'TEXCOORD':
  1421. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1422. uv.stride = sources[ id ].stride;
  1423. break;
  1424. case 'TEXCOORD1':
  1425. buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
  1426. uv.stride = sources[ id ].stride;
  1427. break;
  1428. default:
  1429. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1430. }
  1431. }
  1432. break;
  1433. case 'NORMAL':
  1434. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1435. normal.stride = sources[ input.id ].stride;
  1436. break;
  1437. case 'COLOR':
  1438. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  1439. color.stride = sources[ input.id ].stride;
  1440. break;
  1441. case 'TEXCOORD':
  1442. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1443. uv.stride = sources[ input.id ].stride;
  1444. break;
  1445. case 'TEXCOORD1':
  1446. buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
  1447. uv2.stride = sources[ input.id ].stride;
  1448. break;
  1449. }
  1450. }
  1451. } // build geometry
  1452. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  1453. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  1454. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  1455. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  1456. if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new THREE.Float32BufferAttribute( uv2.array, uv2.stride ) );
  1457. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1458. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1459. build.data = geometry;
  1460. build.type = primitives[ 0 ].type;
  1461. build.materialKeys = materialKeys;
  1462. return build;
  1463. }
  1464. function buildGeometryData( primitive, source, offset, array ) {
  1465. const indices = primitive.p;
  1466. const stride = primitive.stride;
  1467. const vcount = primitive.vcount;
  1468. function pushVector( i ) {
  1469. let index = indices[ i + offset ] * sourceStride;
  1470. const length = index + sourceStride;
  1471. for ( ; index < length; index ++ ) {
  1472. array.push( sourceArray[ index ] );
  1473. }
  1474. }
  1475. const sourceArray = source.array;
  1476. const sourceStride = source.stride;
  1477. if ( primitive.vcount !== undefined ) {
  1478. let index = 0;
  1479. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1480. const count = vcount[ i ];
  1481. if ( count === 4 ) {
  1482. const a = index + stride * 0;
  1483. const b = index + stride * 1;
  1484. const c = index + stride * 2;
  1485. const d = index + stride * 3;
  1486. pushVector( a );
  1487. pushVector( b );
  1488. pushVector( d );
  1489. pushVector( b );
  1490. pushVector( c );
  1491. pushVector( d );
  1492. } else if ( count === 3 ) {
  1493. const a = index + stride * 0;
  1494. const b = index + stride * 1;
  1495. const c = index + stride * 2;
  1496. pushVector( a );
  1497. pushVector( b );
  1498. pushVector( c );
  1499. } else if ( count > 4 ) {
  1500. for ( let k = 1, kl = count - 2; k <= kl; k ++ ) {
  1501. const a = index + stride * 0;
  1502. const b = index + stride * k;
  1503. const c = index + stride * ( k + 1 );
  1504. pushVector( a );
  1505. pushVector( b );
  1506. pushVector( c );
  1507. }
  1508. }
  1509. index += stride * count;
  1510. }
  1511. } else {
  1512. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1513. pushVector( i );
  1514. }
  1515. }
  1516. }
  1517. function getGeometry( id ) {
  1518. return getBuild( library.geometries[ id ], buildGeometry );
  1519. } // kinematics
  1520. function parseKinematicsModel( xml ) {
  1521. const data = {
  1522. name: xml.getAttribute( 'name' ) || '',
  1523. joints: {},
  1524. links: []
  1525. };
  1526. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1527. const child = xml.childNodes[ i ];
  1528. if ( child.nodeType !== 1 ) continue;
  1529. switch ( child.nodeName ) {
  1530. case 'technique_common':
  1531. parseKinematicsTechniqueCommon( child, data );
  1532. break;
  1533. }
  1534. }
  1535. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1536. }
  1537. function buildKinematicsModel( data ) {
  1538. if ( data.build !== undefined ) return data.build;
  1539. return data;
  1540. }
  1541. function getKinematicsModel( id ) {
  1542. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1543. }
  1544. function parseKinematicsTechniqueCommon( xml, data ) {
  1545. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1546. const child = xml.childNodes[ i ];
  1547. if ( child.nodeType !== 1 ) continue;
  1548. switch ( child.nodeName ) {
  1549. case 'joint':
  1550. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1551. break;
  1552. case 'link':
  1553. data.links.push( parseKinematicsLink( child ) );
  1554. break;
  1555. }
  1556. }
  1557. }
  1558. function parseKinematicsJoint( xml ) {
  1559. let data;
  1560. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1561. const child = xml.childNodes[ i ];
  1562. if ( child.nodeType !== 1 ) continue;
  1563. switch ( child.nodeName ) {
  1564. case 'prismatic':
  1565. case 'revolute':
  1566. data = parseKinematicsJointParameter( child );
  1567. break;
  1568. }
  1569. }
  1570. return data;
  1571. }
  1572. function parseKinematicsJointParameter( xml ) {
  1573. const data = {
  1574. sid: xml.getAttribute( 'sid' ),
  1575. name: xml.getAttribute( 'name' ) || '',
  1576. axis: new THREE.Vector3(),
  1577. limits: {
  1578. min: 0,
  1579. max: 0
  1580. },
  1581. type: xml.nodeName,
  1582. static: false,
  1583. zeroPosition: 0,
  1584. middlePosition: 0
  1585. };
  1586. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1587. const child = xml.childNodes[ i ];
  1588. if ( child.nodeType !== 1 ) continue;
  1589. switch ( child.nodeName ) {
  1590. case 'axis':
  1591. const array = parseFloats( child.textContent );
  1592. data.axis.fromArray( array );
  1593. break;
  1594. case 'limits':
  1595. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1596. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1597. data.limits.max = parseFloat( max.textContent );
  1598. data.limits.min = parseFloat( min.textContent );
  1599. break;
  1600. }
  1601. } // if min is equal to or greater than max, consider the joint static
  1602. if ( data.limits.min >= data.limits.max ) {
  1603. data.static = true;
  1604. } // calculate middle position
  1605. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1606. return data;
  1607. }
  1608. function parseKinematicsLink( xml ) {
  1609. const data = {
  1610. sid: xml.getAttribute( 'sid' ),
  1611. name: xml.getAttribute( 'name' ) || '',
  1612. attachments: [],
  1613. transforms: []
  1614. };
  1615. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1616. const child = xml.childNodes[ i ];
  1617. if ( child.nodeType !== 1 ) continue;
  1618. switch ( child.nodeName ) {
  1619. case 'attachment_full':
  1620. data.attachments.push( parseKinematicsAttachment( child ) );
  1621. break;
  1622. case 'matrix':
  1623. case 'translate':
  1624. case 'rotate':
  1625. data.transforms.push( parseKinematicsTransform( child ) );
  1626. break;
  1627. }
  1628. }
  1629. return data;
  1630. }
  1631. function parseKinematicsAttachment( xml ) {
  1632. const data = {
  1633. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1634. transforms: [],
  1635. links: []
  1636. };
  1637. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1638. const child = xml.childNodes[ i ];
  1639. if ( child.nodeType !== 1 ) continue;
  1640. switch ( child.nodeName ) {
  1641. case 'link':
  1642. data.links.push( parseKinematicsLink( child ) );
  1643. break;
  1644. case 'matrix':
  1645. case 'translate':
  1646. case 'rotate':
  1647. data.transforms.push( parseKinematicsTransform( child ) );
  1648. break;
  1649. }
  1650. }
  1651. return data;
  1652. }
  1653. function parseKinematicsTransform( xml ) {
  1654. const data = {
  1655. type: xml.nodeName
  1656. };
  1657. const array = parseFloats( xml.textContent );
  1658. switch ( data.type ) {
  1659. case 'matrix':
  1660. data.obj = new THREE.Matrix4();
  1661. data.obj.fromArray( array ).transpose();
  1662. break;
  1663. case 'translate':
  1664. data.obj = new THREE.Vector3();
  1665. data.obj.fromArray( array );
  1666. break;
  1667. case 'rotate':
  1668. data.obj = new THREE.Vector3();
  1669. data.obj.fromArray( array );
  1670. data.angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1671. break;
  1672. }
  1673. return data;
  1674. } // physics
  1675. function parsePhysicsModel( xml ) {
  1676. const data = {
  1677. name: xml.getAttribute( 'name' ) || '',
  1678. rigidBodies: {}
  1679. };
  1680. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1681. const child = xml.childNodes[ i ];
  1682. if ( child.nodeType !== 1 ) continue;
  1683. switch ( child.nodeName ) {
  1684. case 'rigid_body':
  1685. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1686. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1687. break;
  1688. }
  1689. }
  1690. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1691. }
  1692. function parsePhysicsRigidBody( xml, data ) {
  1693. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1694. const child = xml.childNodes[ i ];
  1695. if ( child.nodeType !== 1 ) continue;
  1696. switch ( child.nodeName ) {
  1697. case 'technique_common':
  1698. parsePhysicsTechniqueCommon( child, data );
  1699. break;
  1700. }
  1701. }
  1702. }
  1703. function parsePhysicsTechniqueCommon( xml, data ) {
  1704. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1705. const child = xml.childNodes[ i ];
  1706. if ( child.nodeType !== 1 ) continue;
  1707. switch ( child.nodeName ) {
  1708. case 'inertia':
  1709. data.inertia = parseFloats( child.textContent );
  1710. break;
  1711. case 'mass':
  1712. data.mass = parseFloats( child.textContent )[ 0 ];
  1713. break;
  1714. }
  1715. }
  1716. } // scene
  1717. function parseKinematicsScene( xml ) {
  1718. const data = {
  1719. bindJointAxis: []
  1720. };
  1721. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1722. const child = xml.childNodes[ i ];
  1723. if ( child.nodeType !== 1 ) continue;
  1724. switch ( child.nodeName ) {
  1725. case 'bind_joint_axis':
  1726. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1727. break;
  1728. }
  1729. }
  1730. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1731. }
  1732. function parseKinematicsBindJointAxis( xml ) {
  1733. const data = {
  1734. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1735. };
  1736. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1737. const child = xml.childNodes[ i ];
  1738. if ( child.nodeType !== 1 ) continue;
  1739. switch ( child.nodeName ) {
  1740. case 'axis':
  1741. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1742. data.axis = param.textContent;
  1743. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1744. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  1745. break;
  1746. }
  1747. }
  1748. return data;
  1749. }
  1750. function buildKinematicsScene( data ) {
  1751. if ( data.build !== undefined ) return data.build;
  1752. return data;
  1753. }
  1754. function getKinematicsScene( id ) {
  1755. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1756. }
  1757. function setupKinematics() {
  1758. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1759. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1760. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1761. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1762. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1763. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1764. const visualScene = getVisualScene( visualSceneId );
  1765. const bindJointAxis = kinematicsScene.bindJointAxis;
  1766. const jointMap = {};
  1767. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1768. const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1769. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1770. if ( targetElement ) {
  1771. // get the parent of the transform element
  1772. const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene
  1773. connect( axis.jointIndex, parentVisualElement );
  1774. }
  1775. }
  1776. function connect( jointIndex, visualElement ) {
  1777. const visualElementName = visualElement.getAttribute( 'name' );
  1778. const joint = kinematicsModel.joints[ jointIndex ];
  1779. visualScene.traverse( function ( object ) {
  1780. if ( object.name === visualElementName ) {
  1781. jointMap[ jointIndex ] = {
  1782. object: object,
  1783. transforms: buildTransformList( visualElement ),
  1784. joint: joint,
  1785. position: joint.zeroPosition
  1786. };
  1787. }
  1788. } );
  1789. }
  1790. const m0 = new THREE.Matrix4();
  1791. kinematics = {
  1792. joints: kinematicsModel && kinematicsModel.joints,
  1793. getJointValue: function ( jointIndex ) {
  1794. const jointData = jointMap[ jointIndex ];
  1795. if ( jointData ) {
  1796. return jointData.position;
  1797. } else {
  1798. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1799. }
  1800. },
  1801. setJointValue: function ( jointIndex, value ) {
  1802. const jointData = jointMap[ jointIndex ];
  1803. if ( jointData ) {
  1804. const joint = jointData.joint;
  1805. if ( value > joint.limits.max || value < joint.limits.min ) {
  1806. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1807. } else if ( joint.static ) {
  1808. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1809. } else {
  1810. const object = jointData.object;
  1811. const axis = joint.axis;
  1812. const transforms = jointData.transforms;
  1813. matrix.identity(); // each update, we have to apply all transforms in the correct order
  1814. for ( let i = 0; i < transforms.length; i ++ ) {
  1815. const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value
  1816. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1817. switch ( joint.type ) {
  1818. case 'revolute':
  1819. matrix.multiply( m0.makeRotationAxis( axis, THREE.MathUtils.degToRad( value ) ) );
  1820. break;
  1821. case 'prismatic':
  1822. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1823. break;
  1824. default:
  1825. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1826. break;
  1827. }
  1828. } else {
  1829. switch ( transform.type ) {
  1830. case 'matrix':
  1831. matrix.multiply( transform.obj );
  1832. break;
  1833. case 'translate':
  1834. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1835. break;
  1836. case 'scale':
  1837. matrix.scale( transform.obj );
  1838. break;
  1839. case 'rotate':
  1840. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1841. break;
  1842. }
  1843. }
  1844. }
  1845. object.matrix.copy( matrix );
  1846. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1847. jointMap[ jointIndex ].position = value;
  1848. }
  1849. } else {
  1850. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1851. }
  1852. }
  1853. };
  1854. }
  1855. function buildTransformList( node ) {
  1856. const transforms = [];
  1857. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1858. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1859. const child = xml.childNodes[ i ];
  1860. if ( child.nodeType !== 1 ) continue;
  1861. let array, vector;
  1862. switch ( child.nodeName ) {
  1863. case 'matrix':
  1864. array = parseFloats( child.textContent );
  1865. const matrix = new THREE.Matrix4().fromArray( array ).transpose();
  1866. transforms.push( {
  1867. sid: child.getAttribute( 'sid' ),
  1868. type: child.nodeName,
  1869. obj: matrix
  1870. } );
  1871. break;
  1872. case 'translate':
  1873. case 'scale':
  1874. array = parseFloats( child.textContent );
  1875. vector = new THREE.Vector3().fromArray( array );
  1876. transforms.push( {
  1877. sid: child.getAttribute( 'sid' ),
  1878. type: child.nodeName,
  1879. obj: vector
  1880. } );
  1881. break;
  1882. case 'rotate':
  1883. array = parseFloats( child.textContent );
  1884. vector = new THREE.Vector3().fromArray( array );
  1885. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1886. transforms.push( {
  1887. sid: child.getAttribute( 'sid' ),
  1888. type: child.nodeName,
  1889. obj: vector,
  1890. angle: angle
  1891. } );
  1892. break;
  1893. }
  1894. }
  1895. return transforms;
  1896. } // nodes
  1897. function prepareNodes( xml ) {
  1898. const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes
  1899. for ( let i = 0; i < elements.length; i ++ ) {
  1900. const element = elements[ i ];
  1901. if ( element.hasAttribute( 'id' ) === false ) {
  1902. element.setAttribute( 'id', generateId() );
  1903. }
  1904. }
  1905. }
  1906. const matrix = new THREE.Matrix4();
  1907. const vector = new THREE.Vector3();
  1908. function parseNode( xml ) {
  1909. const data = {
  1910. name: xml.getAttribute( 'name' ) || '',
  1911. type: xml.getAttribute( 'type' ),
  1912. id: xml.getAttribute( 'id' ),
  1913. sid: xml.getAttribute( 'sid' ),
  1914. matrix: new THREE.Matrix4(),
  1915. nodes: [],
  1916. instanceCameras: [],
  1917. instanceControllers: [],
  1918. instanceLights: [],
  1919. instanceGeometries: [],
  1920. instanceNodes: [],
  1921. transforms: {}
  1922. };
  1923. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1924. const child = xml.childNodes[ i ];
  1925. if ( child.nodeType !== 1 ) continue;
  1926. let array;
  1927. switch ( child.nodeName ) {
  1928. case 'node':
  1929. data.nodes.push( child.getAttribute( 'id' ) );
  1930. parseNode( child );
  1931. break;
  1932. case 'instance_camera':
  1933. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  1934. break;
  1935. case 'instance_controller':
  1936. data.instanceControllers.push( parseNodeInstance( child ) );
  1937. break;
  1938. case 'instance_light':
  1939. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  1940. break;
  1941. case 'instance_geometry':
  1942. data.instanceGeometries.push( parseNodeInstance( child ) );
  1943. break;
  1944. case 'instance_node':
  1945. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  1946. break;
  1947. case 'matrix':
  1948. array = parseFloats( child.textContent );
  1949. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  1950. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1951. break;
  1952. case 'translate':
  1953. array = parseFloats( child.textContent );
  1954. vector.fromArray( array );
  1955. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  1956. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1957. break;
  1958. case 'rotate':
  1959. array = parseFloats( child.textContent );
  1960. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1961. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  1962. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1963. break;
  1964. case 'scale':
  1965. array = parseFloats( child.textContent );
  1966. data.matrix.scale( vector.fromArray( array ) );
  1967. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1968. break;
  1969. case 'extra':
  1970. break;
  1971. default:
  1972. console.log( child );
  1973. }
  1974. }
  1975. if ( hasNode( data.id ) ) {
  1976. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  1977. } else {
  1978. library.nodes[ data.id ] = data;
  1979. }
  1980. return data;
  1981. }
  1982. function parseNodeInstance( xml ) {
  1983. const data = {
  1984. id: parseId( xml.getAttribute( 'url' ) ),
  1985. materials: {},
  1986. skeletons: []
  1987. };
  1988. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1989. const child = xml.childNodes[ i ];
  1990. switch ( child.nodeName ) {
  1991. case 'bind_material':
  1992. const instances = child.getElementsByTagName( 'instance_material' );
  1993. for ( let j = 0; j < instances.length; j ++ ) {
  1994. const instance = instances[ j ];
  1995. const symbol = instance.getAttribute( 'symbol' );
  1996. const target = instance.getAttribute( 'target' );
  1997. data.materials[ symbol ] = parseId( target );
  1998. }
  1999. break;
  2000. case 'skeleton':
  2001. data.skeletons.push( parseId( child.textContent ) );
  2002. break;
  2003. default:
  2004. break;
  2005. }
  2006. }
  2007. return data;
  2008. }
  2009. function buildSkeleton( skeletons, joints ) {
  2010. const boneData = [];
  2011. const sortedBoneData = [];
  2012. let i, j, data; // a skeleton can have multiple root bones. collada expresses this
  2013. // situtation with multiple "skeleton" tags per controller instance
  2014. for ( i = 0; i < skeletons.length; i ++ ) {
  2015. const skeleton = skeletons[ i ];
  2016. let root;
  2017. if ( hasNode( skeleton ) ) {
  2018. root = getNode( skeleton );
  2019. buildBoneHierarchy( root, joints, boneData );
  2020. } else if ( hasVisualScene( skeleton ) ) {
  2021. // handle case where the skeleton refers to the visual scene (#13335)
  2022. const visualScene = library.visualScenes[ skeleton ];
  2023. const children = visualScene.children;
  2024. for ( let j = 0; j < children.length; j ++ ) {
  2025. const child = children[ j ];
  2026. if ( child.type === 'JOINT' ) {
  2027. const root = getNode( child.id );
  2028. buildBoneHierarchy( root, joints, boneData );
  2029. }
  2030. }
  2031. } else {
  2032. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  2033. }
  2034. } // sort bone data (the order is defined in the corresponding controller)
  2035. for ( i = 0; i < joints.length; i ++ ) {
  2036. for ( j = 0; j < boneData.length; j ++ ) {
  2037. data = boneData[ j ];
  2038. if ( data.bone.name === joints[ i ].name ) {
  2039. sortedBoneData[ i ] = data;
  2040. data.processed = true;
  2041. break;
  2042. }
  2043. }
  2044. } // add unprocessed bone data at the end of the list
  2045. for ( i = 0; i < boneData.length; i ++ ) {
  2046. data = boneData[ i ];
  2047. if ( data.processed === false ) {
  2048. sortedBoneData.push( data );
  2049. data.processed = true;
  2050. }
  2051. } // setup arrays for skeleton creation
  2052. const bones = [];
  2053. const boneInverses = [];
  2054. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2055. data = sortedBoneData[ i ];
  2056. bones.push( data.bone );
  2057. boneInverses.push( data.boneInverse );
  2058. }
  2059. return new THREE.Skeleton( bones, boneInverses );
  2060. }
  2061. function buildBoneHierarchy( root, joints, boneData ) {
  2062. // setup bone data from visual scene
  2063. root.traverse( function ( object ) {
  2064. if ( object.isBone === true ) {
  2065. let boneInverse; // retrieve the boneInverse from the controller data
  2066. for ( let i = 0; i < joints.length; i ++ ) {
  2067. const joint = joints[ i ];
  2068. if ( joint.name === object.name ) {
  2069. boneInverse = joint.boneInverse;
  2070. break;
  2071. }
  2072. }
  2073. if ( boneInverse === undefined ) {
  2074. // Unfortunately, there can be joints in the visual scene that are not part of the
  2075. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2076. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2077. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2078. // ensure a correct animation of the model.
  2079. boneInverse = new THREE.Matrix4();
  2080. }
  2081. boneData.push( {
  2082. bone: object,
  2083. boneInverse: boneInverse,
  2084. processed: false
  2085. } );
  2086. }
  2087. } );
  2088. }
  2089. function buildNode( data ) {
  2090. const objects = [];
  2091. const matrix = data.matrix;
  2092. const nodes = data.nodes;
  2093. const type = data.type;
  2094. const instanceCameras = data.instanceCameras;
  2095. const instanceControllers = data.instanceControllers;
  2096. const instanceLights = data.instanceLights;
  2097. const instanceGeometries = data.instanceGeometries;
  2098. const instanceNodes = data.instanceNodes; // nodes
  2099. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2100. objects.push( getNode( nodes[ i ] ) );
  2101. } // instance cameras
  2102. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2103. const instanceCamera = getCamera( instanceCameras[ i ] );
  2104. if ( instanceCamera !== null ) {
  2105. objects.push( instanceCamera.clone() );
  2106. }
  2107. } // instance controllers
  2108. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2109. const instance = instanceControllers[ i ];
  2110. const controller = getController( instance.id );
  2111. const geometries = getGeometry( controller.id );
  2112. const newObjects = buildObjects( geometries, instance.materials );
  2113. const skeletons = instance.skeletons;
  2114. const joints = controller.skin.joints;
  2115. const skeleton = buildSkeleton( skeletons, joints );
  2116. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2117. const object = newObjects[ j ];
  2118. if ( object.isSkinnedMesh ) {
  2119. object.bind( skeleton, controller.skin.bindMatrix );
  2120. object.normalizeSkinWeights();
  2121. }
  2122. objects.push( object );
  2123. }
  2124. } // instance lights
  2125. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2126. const instanceLight = getLight( instanceLights[ i ] );
  2127. if ( instanceLight !== null ) {
  2128. objects.push( instanceLight.clone() );
  2129. }
  2130. } // instance geometries
  2131. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2132. const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds.
  2133. // this is the case when primitives are combined like triangles and lines
  2134. const geometries = getGeometry( instance.id );
  2135. const newObjects = buildObjects( geometries, instance.materials );
  2136. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2137. objects.push( newObjects[ j ] );
  2138. }
  2139. } // instance nodes
  2140. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2141. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2142. }
  2143. let object;
  2144. if ( nodes.length === 0 && objects.length === 1 ) {
  2145. object = objects[ 0 ];
  2146. } else {
  2147. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2148. for ( let i = 0; i < objects.length; i ++ ) {
  2149. object.add( objects[ i ] );
  2150. }
  2151. }
  2152. object.name = type === 'JOINT' ? data.sid : data.name;
  2153. object.matrix.copy( matrix );
  2154. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2155. return object;
  2156. }
  2157. const fallbackMaterial = new THREE.MeshBasicMaterial( {
  2158. color: 0xff00ff
  2159. } );
  2160. function resolveMaterialBinding( keys, instanceMaterials ) {
  2161. const materials = [];
  2162. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2163. const id = instanceMaterials[ keys[ i ] ];
  2164. if ( id === undefined ) {
  2165. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2166. materials.push( fallbackMaterial );
  2167. } else {
  2168. materials.push( getMaterial( id ) );
  2169. }
  2170. }
  2171. return materials;
  2172. }
  2173. function buildObjects( geometries, instanceMaterials ) {
  2174. const objects = [];
  2175. for ( const type in geometries ) {
  2176. const geometry = geometries[ type ];
  2177. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined
  2178. if ( materials.length === 0 ) {
  2179. if ( type === 'lines' || type === 'linestrips' ) {
  2180. materials.push( new THREE.LineBasicMaterial() );
  2181. } else {
  2182. materials.push( new THREE.MeshPhongMaterial() );
  2183. }
  2184. } // regard skinning
  2185. const skinning = geometry.data.attributes.skinIndex !== undefined; // choose between a single or multi materials (material array)
  2186. const material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object
  2187. let object;
  2188. switch ( type ) {
  2189. case 'lines':
  2190. object = new THREE.LineSegments( geometry.data, material );
  2191. break;
  2192. case 'linestrips':
  2193. object = new THREE.Line( geometry.data, material );
  2194. break;
  2195. case 'triangles':
  2196. case 'polylist':
  2197. if ( skinning ) {
  2198. object = new THREE.SkinnedMesh( geometry.data, material );
  2199. } else {
  2200. object = new THREE.Mesh( geometry.data, material );
  2201. }
  2202. break;
  2203. }
  2204. objects.push( object );
  2205. }
  2206. return objects;
  2207. }
  2208. function hasNode( id ) {
  2209. return library.nodes[ id ] !== undefined;
  2210. }
  2211. function getNode( id ) {
  2212. return getBuild( library.nodes[ id ], buildNode );
  2213. } // visual scenes
  2214. function parseVisualScene( xml ) {
  2215. const data = {
  2216. name: xml.getAttribute( 'name' ),
  2217. children: []
  2218. };
  2219. prepareNodes( xml );
  2220. const elements = getElementsByTagName( xml, 'node' );
  2221. for ( let i = 0; i < elements.length; i ++ ) {
  2222. data.children.push( parseNode( elements[ i ] ) );
  2223. }
  2224. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2225. }
  2226. function buildVisualScene( data ) {
  2227. const group = new THREE.Group();
  2228. group.name = data.name;
  2229. const children = data.children;
  2230. for ( let i = 0; i < children.length; i ++ ) {
  2231. const child = children[ i ];
  2232. group.add( getNode( child.id ) );
  2233. }
  2234. return group;
  2235. }
  2236. function hasVisualScene( id ) {
  2237. return library.visualScenes[ id ] !== undefined;
  2238. }
  2239. function getVisualScene( id ) {
  2240. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2241. } // scenes
  2242. function parseScene( xml ) {
  2243. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2244. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2245. }
  2246. function setupAnimations() {
  2247. const clips = library.clips;
  2248. if ( isEmpty( clips ) === true ) {
  2249. if ( isEmpty( library.animations ) === false ) {
  2250. // if there are animations but no clips, we create a default clip for playback
  2251. const tracks = [];
  2252. for ( const id in library.animations ) {
  2253. const animationTracks = getAnimation( id );
  2254. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2255. tracks.push( animationTracks[ i ] );
  2256. }
  2257. }
  2258. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  2259. }
  2260. } else {
  2261. for ( const id in clips ) {
  2262. animations.push( getAnimationClip( id ) );
  2263. }
  2264. }
  2265. } // convert the parser error element into text with each child elements text
  2266. // separated by new lines.
  2267. function parserErrorToText( parserError ) {
  2268. let result = '';
  2269. const stack = [ parserError ];
  2270. while ( stack.length ) {
  2271. const node = stack.shift();
  2272. if ( node.nodeType === Node.TEXT_NODE ) {
  2273. result += node.textContent;
  2274. } else {
  2275. result += '\n';
  2276. stack.push.apply( stack, node.childNodes );
  2277. }
  2278. }
  2279. return result.trim();
  2280. }
  2281. if ( text.length === 0 ) {
  2282. return {
  2283. scene: new THREE.Scene()
  2284. };
  2285. }
  2286. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2287. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2288. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2289. if ( parserError !== undefined ) {
  2290. // Chrome will return parser error with a div in it
  2291. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2292. let errorText;
  2293. if ( errorElement ) {
  2294. errorText = errorElement.textContent;
  2295. } else {
  2296. errorText = parserErrorToText( parserError );
  2297. }
  2298. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2299. return null;
  2300. } // metadata
  2301. const version = collada.getAttribute( 'version' );
  2302. console.log( 'THREE.ColladaLoader: File version', version );
  2303. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2304. const textureLoader = new THREE.TextureLoader( this.manager );
  2305. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2306. let tgaLoader;
  2307. if ( THREE.TGALoader ) {
  2308. tgaLoader = new THREE.TGALoader( this.manager );
  2309. tgaLoader.setPath( this.resourcePath || path );
  2310. } //
  2311. const animations = [];
  2312. let kinematics = {};
  2313. let count = 0; //
  2314. const library = {
  2315. animations: {},
  2316. clips: {},
  2317. controllers: {},
  2318. images: {},
  2319. effects: {},
  2320. materials: {},
  2321. cameras: {},
  2322. lights: {},
  2323. geometries: {},
  2324. nodes: {},
  2325. visualScenes: {},
  2326. kinematicsModels: {},
  2327. physicsModels: {},
  2328. kinematicsScenes: {}
  2329. };
  2330. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2331. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2332. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2333. parseLibrary( collada, 'library_images', 'image', parseImage );
  2334. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2335. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2336. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2337. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2338. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2339. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2340. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2341. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2342. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2343. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2344. buildLibrary( library.animations, buildAnimation );
  2345. buildLibrary( library.clips, buildAnimationClip );
  2346. buildLibrary( library.controllers, buildController );
  2347. buildLibrary( library.images, buildImage );
  2348. buildLibrary( library.effects, buildEffect );
  2349. buildLibrary( library.materials, buildMaterial );
  2350. buildLibrary( library.cameras, buildCamera );
  2351. buildLibrary( library.lights, buildLight );
  2352. buildLibrary( library.geometries, buildGeometry );
  2353. buildLibrary( library.visualScenes, buildVisualScene );
  2354. setupAnimations();
  2355. setupKinematics();
  2356. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2357. scene.animations = animations;
  2358. if ( asset.upAxis === 'Z_UP' ) {
  2359. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  2360. }
  2361. scene.scale.multiplyScalar( asset.unit );
  2362. return {
  2363. get animations() {
  2364. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2365. return animations;
  2366. },
  2367. kinematics: kinematics,
  2368. library: library,
  2369. scene: scene
  2370. };
  2371. }
  2372. }
  2373. THREE.ColladaLoader = ColladaLoader;
  2374. } )();