ColladaLoader.js 84 KB

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