ColladaLoader.js 80 KB

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