ColladaLoader.js 81 KB

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