ColladaLoader.js 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796
  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. case 'extra':
  683. data.extra = parseEffectExtra( child );
  684. break;
  685. }
  686. }
  687. return data;
  688. }
  689. function parseEffectParameters( xml ) {
  690. const data = {};
  691. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  692. const child = xml.childNodes[ i ];
  693. if ( child.nodeType !== 1 ) continue;
  694. switch ( child.nodeName ) {
  695. case 'emission':
  696. case 'diffuse':
  697. case 'specular':
  698. case 'bump':
  699. case 'ambient':
  700. case 'shininess':
  701. case 'transparency':
  702. data[ child.nodeName ] = parseEffectParameter( child );
  703. break;
  704. case 'transparent':
  705. data[ child.nodeName ] = {
  706. opaque: child.getAttribute( 'opaque' ),
  707. data: parseEffectParameter( child )
  708. };
  709. break;
  710. }
  711. }
  712. return data;
  713. }
  714. function parseEffectParameter( xml ) {
  715. const data = {};
  716. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  717. const child = xml.childNodes[ i ];
  718. if ( child.nodeType !== 1 ) continue;
  719. switch ( child.nodeName ) {
  720. case 'color':
  721. data[ child.nodeName ] = parseFloats( child.textContent );
  722. break;
  723. case 'float':
  724. data[ child.nodeName ] = parseFloat( child.textContent );
  725. break;
  726. case 'texture':
  727. data[ child.nodeName ] = {
  728. id: child.getAttribute( 'texture' ),
  729. extra: parseEffectParameterTexture( child )
  730. };
  731. break;
  732. }
  733. }
  734. return data;
  735. }
  736. function parseEffectParameterTexture( xml ) {
  737. const data = {
  738. technique: {}
  739. };
  740. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  741. const child = xml.childNodes[ i ];
  742. if ( child.nodeType !== 1 ) continue;
  743. switch ( child.nodeName ) {
  744. case 'extra':
  745. parseEffectParameterTextureExtra( child, data );
  746. break;
  747. }
  748. }
  749. return data;
  750. }
  751. function parseEffectParameterTextureExtra( xml, data ) {
  752. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  753. const child = xml.childNodes[ i ];
  754. if ( child.nodeType !== 1 ) continue;
  755. switch ( child.nodeName ) {
  756. case 'technique':
  757. parseEffectParameterTextureExtraTechnique( child, data );
  758. break;
  759. }
  760. }
  761. }
  762. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  763. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  764. const child = xml.childNodes[ i ];
  765. if ( child.nodeType !== 1 ) continue;
  766. switch ( child.nodeName ) {
  767. case 'repeatU':
  768. case 'repeatV':
  769. case 'offsetU':
  770. case 'offsetV':
  771. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  772. break;
  773. case 'wrapU':
  774. case 'wrapV':
  775. // some files have values for wrapU/wrapV which become NaN via parseInt
  776. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  777. data.technique[ child.nodeName ] = 1;
  778. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  779. data.technique[ child.nodeName ] = 0;
  780. } else {
  781. data.technique[ child.nodeName ] = parseInt( child.textContent );
  782. }
  783. break;
  784. case 'bump':
  785. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  786. break;
  787. }
  788. }
  789. }
  790. function parseEffectExtra( xml ) {
  791. const data = {};
  792. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  793. const child = xml.childNodes[ i ];
  794. if ( child.nodeType !== 1 ) continue;
  795. switch ( child.nodeName ) {
  796. case 'technique':
  797. data.technique = parseEffectExtraTechnique( child );
  798. break;
  799. }
  800. }
  801. return data;
  802. }
  803. function parseEffectExtraTechnique( xml ) {
  804. const data = {};
  805. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  806. const child = xml.childNodes[ i ];
  807. if ( child.nodeType !== 1 ) continue;
  808. switch ( child.nodeName ) {
  809. case 'double_sided':
  810. data[ child.nodeName ] = parseInt( child.textContent );
  811. break;
  812. case 'bump':
  813. data[ child.nodeName ] = parseEffectExtraTechniqueBump( child );
  814. break;
  815. }
  816. }
  817. return data;
  818. }
  819. function parseEffectExtraTechniqueBump( xml ) {
  820. var data = {};
  821. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  822. var child = xml.childNodes[ i ];
  823. if ( child.nodeType !== 1 ) continue;
  824. switch ( child.nodeName ) {
  825. case 'texture':
  826. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), texcoord: child.getAttribute( 'texcoord' ), extra: parseEffectParameterTexture( child ) };
  827. break;
  828. }
  829. }
  830. return data;
  831. }
  832. function buildEffect( data ) {
  833. return data;
  834. }
  835. function getEffect( id ) {
  836. return getBuild( library.effects[ id ], buildEffect );
  837. } // material
  838. function parseMaterial( xml ) {
  839. const data = {
  840. name: xml.getAttribute( 'name' )
  841. };
  842. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  843. const child = xml.childNodes[ i ];
  844. if ( child.nodeType !== 1 ) continue;
  845. switch ( child.nodeName ) {
  846. case 'instance_effect':
  847. data.url = parseId( child.getAttribute( 'url' ) );
  848. break;
  849. }
  850. }
  851. library.materials[ xml.getAttribute( 'id' ) ] = data;
  852. }
  853. function getTextureLoader( image ) {
  854. let loader;
  855. let extension = image.slice( ( image.lastIndexOf( '.' ) - 1 >>> 0 ) + 2 ); // http://www.jstips.co/en/javascript/get-file-extension/
  856. extension = extension.toLowerCase();
  857. switch ( extension ) {
  858. case 'tga':
  859. loader = tgaLoader;
  860. break;
  861. default:
  862. loader = textureLoader;
  863. }
  864. return loader;
  865. }
  866. function buildMaterial( data ) {
  867. const effect = getEffect( data.url );
  868. const technique = effect.profile.technique;
  869. const extra = effect.profile.extra;
  870. let material;
  871. switch ( technique.type ) {
  872. case 'phong':
  873. case 'blinn':
  874. material = new THREE.MeshPhongMaterial();
  875. break;
  876. case 'lambert':
  877. material = new THREE.MeshLambertMaterial();
  878. break;
  879. default:
  880. material = new THREE.MeshBasicMaterial();
  881. break;
  882. }
  883. material.name = data.name || '';
  884. function getTexture( textureObject ) {
  885. const sampler = effect.profile.samplers[ textureObject.id ];
  886. let image = null; // get image
  887. if ( sampler !== undefined ) {
  888. const surface = effect.profile.surfaces[ sampler.source ];
  889. image = getImage( surface.init_from );
  890. } else {
  891. console.warn( 'THREE.ColladaLoader: Undefined sampler. Access image directly (see #12530).' );
  892. image = getImage( textureObject.id );
  893. } // create texture if image is avaiable
  894. if ( image !== null ) {
  895. const loader = getTextureLoader( image );
  896. if ( loader !== undefined ) {
  897. const texture = loader.load( image );
  898. const extra = textureObject.extra;
  899. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  900. const technique = extra.technique;
  901. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  902. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  903. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  904. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  905. } else {
  906. texture.wrapS = THREE.RepeatWrapping;
  907. texture.wrapT = THREE.RepeatWrapping;
  908. }
  909. return texture;
  910. } else {
  911. console.warn( 'THREE.ColladaLoader: THREE.Loader for texture %s not found.', image );
  912. return null;
  913. }
  914. } else {
  915. console.warn( 'THREE.ColladaLoader: Couldn\'t create texture with ID:', textureObject.id );
  916. return null;
  917. }
  918. }
  919. const parameters = technique.parameters;
  920. for ( const key in parameters ) {
  921. const parameter = parameters[ key ];
  922. switch ( key ) {
  923. case 'diffuse':
  924. if ( parameter.color ) material.color.fromArray( parameter.color );
  925. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  926. break;
  927. case 'specular':
  928. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  929. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  930. break;
  931. case 'bump':
  932. if ( parameter.texture ) material.normalMap = getTexture( parameter.texture );
  933. break;
  934. case 'ambient':
  935. if ( parameter.texture ) material.lightMap = getTexture( parameter.texture );
  936. break;
  937. case 'shininess':
  938. if ( parameter.float && material.shininess ) material.shininess = parameter.float;
  939. break;
  940. case 'emission':
  941. if ( parameter.color && material.emissive ) material.emissive.fromArray( parameter.color );
  942. if ( parameter.texture ) material.emissiveMap = getTexture( parameter.texture );
  943. break;
  944. }
  945. } //
  946. let transparent = parameters[ 'transparent' ];
  947. let transparency = parameters[ 'transparency' ]; // <transparency> does not exist but <transparent>
  948. if ( transparency === undefined && transparent ) {
  949. transparency = {
  950. float: 1
  951. };
  952. } // <transparent> does not exist but <transparency>
  953. if ( transparent === undefined && transparency ) {
  954. transparent = {
  955. opaque: 'A_ONE',
  956. data: {
  957. color: [ 1, 1, 1, 1 ]
  958. }
  959. };
  960. }
  961. if ( transparent && transparency ) {
  962. // handle case if a texture exists but no color
  963. if ( transparent.data.texture ) {
  964. // we do not set an alpha map (see #13792)
  965. material.transparent = true;
  966. } else {
  967. const color = transparent.data.color;
  968. switch ( transparent.opaque ) {
  969. case 'A_ONE':
  970. material.opacity = color[ 3 ] * transparency.float;
  971. break;
  972. case 'RGB_ZERO':
  973. material.opacity = 1 - color[ 0 ] * transparency.float;
  974. break;
  975. case 'A_ZERO':
  976. material.opacity = 1 - color[ 3 ] * transparency.float;
  977. break;
  978. case 'RGB_ONE':
  979. material.opacity = color[ 0 ] * transparency.float;
  980. break;
  981. default:
  982. console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque );
  983. }
  984. if ( material.opacity < 1 ) material.transparent = true;
  985. }
  986. } //
  987. if ( technique.extra !== undefined && technique.extra.technique !== undefined ) {
  988. let techniques = technique.extra.technique;
  989. for ( let k in techniques ) {
  990. let v = techniques[k];
  991. switch (k) {
  992. case 'double_sided':
  993. material.side = ( v === 1 ? THREE.DoubleSide : THREE.FrontSide );
  994. break;
  995. case 'bump':
  996. material.normalMap = getTexture( v.texture );
  997. material.normalScale = new THREE.Vector2( 1, 1 );
  998. break;
  999. }
  1000. }
  1001. }
  1002. return material;
  1003. }
  1004. function getMaterial( id ) {
  1005. return getBuild( library.materials[ id ], buildMaterial );
  1006. } // camera
  1007. function parseCamera( xml ) {
  1008. const data = {
  1009. name: xml.getAttribute( 'name' )
  1010. };
  1011. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1012. const child = xml.childNodes[ i ];
  1013. if ( child.nodeType !== 1 ) continue;
  1014. switch ( child.nodeName ) {
  1015. case 'optics':
  1016. data.optics = parseCameraOptics( child );
  1017. break;
  1018. }
  1019. }
  1020. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  1021. }
  1022. function parseCameraOptics( xml ) {
  1023. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1024. const child = xml.childNodes[ i ];
  1025. switch ( child.nodeName ) {
  1026. case 'technique_common':
  1027. return parseCameraTechnique( child );
  1028. }
  1029. }
  1030. return {};
  1031. }
  1032. function parseCameraTechnique( xml ) {
  1033. const data = {};
  1034. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1035. const child = xml.childNodes[ i ];
  1036. switch ( child.nodeName ) {
  1037. case 'perspective':
  1038. case 'orthographic':
  1039. data.technique = child.nodeName;
  1040. data.parameters = parseCameraParameters( child );
  1041. break;
  1042. }
  1043. }
  1044. return data;
  1045. }
  1046. function parseCameraParameters( xml ) {
  1047. const data = {};
  1048. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1049. const child = xml.childNodes[ i ];
  1050. switch ( child.nodeName ) {
  1051. case 'xfov':
  1052. case 'yfov':
  1053. case 'xmag':
  1054. case 'ymag':
  1055. case 'znear':
  1056. case 'zfar':
  1057. case 'aspect_ratio':
  1058. data[ child.nodeName ] = parseFloat( child.textContent );
  1059. break;
  1060. }
  1061. }
  1062. return data;
  1063. }
  1064. function buildCamera( data ) {
  1065. let camera;
  1066. switch ( data.optics.technique ) {
  1067. case 'perspective':
  1068. camera = new THREE.PerspectiveCamera( data.optics.parameters.yfov, data.optics.parameters.aspect_ratio, data.optics.parameters.znear, data.optics.parameters.zfar );
  1069. break;
  1070. case 'orthographic':
  1071. let ymag = data.optics.parameters.ymag;
  1072. let xmag = data.optics.parameters.xmag;
  1073. const aspectRatio = data.optics.parameters.aspect_ratio;
  1074. xmag = xmag === undefined ? ymag * aspectRatio : xmag;
  1075. ymag = ymag === undefined ? xmag / aspectRatio : ymag;
  1076. xmag *= 0.5;
  1077. ymag *= 0.5;
  1078. camera = new THREE.OrthographicCamera( - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  1079. data.optics.parameters.znear, data.optics.parameters.zfar );
  1080. break;
  1081. default:
  1082. camera = new THREE.PerspectiveCamera();
  1083. break;
  1084. }
  1085. camera.name = data.name || '';
  1086. return camera;
  1087. }
  1088. function getCamera( id ) {
  1089. const data = library.cameras[ id ];
  1090. if ( data !== undefined ) {
  1091. return getBuild( data, buildCamera );
  1092. }
  1093. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  1094. return null;
  1095. } // light
  1096. function parseLight( xml ) {
  1097. let data = {};
  1098. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1099. const child = xml.childNodes[ i ];
  1100. if ( child.nodeType !== 1 ) continue;
  1101. switch ( child.nodeName ) {
  1102. case 'technique_common':
  1103. data = parseLightTechnique( child );
  1104. break;
  1105. }
  1106. }
  1107. library.lights[ xml.getAttribute( 'id' ) ] = data;
  1108. }
  1109. function parseLightTechnique( xml ) {
  1110. const data = {};
  1111. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1112. const child = xml.childNodes[ i ];
  1113. if ( child.nodeType !== 1 ) continue;
  1114. switch ( child.nodeName ) {
  1115. case 'directional':
  1116. case 'point':
  1117. case 'spot':
  1118. case 'ambient':
  1119. data.technique = child.nodeName;
  1120. data.parameters = parseLightParameters( child );
  1121. }
  1122. }
  1123. return data;
  1124. }
  1125. function parseLightParameters( xml ) {
  1126. const data = {};
  1127. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1128. const child = xml.childNodes[ i ];
  1129. if ( child.nodeType !== 1 ) continue;
  1130. switch ( child.nodeName ) {
  1131. case 'color':
  1132. const array = parseFloats( child.textContent );
  1133. data.color = new THREE.Color().fromArray( array );
  1134. break;
  1135. case 'falloff_angle':
  1136. data.falloffAngle = parseFloat( child.textContent );
  1137. break;
  1138. case 'quadratic_attenuation':
  1139. const f = parseFloat( child.textContent );
  1140. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  1141. break;
  1142. }
  1143. }
  1144. return data;
  1145. }
  1146. function buildLight( data ) {
  1147. let light;
  1148. switch ( data.technique ) {
  1149. case 'directional':
  1150. light = new THREE.DirectionalLight();
  1151. break;
  1152. case 'point':
  1153. light = new THREE.PointLight();
  1154. break;
  1155. case 'spot':
  1156. light = new THREE.SpotLight();
  1157. break;
  1158. case 'ambient':
  1159. light = new THREE.AmbientLight();
  1160. break;
  1161. }
  1162. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  1163. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  1164. return light;
  1165. }
  1166. function getLight( id ) {
  1167. const data = library.lights[ id ];
  1168. if ( data !== undefined ) {
  1169. return getBuild( data, buildLight );
  1170. }
  1171. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  1172. return null;
  1173. } // geometry
  1174. function parseGeometry( xml ) {
  1175. const data = {
  1176. name: xml.getAttribute( 'name' ),
  1177. sources: {},
  1178. vertices: {},
  1179. primitives: []
  1180. };
  1181. 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
  1182. if ( mesh === undefined ) return;
  1183. for ( let i = 0; i < mesh.childNodes.length; i ++ ) {
  1184. const child = mesh.childNodes[ i ];
  1185. if ( child.nodeType !== 1 ) continue;
  1186. const id = child.getAttribute( 'id' );
  1187. switch ( child.nodeName ) {
  1188. case 'source':
  1189. data.sources[ id ] = parseSource( child );
  1190. break;
  1191. case 'vertices':
  1192. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  1193. data.vertices = parseGeometryVertices( child );
  1194. break;
  1195. case 'polygons':
  1196. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  1197. break;
  1198. case 'lines':
  1199. case 'linestrips':
  1200. case 'polylist':
  1201. case 'triangles':
  1202. data.primitives.push( parseGeometryPrimitive( child ) );
  1203. break;
  1204. default:
  1205. console.log( child );
  1206. }
  1207. }
  1208. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  1209. }
  1210. function parseSource( xml ) {
  1211. const data = {
  1212. array: [],
  1213. stride: 3
  1214. };
  1215. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1216. const child = xml.childNodes[ i ];
  1217. if ( child.nodeType !== 1 ) continue;
  1218. switch ( child.nodeName ) {
  1219. case 'float_array':
  1220. data.array = parseFloats( child.textContent );
  1221. break;
  1222. case 'Name_array':
  1223. data.array = parseStrings( child.textContent );
  1224. break;
  1225. case 'technique_common':
  1226. const accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  1227. if ( accessor !== undefined ) {
  1228. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  1229. }
  1230. break;
  1231. }
  1232. }
  1233. return data;
  1234. }
  1235. function parseGeometryVertices( xml ) {
  1236. const data = {};
  1237. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1238. const child = xml.childNodes[ i ];
  1239. if ( child.nodeType !== 1 ) continue;
  1240. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  1241. }
  1242. return data;
  1243. }
  1244. function parseGeometryPrimitive( xml ) {
  1245. const primitive = {
  1246. type: xml.nodeName,
  1247. material: xml.getAttribute( 'material' ),
  1248. count: parseInt( xml.getAttribute( 'count' ) ),
  1249. inputs: {},
  1250. stride: 0,
  1251. hasUV: false
  1252. };
  1253. for ( let i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  1254. const child = xml.childNodes[ i ];
  1255. if ( child.nodeType !== 1 ) continue;
  1256. switch ( child.nodeName ) {
  1257. case 'input':
  1258. const id = parseId( child.getAttribute( 'source' ) );
  1259. const semantic = child.getAttribute( 'semantic' );
  1260. const offset = parseInt( child.getAttribute( 'offset' ) );
  1261. const set = parseInt( child.getAttribute( 'set' ) );
  1262. const inputname = set > 0 ? semantic + set : semantic;
  1263. primitive.inputs[ inputname ] = {
  1264. id: id,
  1265. offset: offset
  1266. };
  1267. primitive.stride = Math.max( primitive.stride, offset + 1 );
  1268. if ( semantic === 'TEXCOORD' ) primitive.hasUV = true;
  1269. break;
  1270. case 'vcount':
  1271. primitive.vcount = parseInts( child.textContent );
  1272. break;
  1273. case 'p':
  1274. primitive.p = parseInts( child.textContent );
  1275. break;
  1276. }
  1277. }
  1278. return primitive;
  1279. }
  1280. function groupPrimitives( primitives ) {
  1281. const build = {};
  1282. for ( let i = 0; i < primitives.length; i ++ ) {
  1283. const primitive = primitives[ i ];
  1284. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  1285. build[ primitive.type ].push( primitive );
  1286. }
  1287. return build;
  1288. }
  1289. function checkUVCoordinates( primitives ) {
  1290. let count = 0;
  1291. for ( let i = 0, l = primitives.length; i < l; i ++ ) {
  1292. const primitive = primitives[ i ];
  1293. if ( primitive.hasUV === true ) {
  1294. count ++;
  1295. }
  1296. }
  1297. if ( count > 0 && count < primitives.length ) {
  1298. primitives.uvsNeedsFix = true;
  1299. }
  1300. }
  1301. function buildGeometry( data ) {
  1302. const build = {};
  1303. const sources = data.sources;
  1304. const vertices = data.vertices;
  1305. const primitives = data.primitives;
  1306. if ( primitives.length === 0 ) return {}; // our goal is to create one buffer geometry for a single type of primitives
  1307. // first, we group all primitives by their type
  1308. const groupedPrimitives = groupPrimitives( primitives );
  1309. for ( const type in groupedPrimitives ) {
  1310. const primitiveType = groupedPrimitives[ type ]; // second, ensure consistent uv coordinates for each type of primitives (polylist,triangles or lines)
  1311. checkUVCoordinates( primitiveType ); // third, create a buffer geometry for each type of primitives
  1312. build[ type ] = buildGeometryType( primitiveType, sources, vertices );
  1313. }
  1314. return build;
  1315. }
  1316. function buildGeometryType( primitives, sources, vertices ) {
  1317. const build = {};
  1318. const position = {
  1319. array: [],
  1320. stride: 0
  1321. };
  1322. const normal = {
  1323. array: [],
  1324. stride: 0
  1325. };
  1326. const uv = {
  1327. array: [],
  1328. stride: 0
  1329. };
  1330. const uv2 = {
  1331. array: [],
  1332. stride: 0
  1333. };
  1334. const color = {
  1335. array: [],
  1336. stride: 0
  1337. };
  1338. const skinIndex = {
  1339. array: [],
  1340. stride: 4
  1341. };
  1342. const skinWeight = {
  1343. array: [],
  1344. stride: 4
  1345. };
  1346. const geometry = new THREE.BufferGeometry();
  1347. const materialKeys = [];
  1348. let start = 0;
  1349. for ( let p = 0; p < primitives.length; p ++ ) {
  1350. const primitive = primitives[ p ];
  1351. const inputs = primitive.inputs; // groups
  1352. let count = 0;
  1353. switch ( primitive.type ) {
  1354. case 'lines':
  1355. case 'linestrips':
  1356. count = primitive.count * 2;
  1357. break;
  1358. case 'triangles':
  1359. count = primitive.count * 3;
  1360. break;
  1361. case 'polylist':
  1362. for ( let g = 0; g < primitive.count; g ++ ) {
  1363. const vc = primitive.vcount[ g ];
  1364. switch ( vc ) {
  1365. case 3:
  1366. count += 3; // single triangle
  1367. break;
  1368. case 4:
  1369. count += 6; // quad, subdivided into two triangles
  1370. break;
  1371. default:
  1372. count += ( vc - 2 ) * 3; // polylist with more than four vertices
  1373. break;
  1374. }
  1375. }
  1376. break;
  1377. default:
  1378. console.warn( 'THREE.ColladaLoader: Unknow primitive type:', primitive.type );
  1379. }
  1380. geometry.addGroup( start, count, p );
  1381. start += count; // material
  1382. if ( primitive.material ) {
  1383. materialKeys.push( primitive.material );
  1384. } // geometry data
  1385. for ( const name in inputs ) {
  1386. const input = inputs[ name ];
  1387. switch ( name ) {
  1388. case 'VERTEX':
  1389. for ( const key in vertices ) {
  1390. const id = vertices[ key ];
  1391. switch ( key ) {
  1392. case 'POSITION':
  1393. const prevLength = position.array.length;
  1394. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  1395. position.stride = sources[ id ].stride;
  1396. if ( sources.skinWeights && sources.skinIndices ) {
  1397. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  1398. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  1399. } // see #3803
  1400. if ( primitive.hasUV === false && primitives.uvsNeedsFix === true ) {
  1401. const count = ( position.array.length - prevLength ) / position.stride;
  1402. for ( let i = 0; i < count; i ++ ) {
  1403. // fill missing uv coordinates
  1404. uv.array.push( 0, 0 );
  1405. }
  1406. }
  1407. break;
  1408. case 'NORMAL':
  1409. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  1410. normal.stride = sources[ id ].stride;
  1411. break;
  1412. case 'COLOR':
  1413. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  1414. color.stride = sources[ id ].stride;
  1415. break;
  1416. case 'TEXCOORD':
  1417. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  1418. uv.stride = sources[ id ].stride;
  1419. break;
  1420. case 'TEXCOORD1':
  1421. buildGeometryData( primitive, sources[ id ], input.offset, uv2.array );
  1422. uv.stride = sources[ id ].stride;
  1423. break;
  1424. default:
  1425. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  1426. }
  1427. }
  1428. break;
  1429. case 'NORMAL':
  1430. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  1431. normal.stride = sources[ input.id ].stride;
  1432. break;
  1433. case 'COLOR':
  1434. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  1435. color.stride = sources[ input.id ].stride;
  1436. break;
  1437. case 'TEXCOORD':
  1438. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  1439. uv.stride = sources[ input.id ].stride;
  1440. break;
  1441. case 'TEXCOORD1':
  1442. buildGeometryData( primitive, sources[ input.id ], input.offset, uv2.array );
  1443. uv2.stride = sources[ input.id ].stride;
  1444. break;
  1445. }
  1446. }
  1447. } // build geometry
  1448. if ( position.array.length > 0 ) geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  1449. if ( normal.array.length > 0 ) geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  1450. if ( color.array.length > 0 ) geometry.setAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  1451. if ( uv.array.length > 0 ) geometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  1452. if ( uv2.array.length > 0 ) geometry.setAttribute( 'uv2', new THREE.Float32BufferAttribute( uv2.array, uv2.stride ) );
  1453. if ( skinIndex.array.length > 0 ) geometry.setAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  1454. if ( skinWeight.array.length > 0 ) geometry.setAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  1455. build.data = geometry;
  1456. build.type = primitives[ 0 ].type;
  1457. build.materialKeys = materialKeys;
  1458. return build;
  1459. }
  1460. function buildGeometryData( primitive, source, offset, array ) {
  1461. const indices = primitive.p;
  1462. const stride = primitive.stride;
  1463. const vcount = primitive.vcount;
  1464. function pushVector( i ) {
  1465. let index = indices[ i + offset ] * sourceStride;
  1466. const length = index + sourceStride;
  1467. for ( ; index < length; index ++ ) {
  1468. array.push( sourceArray[ index ] );
  1469. }
  1470. }
  1471. const sourceArray = source.array;
  1472. const sourceStride = source.stride;
  1473. if ( primitive.vcount !== undefined ) {
  1474. let index = 0;
  1475. for ( let i = 0, l = vcount.length; i < l; i ++ ) {
  1476. const count = vcount[ i ];
  1477. if ( count === 4 ) {
  1478. const a = index + stride * 0;
  1479. const b = index + stride * 1;
  1480. const c = index + stride * 2;
  1481. const d = index + stride * 3;
  1482. pushVector( a );
  1483. pushVector( b );
  1484. pushVector( d );
  1485. pushVector( b );
  1486. pushVector( c );
  1487. pushVector( d );
  1488. } else if ( count === 3 ) {
  1489. const a = index + stride * 0;
  1490. const b = index + stride * 1;
  1491. const c = index + stride * 2;
  1492. pushVector( a );
  1493. pushVector( b );
  1494. pushVector( c );
  1495. } else if ( count > 4 ) {
  1496. for ( let k = 1, kl = count - 2; k <= kl; k ++ ) {
  1497. const a = index + stride * 0;
  1498. const b = index + stride * k;
  1499. const c = index + stride * ( k + 1 );
  1500. pushVector( a );
  1501. pushVector( b );
  1502. pushVector( c );
  1503. }
  1504. }
  1505. index += stride * count;
  1506. }
  1507. } else {
  1508. for ( let i = 0, l = indices.length; i < l; i += stride ) {
  1509. pushVector( i );
  1510. }
  1511. }
  1512. }
  1513. function getGeometry( id ) {
  1514. return getBuild( library.geometries[ id ], buildGeometry );
  1515. } // kinematics
  1516. function parseKinematicsModel( xml ) {
  1517. const data = {
  1518. name: xml.getAttribute( 'name' ) || '',
  1519. joints: {},
  1520. links: []
  1521. };
  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 'technique_common':
  1527. parseKinematicsTechniqueCommon( child, data );
  1528. break;
  1529. }
  1530. }
  1531. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  1532. }
  1533. function buildKinematicsModel( data ) {
  1534. if ( data.build !== undefined ) return data.build;
  1535. return data;
  1536. }
  1537. function getKinematicsModel( id ) {
  1538. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  1539. }
  1540. function parseKinematicsTechniqueCommon( xml, data ) {
  1541. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1542. const child = xml.childNodes[ i ];
  1543. if ( child.nodeType !== 1 ) continue;
  1544. switch ( child.nodeName ) {
  1545. case 'joint':
  1546. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  1547. break;
  1548. case 'link':
  1549. data.links.push( parseKinematicsLink( child ) );
  1550. break;
  1551. }
  1552. }
  1553. }
  1554. function parseKinematicsJoint( xml ) {
  1555. let data;
  1556. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1557. const child = xml.childNodes[ i ];
  1558. if ( child.nodeType !== 1 ) continue;
  1559. switch ( child.nodeName ) {
  1560. case 'prismatic':
  1561. case 'revolute':
  1562. data = parseKinematicsJointParameter( child );
  1563. break;
  1564. }
  1565. }
  1566. return data;
  1567. }
  1568. function parseKinematicsJointParameter( xml ) {
  1569. const data = {
  1570. sid: xml.getAttribute( 'sid' ),
  1571. name: xml.getAttribute( 'name' ) || '',
  1572. axis: new THREE.Vector3(),
  1573. limits: {
  1574. min: 0,
  1575. max: 0
  1576. },
  1577. type: xml.nodeName,
  1578. static: false,
  1579. zeroPosition: 0,
  1580. middlePosition: 0
  1581. };
  1582. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1583. const child = xml.childNodes[ i ];
  1584. if ( child.nodeType !== 1 ) continue;
  1585. switch ( child.nodeName ) {
  1586. case 'axis':
  1587. const array = parseFloats( child.textContent );
  1588. data.axis.fromArray( array );
  1589. break;
  1590. case 'limits':
  1591. const max = child.getElementsByTagName( 'max' )[ 0 ];
  1592. const min = child.getElementsByTagName( 'min' )[ 0 ];
  1593. data.limits.max = parseFloat( max.textContent );
  1594. data.limits.min = parseFloat( min.textContent );
  1595. break;
  1596. }
  1597. } // if min is equal to or greater than max, consider the joint static
  1598. if ( data.limits.min >= data.limits.max ) {
  1599. data.static = true;
  1600. } // calculate middle position
  1601. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  1602. return data;
  1603. }
  1604. function parseKinematicsLink( xml ) {
  1605. const data = {
  1606. sid: xml.getAttribute( 'sid' ),
  1607. name: xml.getAttribute( 'name' ) || '',
  1608. attachments: [],
  1609. transforms: []
  1610. };
  1611. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1612. const child = xml.childNodes[ i ];
  1613. if ( child.nodeType !== 1 ) continue;
  1614. switch ( child.nodeName ) {
  1615. case 'attachment_full':
  1616. data.attachments.push( parseKinematicsAttachment( child ) );
  1617. break;
  1618. case 'matrix':
  1619. case 'translate':
  1620. case 'rotate':
  1621. data.transforms.push( parseKinematicsTransform( child ) );
  1622. break;
  1623. }
  1624. }
  1625. return data;
  1626. }
  1627. function parseKinematicsAttachment( xml ) {
  1628. const data = {
  1629. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  1630. transforms: [],
  1631. links: []
  1632. };
  1633. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1634. const child = xml.childNodes[ i ];
  1635. if ( child.nodeType !== 1 ) continue;
  1636. switch ( child.nodeName ) {
  1637. case 'link':
  1638. data.links.push( parseKinematicsLink( child ) );
  1639. break;
  1640. case 'matrix':
  1641. case 'translate':
  1642. case 'rotate':
  1643. data.transforms.push( parseKinematicsTransform( child ) );
  1644. break;
  1645. }
  1646. }
  1647. return data;
  1648. }
  1649. function parseKinematicsTransform( xml ) {
  1650. const data = {
  1651. type: xml.nodeName
  1652. };
  1653. const array = parseFloats( xml.textContent );
  1654. switch ( data.type ) {
  1655. case 'matrix':
  1656. data.obj = new THREE.Matrix4();
  1657. data.obj.fromArray( array ).transpose();
  1658. break;
  1659. case 'translate':
  1660. data.obj = new THREE.Vector3();
  1661. data.obj.fromArray( array );
  1662. break;
  1663. case 'rotate':
  1664. data.obj = new THREE.Vector3();
  1665. data.obj.fromArray( array );
  1666. data.angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1667. break;
  1668. }
  1669. return data;
  1670. } // physics
  1671. function parsePhysicsModel( xml ) {
  1672. const data = {
  1673. name: xml.getAttribute( 'name' ) || '',
  1674. rigidBodies: {}
  1675. };
  1676. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1677. const child = xml.childNodes[ i ];
  1678. if ( child.nodeType !== 1 ) continue;
  1679. switch ( child.nodeName ) {
  1680. case 'rigid_body':
  1681. data.rigidBodies[ child.getAttribute( 'name' ) ] = {};
  1682. parsePhysicsRigidBody( child, data.rigidBodies[ child.getAttribute( 'name' ) ] );
  1683. break;
  1684. }
  1685. }
  1686. library.physicsModels[ xml.getAttribute( 'id' ) ] = data;
  1687. }
  1688. function parsePhysicsRigidBody( xml, data ) {
  1689. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1690. const child = xml.childNodes[ i ];
  1691. if ( child.nodeType !== 1 ) continue;
  1692. switch ( child.nodeName ) {
  1693. case 'technique_common':
  1694. parsePhysicsTechniqueCommon( child, data );
  1695. break;
  1696. }
  1697. }
  1698. }
  1699. function parsePhysicsTechniqueCommon( xml, data ) {
  1700. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1701. const child = xml.childNodes[ i ];
  1702. if ( child.nodeType !== 1 ) continue;
  1703. switch ( child.nodeName ) {
  1704. case 'inertia':
  1705. data.inertia = parseFloats( child.textContent );
  1706. break;
  1707. case 'mass':
  1708. data.mass = parseFloats( child.textContent )[ 0 ];
  1709. break;
  1710. }
  1711. }
  1712. } // scene
  1713. function parseKinematicsScene( xml ) {
  1714. const data = {
  1715. bindJointAxis: []
  1716. };
  1717. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1718. const child = xml.childNodes[ i ];
  1719. if ( child.nodeType !== 1 ) continue;
  1720. switch ( child.nodeName ) {
  1721. case 'bind_joint_axis':
  1722. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  1723. break;
  1724. }
  1725. }
  1726. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  1727. }
  1728. function parseKinematicsBindJointAxis( xml ) {
  1729. const data = {
  1730. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  1731. };
  1732. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1733. const child = xml.childNodes[ i ];
  1734. if ( child.nodeType !== 1 ) continue;
  1735. switch ( child.nodeName ) {
  1736. case 'axis':
  1737. const param = child.getElementsByTagName( 'param' )[ 0 ];
  1738. data.axis = param.textContent;
  1739. const tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  1740. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  1741. break;
  1742. }
  1743. }
  1744. return data;
  1745. }
  1746. function buildKinematicsScene( data ) {
  1747. if ( data.build !== undefined ) return data.build;
  1748. return data;
  1749. }
  1750. function getKinematicsScene( id ) {
  1751. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  1752. }
  1753. function setupKinematics() {
  1754. const kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  1755. const kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  1756. const visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  1757. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  1758. const kinematicsModel = getKinematicsModel( kinematicsModelId );
  1759. const kinematicsScene = getKinematicsScene( kinematicsSceneId );
  1760. const visualScene = getVisualScene( visualSceneId );
  1761. const bindJointAxis = kinematicsScene.bindJointAxis;
  1762. const jointMap = {};
  1763. for ( let i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  1764. const axis = bindJointAxis[ i ]; // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  1765. const targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  1766. if ( targetElement ) {
  1767. // get the parent of the transform element
  1768. const parentVisualElement = targetElement.parentElement; // connect the joint of the kinematics model with the element in the visual scene
  1769. connect( axis.jointIndex, parentVisualElement );
  1770. }
  1771. }
  1772. function connect( jointIndex, visualElement ) {
  1773. const visualElementName = visualElement.getAttribute( 'name' );
  1774. const joint = kinematicsModel.joints[ jointIndex ];
  1775. visualScene.traverse( function ( object ) {
  1776. if ( object.name === visualElementName ) {
  1777. jointMap[ jointIndex ] = {
  1778. object: object,
  1779. transforms: buildTransformList( visualElement ),
  1780. joint: joint,
  1781. position: joint.zeroPosition
  1782. };
  1783. }
  1784. } );
  1785. }
  1786. const m0 = new THREE.Matrix4();
  1787. kinematics = {
  1788. joints: kinematicsModel && kinematicsModel.joints,
  1789. getJointValue: function ( jointIndex ) {
  1790. const jointData = jointMap[ jointIndex ];
  1791. if ( jointData ) {
  1792. return jointData.position;
  1793. } else {
  1794. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  1795. }
  1796. },
  1797. setJointValue: function ( jointIndex, value ) {
  1798. const jointData = jointMap[ jointIndex ];
  1799. if ( jointData ) {
  1800. const joint = jointData.joint;
  1801. if ( value > joint.limits.max || value < joint.limits.min ) {
  1802. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  1803. } else if ( joint.static ) {
  1804. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  1805. } else {
  1806. const object = jointData.object;
  1807. const axis = joint.axis;
  1808. const transforms = jointData.transforms;
  1809. matrix.identity(); // each update, we have to apply all transforms in the correct order
  1810. for ( let i = 0; i < transforms.length; i ++ ) {
  1811. const transform = transforms[ i ]; // if there is a connection of the transform node with a joint, apply the joint value
  1812. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  1813. switch ( joint.type ) {
  1814. case 'revolute':
  1815. matrix.multiply( m0.makeRotationAxis( axis, THREE.MathUtils.degToRad( value ) ) );
  1816. break;
  1817. case 'prismatic':
  1818. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  1819. break;
  1820. default:
  1821. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  1822. break;
  1823. }
  1824. } else {
  1825. switch ( transform.type ) {
  1826. case 'matrix':
  1827. matrix.multiply( transform.obj );
  1828. break;
  1829. case 'translate':
  1830. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  1831. break;
  1832. case 'scale':
  1833. matrix.scale( transform.obj );
  1834. break;
  1835. case 'rotate':
  1836. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  1837. break;
  1838. }
  1839. }
  1840. }
  1841. object.matrix.copy( matrix );
  1842. object.matrix.decompose( object.position, object.quaternion, object.scale );
  1843. jointMap[ jointIndex ].position = value;
  1844. }
  1845. } else {
  1846. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  1847. }
  1848. }
  1849. };
  1850. }
  1851. function buildTransformList( node ) {
  1852. const transforms = [];
  1853. const xml = collada.querySelector( '[id="' + node.id + '"]' );
  1854. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1855. const child = xml.childNodes[ i ];
  1856. if ( child.nodeType !== 1 ) continue;
  1857. let array, vector;
  1858. switch ( child.nodeName ) {
  1859. case 'matrix':
  1860. array = parseFloats( child.textContent );
  1861. const matrix = new THREE.Matrix4().fromArray( array ).transpose();
  1862. transforms.push( {
  1863. sid: child.getAttribute( 'sid' ),
  1864. type: child.nodeName,
  1865. obj: matrix
  1866. } );
  1867. break;
  1868. case 'translate':
  1869. case 'scale':
  1870. array = parseFloats( child.textContent );
  1871. vector = new THREE.Vector3().fromArray( array );
  1872. transforms.push( {
  1873. sid: child.getAttribute( 'sid' ),
  1874. type: child.nodeName,
  1875. obj: vector
  1876. } );
  1877. break;
  1878. case 'rotate':
  1879. array = parseFloats( child.textContent );
  1880. vector = new THREE.Vector3().fromArray( array );
  1881. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1882. transforms.push( {
  1883. sid: child.getAttribute( 'sid' ),
  1884. type: child.nodeName,
  1885. obj: vector,
  1886. angle: angle
  1887. } );
  1888. break;
  1889. }
  1890. }
  1891. return transforms;
  1892. } // nodes
  1893. function prepareNodes( xml ) {
  1894. const elements = xml.getElementsByTagName( 'node' ); // ensure all node elements have id attributes
  1895. for ( let i = 0; i < elements.length; i ++ ) {
  1896. const element = elements[ i ];
  1897. if ( element.hasAttribute( 'id' ) === false ) {
  1898. element.setAttribute( 'id', generateId() );
  1899. }
  1900. }
  1901. }
  1902. const matrix = new THREE.Matrix4();
  1903. const vector = new THREE.Vector3();
  1904. function parseNode( xml ) {
  1905. const data = {
  1906. name: xml.getAttribute( 'name' ) || '',
  1907. type: xml.getAttribute( 'type' ),
  1908. id: xml.getAttribute( 'id' ),
  1909. sid: xml.getAttribute( 'sid' ),
  1910. matrix: new THREE.Matrix4(),
  1911. nodes: [],
  1912. instanceCameras: [],
  1913. instanceControllers: [],
  1914. instanceLights: [],
  1915. instanceGeometries: [],
  1916. instanceNodes: [],
  1917. transforms: {}
  1918. };
  1919. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1920. const child = xml.childNodes[ i ];
  1921. if ( child.nodeType !== 1 ) continue;
  1922. let array;
  1923. switch ( child.nodeName ) {
  1924. case 'node':
  1925. data.nodes.push( child.getAttribute( 'id' ) );
  1926. parseNode( child );
  1927. break;
  1928. case 'instance_camera':
  1929. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  1930. break;
  1931. case 'instance_controller':
  1932. data.instanceControllers.push( parseNodeInstance( child ) );
  1933. break;
  1934. case 'instance_light':
  1935. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  1936. break;
  1937. case 'instance_geometry':
  1938. data.instanceGeometries.push( parseNodeInstance( child ) );
  1939. break;
  1940. case 'instance_node':
  1941. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  1942. break;
  1943. case 'matrix':
  1944. array = parseFloats( child.textContent );
  1945. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  1946. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1947. break;
  1948. case 'translate':
  1949. array = parseFloats( child.textContent );
  1950. vector.fromArray( array );
  1951. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  1952. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1953. break;
  1954. case 'rotate':
  1955. array = parseFloats( child.textContent );
  1956. const angle = THREE.MathUtils.degToRad( array[ 3 ] );
  1957. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  1958. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1959. break;
  1960. case 'scale':
  1961. array = parseFloats( child.textContent );
  1962. data.matrix.scale( vector.fromArray( array ) );
  1963. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  1964. break;
  1965. case 'extra':
  1966. break;
  1967. default:
  1968. console.log( child );
  1969. }
  1970. }
  1971. if ( hasNode( data.id ) ) {
  1972. console.warn( 'THREE.ColladaLoader: There is already a node with ID %s. Exclude current node from further processing.', data.id );
  1973. } else {
  1974. library.nodes[ data.id ] = data;
  1975. }
  1976. return data;
  1977. }
  1978. function parseNodeInstance( xml ) {
  1979. const data = {
  1980. id: parseId( xml.getAttribute( 'url' ) ),
  1981. materials: {},
  1982. skeletons: []
  1983. };
  1984. for ( let i = 0; i < xml.childNodes.length; i ++ ) {
  1985. const child = xml.childNodes[ i ];
  1986. switch ( child.nodeName ) {
  1987. case 'bind_material':
  1988. const instances = child.getElementsByTagName( 'instance_material' );
  1989. for ( let j = 0; j < instances.length; j ++ ) {
  1990. const instance = instances[ j ];
  1991. const symbol = instance.getAttribute( 'symbol' );
  1992. const target = instance.getAttribute( 'target' );
  1993. data.materials[ symbol ] = parseId( target );
  1994. }
  1995. break;
  1996. case 'skeleton':
  1997. data.skeletons.push( parseId( child.textContent ) );
  1998. break;
  1999. default:
  2000. break;
  2001. }
  2002. }
  2003. return data;
  2004. }
  2005. function buildSkeleton( skeletons, joints ) {
  2006. const boneData = [];
  2007. const sortedBoneData = [];
  2008. let i, j, data; // a skeleton can have multiple root bones. collada expresses this
  2009. // situtation with multiple "skeleton" tags per controller instance
  2010. for ( i = 0; i < skeletons.length; i ++ ) {
  2011. const skeleton = skeletons[ i ];
  2012. let root;
  2013. if ( hasNode( skeleton ) ) {
  2014. root = getNode( skeleton );
  2015. buildBoneHierarchy( root, joints, boneData );
  2016. } else if ( hasVisualScene( skeleton ) ) {
  2017. // handle case where the skeleton refers to the visual scene (#13335)
  2018. const visualScene = library.visualScenes[ skeleton ];
  2019. const children = visualScene.children;
  2020. for ( let j = 0; j < children.length; j ++ ) {
  2021. const child = children[ j ];
  2022. if ( child.type === 'JOINT' ) {
  2023. const root = getNode( child.id );
  2024. buildBoneHierarchy( root, joints, boneData );
  2025. }
  2026. }
  2027. } else {
  2028. console.error( 'THREE.ColladaLoader: Unable to find root bone of skeleton with ID:', skeleton );
  2029. }
  2030. } // sort bone data (the order is defined in the corresponding controller)
  2031. for ( i = 0; i < joints.length; i ++ ) {
  2032. for ( j = 0; j < boneData.length; j ++ ) {
  2033. data = boneData[ j ];
  2034. if ( data.bone.name === joints[ i ].name ) {
  2035. sortedBoneData[ i ] = data;
  2036. data.processed = true;
  2037. break;
  2038. }
  2039. }
  2040. } // add unprocessed bone data at the end of the list
  2041. for ( i = 0; i < boneData.length; i ++ ) {
  2042. data = boneData[ i ];
  2043. if ( data.processed === false ) {
  2044. sortedBoneData.push( data );
  2045. data.processed = true;
  2046. }
  2047. } // setup arrays for skeleton creation
  2048. const bones = [];
  2049. const boneInverses = [];
  2050. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  2051. data = sortedBoneData[ i ];
  2052. bones.push( data.bone );
  2053. boneInverses.push( data.boneInverse );
  2054. }
  2055. return new THREE.Skeleton( bones, boneInverses );
  2056. }
  2057. function buildBoneHierarchy( root, joints, boneData ) {
  2058. // setup bone data from visual scene
  2059. root.traverse( function ( object ) {
  2060. if ( object.isBone === true ) {
  2061. let boneInverse; // retrieve the boneInverse from the controller data
  2062. for ( let i = 0; i < joints.length; i ++ ) {
  2063. const joint = joints[ i ];
  2064. if ( joint.name === object.name ) {
  2065. boneInverse = joint.boneInverse;
  2066. break;
  2067. }
  2068. }
  2069. if ( boneInverse === undefined ) {
  2070. // Unfortunately, there can be joints in the visual scene that are not part of the
  2071. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  2072. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  2073. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  2074. // ensure a correct animation of the model.
  2075. boneInverse = new THREE.Matrix4();
  2076. }
  2077. boneData.push( {
  2078. bone: object,
  2079. boneInverse: boneInverse,
  2080. processed: false
  2081. } );
  2082. }
  2083. } );
  2084. }
  2085. function buildNode( data ) {
  2086. const objects = [];
  2087. const matrix = data.matrix;
  2088. const nodes = data.nodes;
  2089. const type = data.type;
  2090. const instanceCameras = data.instanceCameras;
  2091. const instanceControllers = data.instanceControllers;
  2092. const instanceLights = data.instanceLights;
  2093. const instanceGeometries = data.instanceGeometries;
  2094. const instanceNodes = data.instanceNodes; // nodes
  2095. for ( let i = 0, l = nodes.length; i < l; i ++ ) {
  2096. objects.push( getNode( nodes[ i ] ) );
  2097. } // instance cameras
  2098. for ( let i = 0, l = instanceCameras.length; i < l; i ++ ) {
  2099. const instanceCamera = getCamera( instanceCameras[ i ] );
  2100. if ( instanceCamera !== null ) {
  2101. objects.push( instanceCamera.clone() );
  2102. }
  2103. } // instance controllers
  2104. for ( let i = 0, l = instanceControllers.length; i < l; i ++ ) {
  2105. const instance = instanceControllers[ i ];
  2106. const controller = getController( instance.id );
  2107. const geometries = getGeometry( controller.id );
  2108. const newObjects = buildObjects( geometries, instance.materials );
  2109. const skeletons = instance.skeletons;
  2110. const joints = controller.skin.joints;
  2111. const skeleton = buildSkeleton( skeletons, joints );
  2112. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2113. const object = newObjects[ j ];
  2114. if ( object.isSkinnedMesh ) {
  2115. object.bind( skeleton, controller.skin.bindMatrix );
  2116. object.normalizeSkinWeights();
  2117. }
  2118. objects.push( object );
  2119. }
  2120. } // instance lights
  2121. for ( let i = 0, l = instanceLights.length; i < l; i ++ ) {
  2122. const instanceLight = getLight( instanceLights[ i ] );
  2123. if ( instanceLight !== null ) {
  2124. objects.push( instanceLight.clone() );
  2125. }
  2126. } // instance geometries
  2127. for ( let i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  2128. const instance = instanceGeometries[ i ]; // a single geometry instance in collada can lead to multiple object3Ds.
  2129. // this is the case when primitives are combined like triangles and lines
  2130. const geometries = getGeometry( instance.id );
  2131. const newObjects = buildObjects( geometries, instance.materials );
  2132. for ( let j = 0, jl = newObjects.length; j < jl; j ++ ) {
  2133. objects.push( newObjects[ j ] );
  2134. }
  2135. } // instance nodes
  2136. for ( let i = 0, l = instanceNodes.length; i < l; i ++ ) {
  2137. objects.push( getNode( instanceNodes[ i ] ).clone() );
  2138. }
  2139. let object;
  2140. if ( nodes.length === 0 && objects.length === 1 ) {
  2141. object = objects[ 0 ];
  2142. } else {
  2143. object = type === 'JOINT' ? new THREE.Bone() : new THREE.Group();
  2144. for ( let i = 0; i < objects.length; i ++ ) {
  2145. object.add( objects[ i ] );
  2146. }
  2147. }
  2148. object.name = type === 'JOINT' ? data.sid : data.name;
  2149. object.matrix.copy( matrix );
  2150. object.matrix.decompose( object.position, object.quaternion, object.scale );
  2151. return object;
  2152. }
  2153. const fallbackMaterial = new THREE.MeshBasicMaterial( {
  2154. color: 0xff00ff
  2155. } );
  2156. function resolveMaterialBinding( keys, instanceMaterials ) {
  2157. const materials = [];
  2158. for ( let i = 0, l = keys.length; i < l; i ++ ) {
  2159. const id = instanceMaterials[ keys[ i ] ];
  2160. if ( id === undefined ) {
  2161. console.warn( 'THREE.ColladaLoader: Material with key %s not found. Apply fallback material.', keys[ i ] );
  2162. materials.push( fallbackMaterial );
  2163. } else {
  2164. materials.push( getMaterial( id ) );
  2165. }
  2166. }
  2167. return materials;
  2168. }
  2169. function buildObjects( geometries, instanceMaterials ) {
  2170. const objects = [];
  2171. for ( const type in geometries ) {
  2172. const geometry = geometries[ type ];
  2173. const materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials ); // handle case if no materials are defined
  2174. if ( materials.length === 0 ) {
  2175. if ( type === 'lines' || type === 'linestrips' ) {
  2176. materials.push( new THREE.LineBasicMaterial() );
  2177. } else {
  2178. materials.push( new THREE.MeshPhongMaterial() );
  2179. }
  2180. } // regard skinning
  2181. const skinning = geometry.data.attributes.skinIndex !== undefined; // choose between a single or multi materials (material array)
  2182. const material = materials.length === 1 ? materials[ 0 ] : materials; // now create a specific 3D object
  2183. let object;
  2184. switch ( type ) {
  2185. case 'lines':
  2186. object = new THREE.LineSegments( geometry.data, material );
  2187. break;
  2188. case 'linestrips':
  2189. object = new THREE.Line( geometry.data, material );
  2190. break;
  2191. case 'triangles':
  2192. case 'polylist':
  2193. if ( skinning ) {
  2194. object = new THREE.SkinnedMesh( geometry.data, material );
  2195. } else {
  2196. object = new THREE.Mesh( geometry.data, material );
  2197. }
  2198. break;
  2199. }
  2200. objects.push( object );
  2201. }
  2202. return objects;
  2203. }
  2204. function hasNode( id ) {
  2205. return library.nodes[ id ] !== undefined;
  2206. }
  2207. function getNode( id ) {
  2208. return getBuild( library.nodes[ id ], buildNode );
  2209. } // visual scenes
  2210. function parseVisualScene( xml ) {
  2211. const data = {
  2212. name: xml.getAttribute( 'name' ),
  2213. children: []
  2214. };
  2215. prepareNodes( xml );
  2216. const elements = getElementsByTagName( xml, 'node' );
  2217. for ( let i = 0; i < elements.length; i ++ ) {
  2218. data.children.push( parseNode( elements[ i ] ) );
  2219. }
  2220. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  2221. }
  2222. function buildVisualScene( data ) {
  2223. const group = new THREE.Group();
  2224. group.name = data.name;
  2225. const children = data.children;
  2226. for ( let i = 0; i < children.length; i ++ ) {
  2227. const child = children[ i ];
  2228. group.add( getNode( child.id ) );
  2229. }
  2230. return group;
  2231. }
  2232. function hasVisualScene( id ) {
  2233. return library.visualScenes[ id ] !== undefined;
  2234. }
  2235. function getVisualScene( id ) {
  2236. return getBuild( library.visualScenes[ id ], buildVisualScene );
  2237. } // scenes
  2238. function parseScene( xml ) {
  2239. const instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  2240. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  2241. }
  2242. function setupAnimations() {
  2243. const clips = library.clips;
  2244. if ( isEmpty( clips ) === true ) {
  2245. if ( isEmpty( library.animations ) === false ) {
  2246. // if there are animations but no clips, we create a default clip for playback
  2247. const tracks = [];
  2248. for ( const id in library.animations ) {
  2249. const animationTracks = getAnimation( id );
  2250. for ( let i = 0, l = animationTracks.length; i < l; i ++ ) {
  2251. tracks.push( animationTracks[ i ] );
  2252. }
  2253. }
  2254. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  2255. }
  2256. } else {
  2257. for ( const id in clips ) {
  2258. animations.push( getAnimationClip( id ) );
  2259. }
  2260. }
  2261. } // convert the parser error element into text with each child elements text
  2262. // separated by new lines.
  2263. function parserErrorToText( parserError ) {
  2264. let result = '';
  2265. const stack = [ parserError ];
  2266. while ( stack.length ) {
  2267. const node = stack.shift();
  2268. if ( node.nodeType === Node.TEXT_NODE ) {
  2269. result += node.textContent;
  2270. } else {
  2271. result += '\n';
  2272. stack.push.apply( stack, node.childNodes );
  2273. }
  2274. }
  2275. return result.trim();
  2276. }
  2277. if ( text.length === 0 ) {
  2278. return {
  2279. scene: new THREE.Scene()
  2280. };
  2281. }
  2282. const xml = new DOMParser().parseFromString( text, 'application/xml' );
  2283. const collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  2284. const parserError = xml.getElementsByTagName( 'parsererror' )[ 0 ];
  2285. if ( parserError !== undefined ) {
  2286. // Chrome will return parser error with a div in it
  2287. const errorElement = getElementsByTagName( parserError, 'div' )[ 0 ];
  2288. let errorText;
  2289. if ( errorElement ) {
  2290. errorText = errorElement.textContent;
  2291. } else {
  2292. errorText = parserErrorToText( parserError );
  2293. }
  2294. console.error( 'THREE.ColladaLoader: Failed to parse collada file.\n', errorText );
  2295. return null;
  2296. } // metadata
  2297. const version = collada.getAttribute( 'version' );
  2298. console.log( 'THREE.ColladaLoader: File version', version );
  2299. const asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  2300. const textureLoader = new THREE.TextureLoader( this.manager );
  2301. textureLoader.setPath( this.resourcePath || path ).setCrossOrigin( this.crossOrigin );
  2302. let tgaLoader;
  2303. if ( THREE.TGALoader ) {
  2304. tgaLoader = new THREE.TGALoader( this.manager );
  2305. tgaLoader.setPath( this.resourcePath || path );
  2306. } //
  2307. const animations = [];
  2308. let kinematics = {};
  2309. let count = 0; //
  2310. const library = {
  2311. animations: {},
  2312. clips: {},
  2313. controllers: {},
  2314. images: {},
  2315. effects: {},
  2316. materials: {},
  2317. cameras: {},
  2318. lights: {},
  2319. geometries: {},
  2320. nodes: {},
  2321. visualScenes: {},
  2322. kinematicsModels: {},
  2323. physicsModels: {},
  2324. kinematicsScenes: {}
  2325. };
  2326. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  2327. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  2328. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  2329. parseLibrary( collada, 'library_images', 'image', parseImage );
  2330. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  2331. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  2332. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  2333. parseLibrary( collada, 'library_lights', 'light', parseLight );
  2334. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  2335. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  2336. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  2337. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  2338. parseLibrary( collada, 'library_physics_models', 'physics_model', parsePhysicsModel );
  2339. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  2340. buildLibrary( library.animations, buildAnimation );
  2341. buildLibrary( library.clips, buildAnimationClip );
  2342. buildLibrary( library.controllers, buildController );
  2343. buildLibrary( library.images, buildImage );
  2344. buildLibrary( library.effects, buildEffect );
  2345. buildLibrary( library.materials, buildMaterial );
  2346. buildLibrary( library.cameras, buildCamera );
  2347. buildLibrary( library.lights, buildLight );
  2348. buildLibrary( library.geometries, buildGeometry );
  2349. buildLibrary( library.visualScenes, buildVisualScene );
  2350. setupAnimations();
  2351. setupKinematics();
  2352. const scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  2353. scene.animations = animations;
  2354. if ( asset.upAxis === 'Z_UP' ) {
  2355. scene.quaternion.setFromEuler( new THREE.Euler( - Math.PI / 2, 0, 0 ) );
  2356. }
  2357. scene.scale.multiplyScalar( asset.unit );
  2358. return {
  2359. get animations() {
  2360. console.warn( 'THREE.ColladaLoader: Please access animations over scene.animations now.' );
  2361. return animations;
  2362. },
  2363. kinematics: kinematics,
  2364. library: library,
  2365. scene: scene
  2366. };
  2367. }
  2368. }
  2369. THREE.ColladaLoader = ColladaLoader;
  2370. } )();