ColladaLoader.js 84 KB

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