ColladaLoader.js 82 KB

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