ColladaLoader.js 81 KB

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