ColladaLoader.js 81 KB

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