ColladaLoader.js 79 KB

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