USDComposer.js 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594
  1. import {
  2. AnimationClip,
  3. BoxGeometry,
  4. BufferAttribute,
  5. BufferGeometry,
  6. CapsuleGeometry,
  7. ClampToEdgeWrapping,
  8. Color,
  9. ConeGeometry,
  10. CylinderGeometry,
  11. DirectionalLight,
  12. Euler,
  13. Group,
  14. Matrix4,
  15. Mesh,
  16. MeshPhysicalMaterial,
  17. MirroredRepeatWrapping,
  18. NoColorSpace,
  19. Object3D,
  20. OrthographicCamera,
  21. PerspectiveCamera,
  22. PointLight,
  23. Quaternion,
  24. QuaternionKeyframeTrack,
  25. RectAreaLight,
  26. RepeatWrapping,
  27. ShapeUtils,
  28. SkinnedMesh,
  29. Skeleton,
  30. Bone,
  31. SphereGeometry,
  32. SpotLight,
  33. SRGBColorSpace,
  34. Texture,
  35. Vector2,
  36. Vector3,
  37. VectorKeyframeTrack
  38. } from 'three';
  39. // Pre-compiled regex patterns for performance
  40. const VARIANT_PATH_REGEX = /^(.+?)\/\{(\w+)=(\w+)\}\/(.+)$/;
  41. // Spec types (must match USDCParser)
  42. const SpecType = {
  43. Unknown: 0,
  44. Attribute: 1,
  45. Connection: 2,
  46. Expression: 3,
  47. Mapper: 4,
  48. MapperArg: 5,
  49. Prim: 6,
  50. PseudoRoot: 7,
  51. Relationship: 8,
  52. RelationshipTarget: 9,
  53. Variant: 10,
  54. VariantSet: 11
  55. };
  56. // UsdGeomCamera fallback values (OpenUSD schema)
  57. const USD_CAMERA_DEFAULTS = {
  58. projection: 'perspective',
  59. clippingRange: [ 1, 1000000 ],
  60. horizontalAperture: 20.955,
  61. verticalAperture: 15.2908,
  62. horizontalApertureOffset: 0,
  63. verticalApertureOffset: 0,
  64. focalLength: 50,
  65. focusDistance: 0,
  66. fStop: 0
  67. };
  68. /**
  69. * USDComposer handles scene composition from parsed USD data.
  70. * This includes reference resolution, variant selection, transform handling,
  71. * and building the Three.js scene graph.
  72. *
  73. * Works with specsByPath format from USDCParser.
  74. */
  75. class USDComposer {
  76. constructor( manager = null ) {
  77. this.textureCache = {};
  78. this.skinnedMeshes = [];
  79. this.manager = manager;
  80. }
  81. /**
  82. * Compose a Three.js scene from parsed USD data.
  83. * @param {Object} parsedData - Data from USDCParser or USDAParser
  84. * @param {Object} assets - Dictionary of referenced assets (specsByPath or blob URLs)
  85. * @param {Object} variantSelections - External variant selections
  86. * @param {string} basePath - Base path for resolving relative references
  87. * @returns {Group} Three.js scene graph
  88. */
  89. compose( parsedData, assets = {}, variantSelections = {}, basePath = '' ) {
  90. this.specsByPath = parsedData.specsByPath;
  91. this.assets = assets;
  92. this.externalVariantSelections = variantSelections;
  93. this.basePath = basePath;
  94. this.skinnedMeshes = [];
  95. this.skeletons = {};
  96. // Build indexes for O(1) lookups
  97. this._buildIndexes();
  98. // Get FPS from root spec
  99. const rootSpec = this.specsByPath[ '/' ];
  100. const rootFields = rootSpec ? rootSpec.fields : {};
  101. this.fps = rootFields.framesPerSecond || rootFields.timeCodesPerSecond || 30;
  102. const group = new Group();
  103. this._buildHierarchy( group, '/' );
  104. // Bind skeletons to skinned meshes
  105. this._bindSkeletons();
  106. // Expose skeleton on the root group so that AnimationMixer's
  107. // PropertyBinding.findNode resolves bone names before scene objects.
  108. // Without this, Xform prims that share a name with a skeleton joint
  109. // would be animated instead of the bone.
  110. const skeletonPaths = Object.keys( this.skeletons );
  111. if ( skeletonPaths.length === 1 ) {
  112. group.skeleton = this.skeletons[ skeletonPaths[ 0 ] ].skeleton;
  113. }
  114. // Build animations
  115. group.animations = this._buildAnimations();
  116. // Handle metersPerUnit scaling
  117. const metersPerUnit = rootFields.metersPerUnit;
  118. if ( metersPerUnit !== undefined && metersPerUnit !== 1 ) {
  119. group.scale.setScalar( metersPerUnit );
  120. }
  121. // Handle Z-up to Y-up conversion
  122. if ( rootSpec && rootSpec.fields && rootSpec.fields.upAxis === 'Z' ) {
  123. group.rotation.x = - Math.PI / 2;
  124. }
  125. return group;
  126. }
  127. /**
  128. * Apply USD transforms to a Three.js object.
  129. * Handles xformOpOrder with proper matrix composition.
  130. * USD uses row-vector convention, Three.js uses column-vector.
  131. */
  132. applyTransform( obj, fields, attrs = {} ) {
  133. const data = { ...fields, ...attrs };
  134. const xformOpOrder = data[ 'xformOpOrder' ];
  135. // If we have xformOpOrder, apply transforms using matrices
  136. if ( xformOpOrder && xformOpOrder.length > 0 ) {
  137. const matrix = new Matrix4();
  138. const tempMatrix = new Matrix4();
  139. // Track scale for handling negative scale with rotation
  140. let scaleValues = null;
  141. // Iterate FORWARD for Three.js column-vector convention
  142. for ( let i = 0; i < xformOpOrder.length; i ++ ) {
  143. const op = xformOpOrder[ i ];
  144. const isInverse = op.startsWith( '!invert!' );
  145. const opName = isInverse ? op.slice( 8 ) : op;
  146. if ( opName === 'xformOp:transform' ) {
  147. const m = data[ 'xformOp:transform' ];
  148. if ( m && m.length === 16 ) {
  149. tempMatrix.set(
  150. m[ 0 ], m[ 4 ], m[ 8 ], m[ 12 ],
  151. m[ 1 ], m[ 5 ], m[ 9 ], m[ 13 ],
  152. m[ 2 ], m[ 6 ], m[ 10 ], m[ 14 ],
  153. m[ 3 ], m[ 7 ], m[ 11 ], m[ 15 ]
  154. );
  155. if ( isInverse ) tempMatrix.invert();
  156. matrix.multiply( tempMatrix );
  157. }
  158. } else if ( opName === 'xformOp:translate' ) {
  159. const t = data[ 'xformOp:translate' ];
  160. if ( t ) {
  161. tempMatrix.makeTranslation( t[ 0 ], t[ 1 ], t[ 2 ] );
  162. if ( isInverse ) tempMatrix.invert();
  163. matrix.multiply( tempMatrix );
  164. }
  165. } else if ( opName === 'xformOp:translate:pivot' ) {
  166. const t = data[ 'xformOp:translate:pivot' ];
  167. if ( t ) {
  168. tempMatrix.makeTranslation( t[ 0 ], t[ 1 ], t[ 2 ] );
  169. if ( isInverse ) tempMatrix.invert();
  170. matrix.multiply( tempMatrix );
  171. }
  172. } else if ( opName === 'xformOp:scale' ) {
  173. const s = data[ 'xformOp:scale' ];
  174. if ( s ) {
  175. if ( Array.isArray( s ) ) {
  176. tempMatrix.makeScale( s[ 0 ], s[ 1 ], s[ 2 ] );
  177. scaleValues = [ s[ 0 ], s[ 1 ], s[ 2 ] ];
  178. } else {
  179. tempMatrix.makeScale( s, s, s );
  180. scaleValues = [ s, s, s ];
  181. }
  182. if ( isInverse ) tempMatrix.invert();
  183. matrix.multiply( tempMatrix );
  184. }
  185. } else if ( opName === 'xformOp:rotateXYZ' ) {
  186. const r = data[ 'xformOp:rotateXYZ' ];
  187. if ( r ) {
  188. // USD rotateXYZ: matrix = Rx * Ry * Rz
  189. // Three.js Euler 'ZYX' order produces same result
  190. const euler = new Euler(
  191. r[ 0 ] * Math.PI / 180,
  192. r[ 1 ] * Math.PI / 180,
  193. r[ 2 ] * Math.PI / 180,
  194. 'ZYX'
  195. );
  196. tempMatrix.makeRotationFromEuler( euler );
  197. if ( isInverse ) tempMatrix.invert();
  198. matrix.multiply( tempMatrix );
  199. }
  200. } else if ( opName === 'xformOp:rotateX' ) {
  201. const r = data[ 'xformOp:rotateX' ];
  202. if ( r !== undefined ) {
  203. tempMatrix.makeRotationX( r * Math.PI / 180 );
  204. if ( isInverse ) tempMatrix.invert();
  205. matrix.multiply( tempMatrix );
  206. }
  207. } else if ( opName === 'xformOp:rotateY' ) {
  208. const r = data[ 'xformOp:rotateY' ];
  209. if ( r !== undefined ) {
  210. tempMatrix.makeRotationY( r * Math.PI / 180 );
  211. if ( isInverse ) tempMatrix.invert();
  212. matrix.multiply( tempMatrix );
  213. }
  214. } else if ( opName === 'xformOp:rotateZ' ) {
  215. const r = data[ 'xformOp:rotateZ' ];
  216. if ( r !== undefined ) {
  217. tempMatrix.makeRotationZ( r * Math.PI / 180 );
  218. if ( isInverse ) tempMatrix.invert();
  219. matrix.multiply( tempMatrix );
  220. }
  221. } else if ( opName === 'xformOp:orient' ) {
  222. const q = data[ 'xformOp:orient' ];
  223. if ( q && q.length === 4 ) {
  224. const quat = new Quaternion( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  225. tempMatrix.makeRotationFromQuaternion( quat );
  226. if ( isInverse ) tempMatrix.invert();
  227. matrix.multiply( tempMatrix );
  228. }
  229. }
  230. }
  231. obj.matrix.copy( matrix );
  232. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  233. // Fix for negative scale: decompose() may absorb negative scale into quaternion
  234. // Restore original scale signs to keep animation consistent
  235. if ( scaleValues ) {
  236. const negX = scaleValues[ 0 ] < 0;
  237. const negY = scaleValues[ 1 ] < 0;
  238. const negZ = scaleValues[ 2 ] < 0;
  239. const negCount = ( negX ? 1 : 0 ) + ( negY ? 1 : 0 ) + ( negZ ? 1 : 0 );
  240. // decompose() absorbs pairs of negative scales into rotation
  241. // For [-1,-1,-1] → [-1,1,1], Y and Z were absorbed, flip quat.y and quat.w
  242. if ( negCount === 3 ) {
  243. obj.scale.set( scaleValues[ 0 ], scaleValues[ 1 ], scaleValues[ 2 ] );
  244. obj.quaternion.set(
  245. obj.quaternion.x,
  246. - obj.quaternion.y,
  247. obj.quaternion.z,
  248. - obj.quaternion.w
  249. );
  250. }
  251. }
  252. return;
  253. }
  254. // Fallback: handle individual transform ops without order
  255. if ( data[ 'xformOp:translate' ] ) {
  256. const t = data[ 'xformOp:translate' ];
  257. obj.position.set( t[ 0 ], t[ 1 ], t[ 2 ] );
  258. }
  259. if ( data[ 'xformOp:translate:pivot' ] ) {
  260. const p = data[ 'xformOp:translate:pivot' ];
  261. obj.pivot = new Vector3( p[ 0 ], p[ 1 ], p[ 2 ] );
  262. }
  263. if ( data[ 'xformOp:scale' ] ) {
  264. const s = data[ 'xformOp:scale' ];
  265. if ( Array.isArray( s ) ) {
  266. obj.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  267. } else {
  268. obj.scale.set( s, s, s );
  269. }
  270. }
  271. if ( data[ 'xformOp:rotateXYZ' ] ) {
  272. const r = data[ 'xformOp:rotateXYZ' ];
  273. obj.rotation.set(
  274. r[ 0 ] * Math.PI / 180,
  275. r[ 1 ] * Math.PI / 180,
  276. r[ 2 ] * Math.PI / 180
  277. );
  278. }
  279. if ( data[ 'xformOp:orient' ] ) {
  280. const q = data[ 'xformOp:orient' ];
  281. if ( q.length === 4 ) {
  282. obj.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  283. }
  284. }
  285. }
  286. /**
  287. * Build indexes for efficient lookups.
  288. * Called once during compose() to avoid O(n) scans per lookup.
  289. */
  290. _buildIndexes() {
  291. // childrenByPath: parentPath -> [childName1, childName2, ...]
  292. this.childrenByPath = new Map();
  293. // attributesByPrimPath: primPath -> Map(attrName -> attrSpec)
  294. this.attributesByPrimPath = new Map();
  295. // materialsByRoot: rootPath -> [materialPath1, materialPath2, ...]
  296. this.materialsByRoot = new Map();
  297. // shadersByMaterialPath: materialPath -> [shaderPath1, shaderPath2, ...]
  298. this.shadersByMaterialPath = new Map();
  299. // geomSubsetsByMeshPath: meshPath -> [subsetPath1, subsetPath2, ...]
  300. this.geomSubsetsByMeshPath = new Map();
  301. for ( const path in this.specsByPath ) {
  302. const spec = this.specsByPath[ path ];
  303. if ( spec.specType === SpecType.Prim ) {
  304. // Build parent-child index
  305. const lastSlash = path.lastIndexOf( '/' );
  306. if ( lastSlash > 0 ) {
  307. const parentPath = path.slice( 0, lastSlash );
  308. const childName = path.slice( lastSlash + 1 );
  309. if ( ! this.childrenByPath.has( parentPath ) ) {
  310. this.childrenByPath.set( parentPath, [] );
  311. }
  312. this.childrenByPath.get( parentPath ).push( { name: childName, path: path } );
  313. } else if ( lastSlash === 0 && path.length > 1 ) {
  314. // Direct child of root
  315. const childName = path.slice( 1 );
  316. if ( ! this.childrenByPath.has( '/' ) ) {
  317. this.childrenByPath.set( '/', [] );
  318. }
  319. this.childrenByPath.get( '/' ).push( { name: childName, path: path } );
  320. }
  321. const typeName = spec.fields.typeName;
  322. // Build material index
  323. if ( typeName === 'Material' ) {
  324. const parts = path.split( '/' );
  325. const rootPath = parts.length > 1 ? '/' + parts[ 1 ] : '/';
  326. if ( ! this.materialsByRoot.has( rootPath ) ) {
  327. this.materialsByRoot.set( rootPath, [] );
  328. }
  329. this.materialsByRoot.get( rootPath ).push( path );
  330. }
  331. // Build shader index (shaders are children or descendants of materials)
  332. if ( typeName === 'Shader' && lastSlash > 0 ) {
  333. // Walk up ancestors to find the nearest Material prim.
  334. // Shaders may be direct children of a Material, or nested
  335. // inside a NodeGraph (common with MaterialX materials).
  336. let ancestorPath = path.slice( 0, lastSlash );
  337. while ( ancestorPath.length > 0 ) {
  338. const ancestorSpec = this.specsByPath[ ancestorPath ];
  339. if ( ancestorSpec && ancestorSpec.specType === SpecType.Prim && ancestorSpec.fields.typeName === 'Material' ) {
  340. if ( ! this.shadersByMaterialPath.has( ancestorPath ) ) {
  341. this.shadersByMaterialPath.set( ancestorPath, [] );
  342. }
  343. this.shadersByMaterialPath.get( ancestorPath ).push( path );
  344. break;
  345. }
  346. const slash = ancestorPath.lastIndexOf( '/' );
  347. if ( slash <= 0 ) break;
  348. ancestorPath = ancestorPath.slice( 0, slash );
  349. }
  350. }
  351. // Build GeomSubset index (subsets are children of meshes)
  352. if ( typeName === 'GeomSubset' && lastSlash > 0 ) {
  353. const meshPath = path.slice( 0, lastSlash );
  354. if ( ! this.geomSubsetsByMeshPath.has( meshPath ) ) {
  355. this.geomSubsetsByMeshPath.set( meshPath, [] );
  356. }
  357. this.geomSubsetsByMeshPath.get( meshPath ).push( path );
  358. }
  359. } else if ( spec.specType === SpecType.Attribute || spec.specType === SpecType.Relationship ) {
  360. // Build attribute index
  361. const dotIndex = path.lastIndexOf( '.' );
  362. if ( dotIndex > 0 ) {
  363. const primPath = path.slice( 0, dotIndex );
  364. const attrName = path.slice( dotIndex + 1 );
  365. if ( ! this.attributesByPrimPath.has( primPath ) ) {
  366. this.attributesByPrimPath.set( primPath, new Map() );
  367. }
  368. this.attributesByPrimPath.get( primPath ).set( attrName, spec );
  369. }
  370. }
  371. }
  372. }
  373. /**
  374. * Check if a path is a direct child of parentPath.
  375. */
  376. _isDirectChild( parentPath, path, prefix ) {
  377. if ( ! path.startsWith( prefix ) ) return false;
  378. const remainder = path.slice( prefix.length );
  379. if ( remainder.length === 0 ) return false;
  380. // Check for variant paths or simple names
  381. if ( remainder.startsWith( '{' ) ) {
  382. return false; // Variant paths are not direct children
  383. }
  384. return ! remainder.includes( '/' );
  385. }
  386. /**
  387. * Build the scene hierarchy recursively.
  388. * Uses childrenByPath index for O(1) child lookup instead of O(n) iteration.
  389. */
  390. _buildHierarchy( parent, parentPath ) {
  391. // Collect children from parentPath and any active variant paths
  392. const childEntries = [];
  393. const seenPaths = new Set();
  394. // Get direct children using the index
  395. const directChildren = this.childrenByPath.get( parentPath );
  396. if ( directChildren ) {
  397. for ( const child of directChildren ) {
  398. if ( ! seenPaths.has( child.path ) ) {
  399. seenPaths.add( child.path );
  400. childEntries.push( child );
  401. }
  402. }
  403. }
  404. // Also get children from active variant paths
  405. const variantPaths = this._getVariantPaths( parentPath );
  406. for ( const vp of variantPaths ) {
  407. const variantChildren = this.childrenByPath.get( vp );
  408. if ( variantChildren ) {
  409. for ( const child of variantChildren ) {
  410. if ( ! seenPaths.has( child.path ) ) {
  411. seenPaths.add( child.path );
  412. childEntries.push( child );
  413. }
  414. }
  415. }
  416. }
  417. // Process each child
  418. for ( const { name, path } of childEntries ) {
  419. const spec = this.specsByPath[ path ];
  420. if ( ! spec || spec.specType !== SpecType.Prim ) continue;
  421. const typeName = spec.fields.typeName;
  422. // Check for references/payloads
  423. const refValues = this._getReferences( spec );
  424. if ( refValues.length > 0 ) {
  425. // Get local variant selections from this prim
  426. const localVariants = this._getLocalVariantSelections( spec.fields );
  427. // Resolve all references
  428. const resolvedGroups = [];
  429. for ( const refValue of refValues ) {
  430. const referencedGroup = this._resolveReference( refValue, localVariants );
  431. if ( referencedGroup ) resolvedGroups.push( referencedGroup );
  432. }
  433. if ( resolvedGroups.length > 0 ) {
  434. const attrs = this._getAttributes( path );
  435. // Single reference with single mesh: use optimized path
  436. // This handles the USDZExporter pattern: Xform references geometry file
  437. if ( resolvedGroups.length === 1 ) {
  438. const singleMesh = this._findSingleMesh( resolvedGroups[ 0 ] );
  439. if ( singleMesh && ( typeName === 'Xform' || ! typeName ) ) {
  440. // Merge the mesh into this prim
  441. singleMesh.name = name;
  442. this.applyTransform( singleMesh, spec.fields, attrs );
  443. // Apply material binding from the referencing prim if present
  444. this._applyMaterialBinding( singleMesh, path );
  445. parent.add( singleMesh );
  446. // Still build local children (overrides)
  447. this._buildHierarchy( singleMesh, path );
  448. continue;
  449. }
  450. }
  451. // Create a container for the referenced content
  452. const obj = new Object3D();
  453. obj.name = name;
  454. this.applyTransform( obj, spec.fields, attrs );
  455. // Add all children from all resolved references
  456. for ( const referencedGroup of resolvedGroups ) {
  457. while ( referencedGroup.children.length > 0 ) {
  458. obj.add( referencedGroup.children[ 0 ] );
  459. }
  460. }
  461. parent.add( obj );
  462. // Still build local children (overrides)
  463. this._buildHierarchy( obj, path );
  464. continue;
  465. }
  466. }
  467. // Build appropriate object based on type
  468. if ( typeName === 'SkelRoot' ) {
  469. // Skeletal root - treat as transform but track for skeleton binding
  470. const obj = new Object3D();
  471. obj.name = name;
  472. obj.userData.isSkelRoot = true;
  473. const attrs = this._getAttributes( path );
  474. this.applyTransform( obj, spec.fields, attrs );
  475. parent.add( obj );
  476. this._buildHierarchy( obj, path );
  477. } else if ( typeName === 'Skeleton' ) {
  478. // Build skeleton and store it
  479. const skeleton = this._buildSkeleton( path );
  480. if ( skeleton ) {
  481. this.skeletons[ path ] = skeleton;
  482. }
  483. // Recursively build children (may contain SkelAnimation)
  484. this._buildHierarchy( parent, path );
  485. } else if ( typeName === 'SkelAnimation' ) {
  486. // Skip - animations are processed separately in _buildAnimations
  487. } else if ( typeName === 'Mesh' ) {
  488. const obj = this._buildMesh( path, spec );
  489. if ( obj ) {
  490. parent.add( obj );
  491. this._buildHierarchy( obj, path );
  492. }
  493. } else if ( typeName === 'Camera' ) {
  494. const obj = this._buildCamera( path );
  495. obj.name = name;
  496. const attrs = this._getAttributes( path );
  497. this.applyTransform( obj, spec.fields, attrs );
  498. parent.add( obj );
  499. this._buildHierarchy( obj, path );
  500. } else if ( typeName === 'DistantLight' || typeName === 'SphereLight' || typeName === 'RectLight' || typeName === 'DiskLight' ) {
  501. const obj = this._buildLight( path, typeName );
  502. obj.name = name;
  503. const attrs = this._getAttributes( path );
  504. this.applyTransform( obj, spec.fields, attrs );
  505. parent.add( obj );
  506. this._buildHierarchy( obj, path );
  507. } else if ( typeName === 'Cube' || typeName === 'Sphere' || typeName === 'Cylinder' || typeName === 'Cone' || typeName === 'Capsule' ) {
  508. const obj = this._buildGeomPrimitive( path, spec, typeName );
  509. if ( obj ) {
  510. parent.add( obj );
  511. this._buildHierarchy( obj, path );
  512. }
  513. } else if ( typeName === 'Material' || typeName === 'Shader' || typeName === 'GeomSubset' ) {
  514. // Skip materials/shaders/subsets, they're referenced by meshes
  515. } else {
  516. // Transform node, group, or unknown type
  517. const obj = new Object3D();
  518. obj.name = name;
  519. const attrs = this._getAttributes( path );
  520. this.applyTransform( obj, spec.fields, attrs );
  521. parent.add( obj );
  522. this._buildHierarchy( obj, path );
  523. }
  524. }
  525. }
  526. /**
  527. * Get variant paths for a parent path based on variant selections.
  528. */
  529. _getVariantPaths( parentPath ) {
  530. const parentSpec = this.specsByPath[ parentPath ];
  531. const variantSetChildren = parentSpec?.fields?.variantSetChildren;
  532. const variantPaths = [];
  533. if ( ! variantSetChildren || variantSetChildren.length === 0 ) {
  534. return variantPaths;
  535. }
  536. for ( const variantSetName of variantSetChildren ) {
  537. // External selections take priority
  538. let selectedVariant = this.externalVariantSelections[ variantSetName ] || null;
  539. // Fall back to file's internal selection
  540. if ( ! selectedVariant ) {
  541. const variantSelection = parentSpec.fields.variantSelection;
  542. selectedVariant = variantSelection ? variantSelection[ variantSetName ] : null;
  543. }
  544. // Fall back to first variant child
  545. if ( ! selectedVariant ) {
  546. const variantSetPath = parentPath + '/{' + variantSetName + '=}';
  547. const variantSetSpec = this.specsByPath[ variantSetPath ];
  548. if ( variantSetSpec?.fields?.variantChildren ) {
  549. selectedVariant = variantSetSpec.fields.variantChildren[ 0 ];
  550. }
  551. }
  552. if ( selectedVariant ) {
  553. const variantPath = parentPath + '/{' + variantSetName + '=' + selectedVariant + '}';
  554. variantPaths.push( variantPath );
  555. }
  556. }
  557. return variantPaths;
  558. }
  559. /**
  560. * Resolve a file path relative to basePath.
  561. */
  562. _resolveFilePath( refPath ) {
  563. let cleanPath = refPath;
  564. // Remove ./ prefix
  565. if ( cleanPath.startsWith( './' ) ) {
  566. cleanPath = cleanPath.slice( 2 );
  567. }
  568. // Combine with base path
  569. if ( this.basePath ) {
  570. return this.basePath + '/' + cleanPath;
  571. }
  572. return cleanPath;
  573. }
  574. /**
  575. * Resolve a USD reference and return the composed content.
  576. * @param {string} refValue - Reference value like "@./path/to/file.usdc@"
  577. * @param {Object} localVariants - Variant selections to apply
  578. * @returns {Group|null} Composed content or null
  579. */
  580. _resolveReference( refValue, localVariants = {} ) {
  581. if ( ! refValue ) return null;
  582. const match = refValue.match( /@([^@]+)@(?:<([^>]+)>)?/ );
  583. if ( ! match ) return null;
  584. const filePath = match[ 1 ];
  585. const primPath = match[ 2 ]; // e.g., "/Geometry"
  586. const resolvedPath = this._resolveFilePath( filePath );
  587. // Merge variant selections - external takes priority, then local
  588. const mergedVariants = { ...localVariants, ...this.externalVariantSelections };
  589. // Look up pre-parsed data in assets
  590. const referencedData = this.assets[ resolvedPath ];
  591. if ( ! referencedData ) return null;
  592. // If it's specsByPath data, compose it
  593. if ( referencedData.specsByPath ) {
  594. const composer = new USDComposer( this.manager );
  595. const newBasePath = this._getBasePath( resolvedPath );
  596. const composedGroup = composer.compose( referencedData, this.assets, mergedVariants, newBasePath );
  597. // If a primPath is specified, find and return just that subtree
  598. if ( primPath ) {
  599. const primName = primPath.split( '/' ).pop();
  600. // Find the direct child with this name (not a deep search)
  601. // This is important because there may be multiple objects with the same name
  602. let targetObject = null;
  603. for ( const child of composedGroup.children ) {
  604. if ( child.name === primName ) {
  605. targetObject = child;
  606. break;
  607. }
  608. }
  609. if ( targetObject ) {
  610. // Detach from parent for re-parenting
  611. composedGroup.remove( targetObject );
  612. // Wrap in a group to maintain consistent return type
  613. const wrapper = new Group();
  614. wrapper.add( targetObject );
  615. return wrapper;
  616. }
  617. }
  618. return composedGroup;
  619. }
  620. // If it's already a Three.js Group (legacy support), clone it
  621. if ( referencedData.isGroup || referencedData.isObject3D ) {
  622. return referencedData.clone();
  623. }
  624. return null;
  625. }
  626. /**
  627. * Find a single mesh in the group's shallow hierarchy.
  628. * Only returns a mesh if it's at depth 0 or 1, not deeply nested.
  629. * This preserves transforms in complex hierarchies like Kitchen Set
  630. * while supporting USDZExporter round-trip (Xform > Xform > Mesh pattern).
  631. */
  632. _findSingleMesh( group ) {
  633. // Check direct children first
  634. for ( const child of group.children ) {
  635. if ( child.isMesh ) {
  636. group.remove( child );
  637. return child;
  638. }
  639. }
  640. // Check grandchildren (USDZExporter pattern: Xform > Geometry > Mesh)
  641. // Only if there's exactly one child with exactly one grandchild
  642. if ( group.children.length === 1 ) {
  643. const child = group.children[ 0 ];
  644. if ( child.children && child.children.length === 1 ) {
  645. const grandchild = child.children[ 0 ];
  646. if ( grandchild.isMesh && ! this._hasNonIdentityTransform( child ) ) {
  647. // Safe to merge - intermediate has identity transform
  648. child.remove( grandchild );
  649. return grandchild;
  650. }
  651. }
  652. }
  653. return null;
  654. }
  655. /**
  656. * Check if an object has a non-identity local transform.
  657. */
  658. _hasNonIdentityTransform( obj ) {
  659. const pos = obj.position;
  660. const rot = obj.rotation;
  661. const scale = obj.scale;
  662. const hasPosition = pos.x !== 0 || pos.y !== 0 || pos.z !== 0;
  663. const hasRotation = rot.x !== 0 || rot.y !== 0 || rot.z !== 0;
  664. const hasScale = scale.x !== 1 || scale.y !== 1 || scale.z !== 1;
  665. return hasPosition || hasRotation || hasScale;
  666. }
  667. /**
  668. * Get the base path (directory) from a file path.
  669. */
  670. _getBasePath( filePath ) {
  671. const lastSlash = filePath.lastIndexOf( '/' );
  672. return lastSlash >= 0 ? filePath.slice( 0, lastSlash ) : '';
  673. }
  674. /**
  675. * Extract variant selections from a spec's fields.
  676. */
  677. _getLocalVariantSelections( fields ) {
  678. const variants = {};
  679. if ( fields.variantSelection ) {
  680. for ( const key in fields.variantSelection ) {
  681. variants[ key ] = fields.variantSelection[ key ];
  682. }
  683. }
  684. return variants;
  685. }
  686. /**
  687. * Get all reference values from a prim spec.
  688. * @returns {string[]} Array of reference strings like "@path@" or "@path@<prim>"
  689. */
  690. _getReferences( spec ) {
  691. const results = [];
  692. if ( spec.fields.references && spec.fields.references.length > 0 ) {
  693. const ref = spec.fields.references[ 0 ];
  694. if ( typeof ref === 'string' ) {
  695. // Extract all @...@ references (handles both single and array values)
  696. const matches = ref.matchAll( /@([^@]+)@(?:<([^>]+)>)?/g );
  697. for ( const match of matches ) {
  698. results.push( match[ 0 ] );
  699. }
  700. } else if ( ref.assetPath ) {
  701. results.push( '@' + ref.assetPath + '@' );
  702. }
  703. }
  704. if ( results.length === 0 && spec.fields.payload ) {
  705. const payload = spec.fields.payload;
  706. if ( typeof payload === 'string' ) results.push( payload );
  707. else if ( payload.assetPath ) results.push( '@' + payload.assetPath + '@' );
  708. }
  709. return results;
  710. }
  711. /**
  712. * Get attributes for a path from attribute specs.
  713. */
  714. _getAttributes( path ) {
  715. const attrs = {};
  716. this._collectAttributesFromPath( path, attrs );
  717. // Collect overrides from sibling variants (when path is inside a variant)
  718. const variantMatch = path.match( VARIANT_PATH_REGEX );
  719. if ( variantMatch ) {
  720. const basePath = variantMatch[ 1 ];
  721. const relativePath = variantMatch[ 4 ];
  722. const variantPaths = this._getVariantPaths( basePath );
  723. for ( const vp of variantPaths ) {
  724. if ( path.startsWith( vp ) ) continue;
  725. const overridePath = vp + '/' + relativePath;
  726. this._collectAttributesFromPath( overridePath, attrs );
  727. }
  728. } else {
  729. // Check for variant overrides at ancestor levels
  730. const parts = path.split( '/' );
  731. for ( let i = 1; i < parts.length - 1; i ++ ) {
  732. const ancestorPath = parts.slice( 0, i + 1 ).join( '/' );
  733. const relativePath = parts.slice( i + 1 ).join( '/' );
  734. const variantPaths = this._getVariantPaths( ancestorPath );
  735. for ( const vp of variantPaths ) {
  736. const overridePath = vp + '/' + relativePath;
  737. this._collectAttributesFromPath( overridePath, attrs );
  738. }
  739. }
  740. }
  741. return attrs;
  742. }
  743. _collectAttributesFromPath( path, attrs ) {
  744. // Use the attribute index for O(1) lookup instead of O(n) iteration
  745. const attrMap = this.attributesByPrimPath.get( path );
  746. if ( ! attrMap ) return;
  747. for ( const [ attrName, attrSpec ] of attrMap ) {
  748. if ( attrSpec.fields?.default !== undefined ) {
  749. attrs[ attrName ] = attrSpec.fields.default;
  750. } else if ( attrSpec.fields?.timeSamples ) {
  751. // For animated attributes without default, use the first time sample (rest pose)
  752. const { times, values } = attrSpec.fields.timeSamples;
  753. if ( times && values && times.length > 0 ) {
  754. // Find time 0, or use the first available time
  755. const idx = times.indexOf( 0 );
  756. attrs[ attrName ] = idx >= 0 ? values[ idx ] : values[ 0 ];
  757. }
  758. }
  759. if ( attrSpec.fields?.elementSize !== undefined ) {
  760. attrs[ attrName + ':elementSize' ] = attrSpec.fields.elementSize;
  761. }
  762. if ( attrName.startsWith( 'primvars:' ) && attrSpec.fields?.typeName !== undefined ) {
  763. attrs[ attrName + ':typeName' ] = attrSpec.fields.typeName;
  764. }
  765. }
  766. }
  767. /**
  768. * Build a mesh from a USD geometric primitive (Cube, Sphere, Cylinder, Cone, Capsule).
  769. */
  770. _buildGeomPrimitive( path, spec, typeName ) {
  771. const attrs = this._getAttributes( path );
  772. const name = path.split( '/' ).pop();
  773. let geometry;
  774. switch ( typeName ) {
  775. case 'Cube': {
  776. const size = attrs[ 'size' ] || 2;
  777. geometry = new BoxGeometry( size, size, size );
  778. break;
  779. }
  780. case 'Sphere': {
  781. const radius = attrs[ 'radius' ] || 1;
  782. geometry = new SphereGeometry( radius, 32, 16 );
  783. break;
  784. }
  785. case 'Cylinder': {
  786. const height = attrs[ 'height' ] || 2;
  787. const radius = attrs[ 'radius' ] || 1;
  788. geometry = new CylinderGeometry( radius, radius, height, 32 );
  789. break;
  790. }
  791. case 'Cone': {
  792. const height = attrs[ 'height' ] || 2;
  793. const radius = attrs[ 'radius' ] || 1;
  794. geometry = new ConeGeometry( radius, height, 32 );
  795. break;
  796. }
  797. case 'Capsule': {
  798. const height = attrs[ 'height' ] || 1;
  799. const radius = attrs[ 'radius' ] || 0.5;
  800. geometry = new CapsuleGeometry( radius, height, 16, 32 );
  801. break;
  802. }
  803. }
  804. // USD defaults axis to "Z", Three.js uses Y
  805. const axis = attrs[ 'axis' ] || 'Z';
  806. if ( axis === 'X' ) {
  807. geometry.rotateZ( - Math.PI / 2 );
  808. } else if ( axis === 'Z' ) {
  809. geometry.rotateX( Math.PI / 2 );
  810. }
  811. const material = this._buildMaterial( path, spec.fields );
  812. const mesh = new Mesh( geometry, material );
  813. mesh.name = name;
  814. this.applyTransform( mesh, spec.fields, attrs );
  815. return mesh;
  816. }
  817. /**
  818. * Build a mesh from a Mesh spec.
  819. */
  820. _buildMesh( path, spec ) {
  821. const attrs = this._getAttributes( path );
  822. // Check for skinning data
  823. const jointIndices = attrs[ 'primvars:skel:jointIndices' ];
  824. const jointWeights = attrs[ 'primvars:skel:jointWeights' ];
  825. const hasSkinning = jointIndices && jointWeights &&
  826. jointIndices.length > 0 && jointWeights.length > 0;
  827. // Collect GeomSubsets for multi-material support
  828. const geomSubsets = this._getGeomSubsets( path );
  829. let geometry, material;
  830. if ( geomSubsets.length > 0 ) {
  831. geometry = this._buildGeometryWithSubsets( attrs, geomSubsets, hasSkinning );
  832. const meshMaterialPath = this._getMaterialPath( path, spec.fields );
  833. material = geomSubsets.map( subset => {
  834. const matPath = subset.materialPath || meshMaterialPath;
  835. return this._buildMaterialForPath( matPath );
  836. } );
  837. } else {
  838. geometry = this._buildGeometry( path, attrs, hasSkinning );
  839. material = this._buildMaterial( path, spec.fields );
  840. }
  841. const displayColor = attrs[ 'primvars:displayColor' ];
  842. if ( displayColor && displayColor.length >= 3 ) {
  843. const applyDisplayColor = ( mat ) => {
  844. if ( mat.color && mat.color.r === 1 && mat.color.g === 1 && mat.color.b === 1 && ! mat.map ) {
  845. mat.color.setRGB( displayColor[ 0 ], displayColor[ 1 ], displayColor[ 2 ], SRGBColorSpace );
  846. }
  847. };
  848. if ( Array.isArray( material ) ) {
  849. material.forEach( applyDisplayColor );
  850. } else {
  851. applyDisplayColor( material );
  852. }
  853. }
  854. const displayOpacity = attrs[ 'primvars:displayOpacity' ];
  855. if ( displayOpacity && displayOpacity.length === 1 && geomSubsets.length === 0 ) {
  856. const opacity = displayOpacity[ 0 ];
  857. const applyDisplayOpacity = ( mat ) => {
  858. if ( opacity < 1 && mat.opacity === 1 && mat.transparent === false ) {
  859. mat.opacity = opacity;
  860. mat.transparent = true;
  861. }
  862. };
  863. if ( Array.isArray( material ) ) {
  864. material.forEach( applyDisplayOpacity );
  865. } else {
  866. applyDisplayOpacity( material );
  867. }
  868. }
  869. let mesh;
  870. if ( hasSkinning ) {
  871. mesh = new SkinnedMesh( geometry, material );
  872. // Find skeleton path from skel:skeleton relationship
  873. let skelBindingSpec = this.specsByPath[ path + '.skel:skeleton' ];
  874. if ( ! skelBindingSpec ) {
  875. skelBindingSpec = this.specsByPath[ path + '.rel skel:skeleton' ];
  876. }
  877. let skeletonPath = null;
  878. if ( skelBindingSpec ) {
  879. if ( skelBindingSpec.fields.targetPaths && skelBindingSpec.fields.targetPaths.length > 0 ) {
  880. skeletonPath = skelBindingSpec.fields.targetPaths[ 0 ];
  881. } else if ( skelBindingSpec.fields.default ) {
  882. skeletonPath = skelBindingSpec.fields.default.replace( /<|>/g, '' );
  883. }
  884. }
  885. // Get per-mesh joint mapping
  886. const localJoints = attrs[ 'skel:joints' ];
  887. // Get geomBindTransform if present
  888. const geomBindTransform = attrs[ 'primvars:skel:geomBindTransform' ];
  889. this.skinnedMeshes.push( { mesh, skeletonPath, path, localJoints, geomBindTransform } );
  890. } else {
  891. mesh = new Mesh( geometry, material );
  892. }
  893. mesh.name = path.split( '/' ).pop();
  894. this.applyTransform( mesh, spec.fields, attrs );
  895. return mesh;
  896. }
  897. /**
  898. * Build a camera from a Camera spec.
  899. */
  900. _buildCamera( path ) {
  901. const attrs = this._getAttributes( path );
  902. const projectionToken = attrs[ 'projection' ];
  903. const projection = typeof projectionToken === 'string'
  904. ? projectionToken.toLowerCase()
  905. : USD_CAMERA_DEFAULTS.projection;
  906. const clippingRange = attrs[ 'clippingRange' ] || USD_CAMERA_DEFAULTS.clippingRange;
  907. const near = Math.max(
  908. Number.EPSILON,
  909. this._parseNumber( clippingRange[ 0 ], USD_CAMERA_DEFAULTS.clippingRange[ 0 ] )
  910. );
  911. const far = Math.max(
  912. near + Number.EPSILON,
  913. this._parseNumber( clippingRange[ 1 ], USD_CAMERA_DEFAULTS.clippingRange[ 1 ] )
  914. );
  915. const horizontalAperture = this._parseNumber(
  916. attrs[ 'horizontalAperture' ],
  917. USD_CAMERA_DEFAULTS.horizontalAperture
  918. );
  919. const verticalAperture = this._parseNumber(
  920. attrs[ 'verticalAperture' ],
  921. USD_CAMERA_DEFAULTS.verticalAperture
  922. );
  923. const horizontalApertureOffset = this._parseNumber(
  924. attrs[ 'horizontalApertureOffset' ],
  925. USD_CAMERA_DEFAULTS.horizontalApertureOffset
  926. );
  927. const verticalApertureOffset = this._parseNumber(
  928. attrs[ 'verticalApertureOffset' ],
  929. USD_CAMERA_DEFAULTS.verticalApertureOffset
  930. );
  931. const focalLength = this._parseNumber( attrs[ 'focalLength' ], USD_CAMERA_DEFAULTS.focalLength );
  932. const focusDistance = this._parseNumber( attrs[ 'focusDistance' ], USD_CAMERA_DEFAULTS.focusDistance );
  933. const fStop = this._parseNumber( attrs[ 'fStop' ], USD_CAMERA_DEFAULTS.fStop );
  934. let camera;
  935. if ( projection === 'orthographic' ) {
  936. // USD orthographic apertures are in tenths of a world unit.
  937. const width = horizontalAperture / 10;
  938. const height = verticalAperture / 10;
  939. const offsetX = horizontalApertureOffset / 10;
  940. const offsetY = verticalApertureOffset / 10;
  941. camera = new OrthographicCamera(
  942. offsetX - width * 0.5,
  943. offsetX + width * 0.5,
  944. offsetY + height * 0.5,
  945. offsetY - height * 0.5,
  946. near,
  947. far
  948. );
  949. } else {
  950. const safeVerticalAperture = Math.max( Number.EPSILON, verticalAperture );
  951. const safeFocalLength = Math.max( Number.EPSILON, focalLength );
  952. const aspect = horizontalAperture / safeVerticalAperture;
  953. const fov = 2 * Math.atan( safeVerticalAperture / ( 2 * safeFocalLength ) ) * 180 / Math.PI;
  954. camera = new PerspectiveCamera( fov, aspect, near, far );
  955. camera.filmGauge = Math.max( horizontalAperture, verticalAperture );
  956. camera.filmOffset = horizontalApertureOffset;
  957. camera.focus = focusDistance;
  958. camera.setFocalLength( safeFocalLength );
  959. if ( verticalApertureOffset !== 0 ) {
  960. // Three.js supports only horizontal film offset directly.
  961. camera.userData.verticalApertureOffset = verticalApertureOffset;
  962. }
  963. }
  964. camera.userData.fStop = fStop;
  965. camera.userData.usdProjection = projection;
  966. return camera;
  967. }
  968. /**
  969. * Build a light from a UsdLux light spec.
  970. */
  971. _buildLight( path, typeName ) {
  972. const attrs = this._getAttributes( path );
  973. const intensity = this._parseNumber( attrs[ 'inputs:intensity' ], 1 );
  974. const baseColor = attrs[ 'inputs:color' ] || [ 1, 1, 1 ];
  975. const enableColorTemperature = attrs[ 'inputs:enableColorTemperature' ] === true;
  976. const colorTemperature = this._parseNumber( attrs[ 'inputs:colorTemperature' ], 6500 );
  977. const color = new Color( baseColor[ 0 ], baseColor[ 1 ], baseColor[ 2 ] );
  978. if ( enableColorTemperature ) {
  979. const temp = this._colorTemperature( colorTemperature );
  980. color.multiply( temp );
  981. }
  982. let light;
  983. switch ( typeName ) {
  984. case 'DistantLight':
  985. light = new DirectionalLight( color, intensity );
  986. break;
  987. case 'SphereLight': {
  988. const coneAngle = this._parseNumber( attrs[ 'shaping:cone:angle' ], 0 );
  989. if ( coneAngle > 0 ) {
  990. const angle = coneAngle * Math.PI / 180;
  991. const softness = this._parseNumber( attrs[ 'shaping:cone:softness' ], 0 );
  992. light = new SpotLight( color, intensity, 0, angle, softness );
  993. } else {
  994. light = new PointLight( color, intensity );
  995. }
  996. break;
  997. }
  998. case 'RectLight': {
  999. const width = this._parseNumber( attrs[ 'inputs:width' ], 1 );
  1000. const height = this._parseNumber( attrs[ 'inputs:height' ], 1 );
  1001. light = new RectAreaLight( color, intensity, width, height );
  1002. break;
  1003. }
  1004. case 'DiskLight': {
  1005. const radius = this._parseNumber( attrs[ 'inputs:radius' ], 0.5 );
  1006. const side = radius * 2;
  1007. light = new RectAreaLight( color, intensity, side, side );
  1008. break;
  1009. }
  1010. }
  1011. return light;
  1012. }
  1013. /**
  1014. * Convert a color temperature in Kelvin to an RGB Color.
  1015. * Based on Tanner Helland's algorithm.
  1016. */
  1017. _colorTemperature( kelvin ) {
  1018. const temp = kelvin / 100;
  1019. let r, g, b;
  1020. if ( temp <= 66 ) {
  1021. r = 1;
  1022. g = 0.39008157876901960784 * Math.log( temp ) - 0.63184144378862745098;
  1023. } else {
  1024. r = 1.29293618606274509804 * Math.pow( temp - 60, - 0.1332047592 );
  1025. g = 1.12989086089529411765 * Math.pow( temp - 60, - 0.0755148492 );
  1026. }
  1027. if ( temp >= 66 ) {
  1028. b = 1;
  1029. } else if ( temp <= 19 ) {
  1030. b = 0;
  1031. } else {
  1032. b = 0.54320678911019607843 * Math.log( temp - 10 ) - 1.19625408914;
  1033. }
  1034. return new Color(
  1035. Math.min( Math.max( r, 0 ), 1 ),
  1036. Math.min( Math.max( g, 0 ), 1 ),
  1037. Math.min( Math.max( b, 0 ), 1 )
  1038. );
  1039. }
  1040. _parseNumber( value, fallback ) {
  1041. const n = Number( value );
  1042. return Number.isFinite( n ) ? n : fallback;
  1043. }
  1044. _getGeomSubsets( meshPath ) {
  1045. const subsets = [];
  1046. const subsetPaths = this.geomSubsetsByMeshPath.get( meshPath );
  1047. if ( ! subsetPaths ) return subsets;
  1048. for ( const p of subsetPaths ) {
  1049. const attrs = this._getAttributes( p );
  1050. const indices = attrs[ 'indices' ];
  1051. if ( ! indices || indices.length === 0 ) continue;
  1052. // Get material binding - check direct path and variant paths
  1053. const materialPath = this._getMaterialBindingTarget( p );
  1054. subsets.push( {
  1055. name: p.split( '/' ).pop(),
  1056. indices: indices,
  1057. materialPath: materialPath
  1058. } );
  1059. }
  1060. return subsets;
  1061. }
  1062. /**
  1063. * Get material binding target path, checking variant paths if needed.
  1064. */
  1065. _getMaterialBindingTarget( primPath ) {
  1066. const attrName = 'material:binding';
  1067. // First check direct path
  1068. const directPath = primPath + '.' + attrName;
  1069. const directSpec = this.specsByPath[ directPath ];
  1070. if ( directSpec?.fields?.targetPaths?.length > 0 ) {
  1071. return directSpec.fields.targetPaths[ 0 ];
  1072. }
  1073. // Check variant paths at ancestor levels
  1074. const parts = primPath.split( '/' );
  1075. for ( let i = 1; i < parts.length; i ++ ) {
  1076. const ancestorPath = parts.slice( 0, i + 1 ).join( '/' );
  1077. const relativePath = parts.slice( i + 1 ).join( '/' );
  1078. const variantPaths = this._getVariantPaths( ancestorPath );
  1079. for ( const vp of variantPaths ) {
  1080. const overridePath = relativePath ? vp + '/' + relativePath + '.' + attrName : vp + '.' + attrName;
  1081. const overrideSpec = this.specsByPath[ overridePath ];
  1082. if ( overrideSpec?.fields?.targetPaths?.length > 0 ) {
  1083. return overrideSpec.fields.targetPaths[ 0 ];
  1084. }
  1085. }
  1086. }
  1087. return null;
  1088. }
  1089. _buildGeometry( path, fields, hasSkinning = false ) {
  1090. const geometry = new BufferGeometry();
  1091. const points = fields[ 'points' ];
  1092. if ( ! points || points.length === 0 ) return geometry;
  1093. const faceVertexIndices = fields[ 'faceVertexIndices' ];
  1094. const faceVertexCounts = fields[ 'faceVertexCounts' ];
  1095. // Parse polygon holes (Arnold format: [holeFaceIdx, parentFaceIdx, ...])
  1096. const polygonHoles = fields[ 'primvars:arnold:polygon_holes' ];
  1097. const holeMap = this._buildHoleMap( polygonHoles );
  1098. // Compute triangulation pattern once using actual vertex positions
  1099. // This pattern will be reused for normals, UVs, etc.
  1100. let indices = faceVertexIndices;
  1101. let triPattern = null;
  1102. if ( faceVertexCounts && faceVertexCounts.length > 0 ) {
  1103. const result = this._triangulateIndicesWithPattern( faceVertexIndices, faceVertexCounts, points, holeMap );
  1104. indices = result.indices;
  1105. triPattern = result.pattern;
  1106. }
  1107. let positions = points;
  1108. if ( indices && indices.length > 0 ) {
  1109. positions = this._expandAttribute( points, indices, 3 );
  1110. }
  1111. geometry.setAttribute( 'position', new BufferAttribute( new Float32Array( positions ), 3 ) );
  1112. const normals = fields[ 'normals' ] || fields[ 'primvars:normals' ];
  1113. const normalIndicesRaw = fields[ 'normals:indices' ] || fields[ 'primvars:normals:indices' ];
  1114. if ( normals && normals.length > 0 ) {
  1115. let normalData = normals;
  1116. if ( normalIndicesRaw && normalIndicesRaw.length > 0 && triPattern ) {
  1117. // Indexed normals - apply triangulation pattern to indices
  1118. const triangulatedNormalIndices = this._applyTriangulationPattern( normalIndicesRaw, triPattern );
  1119. normalData = this._expandAttribute( normals, triangulatedNormalIndices, 3 );
  1120. } else if ( normals.length === points.length ) {
  1121. // Per-vertex normals
  1122. if ( indices && indices.length > 0 ) {
  1123. normalData = this._expandAttribute( normals, indices, 3 );
  1124. }
  1125. } else if ( triPattern ) {
  1126. // Per-face-vertex normals (no separate indices) - use same triangulation pattern
  1127. const normalIndices = this._applyTriangulationPattern(
  1128. Array.from( { length: normals.length / 3 }, ( _, i ) => i ),
  1129. triPattern
  1130. );
  1131. normalData = this._expandAttribute( normals, normalIndices, 3 );
  1132. }
  1133. geometry.setAttribute( 'normal', new BufferAttribute( new Float32Array( normalData ), 3 ) );
  1134. } else {
  1135. // Compute vertex normals from the original indexed topology where
  1136. // vertices are shared, then expand them like positions.
  1137. const vertexNormals = this._computeVertexNormals( points, indices );
  1138. geometry.setAttribute( 'normal', new BufferAttribute( new Float32Array(
  1139. this._expandAttribute( vertexNormals, indices, 3 )
  1140. ), 3 ) );
  1141. }
  1142. const { uvs, uvIndices } = this._findUVPrimvar( fields );
  1143. const numFaceVertices = faceVertexIndices ? faceVertexIndices.length : 0;
  1144. if ( uvs && uvs.length > 0 ) {
  1145. let uvData = uvs;
  1146. if ( uvIndices && uvIndices.length > 0 && triPattern ) {
  1147. const triangulatedUvIndices = this._applyTriangulationPattern( uvIndices, triPattern );
  1148. uvData = this._expandAttribute( uvs, triangulatedUvIndices, 2 );
  1149. } else if ( indices && uvs.length / 2 === points.length / 3 ) {
  1150. uvData = this._expandAttribute( uvs, indices, 2 );
  1151. } else if ( triPattern && uvs.length / 2 === numFaceVertices ) {
  1152. // Per-face-vertex UVs (faceVarying, no separate indices)
  1153. const uvIndicesFromPattern = this._applyTriangulationPattern(
  1154. Array.from( { length: numFaceVertices }, ( _, i ) => i ),
  1155. triPattern
  1156. );
  1157. uvData = this._expandAttribute( uvs, uvIndicesFromPattern, 2 );
  1158. }
  1159. geometry.setAttribute( 'uv', new BufferAttribute( new Float32Array( uvData ), 2 ) );
  1160. }
  1161. // Second UV set (st1) for lightmaps/AO
  1162. const { uvs2, uv2Indices } = this._findUV2Primvar( fields );
  1163. if ( uvs2 && uvs2.length > 0 ) {
  1164. let uv2Data = uvs2;
  1165. if ( uv2Indices && uv2Indices.length > 0 && triPattern ) {
  1166. const triangulatedUv2Indices = this._applyTriangulationPattern( uv2Indices, triPattern );
  1167. uv2Data = this._expandAttribute( uvs2, triangulatedUv2Indices, 2 );
  1168. } else if ( indices && uvs2.length / 2 === points.length / 3 ) {
  1169. uv2Data = this._expandAttribute( uvs2, indices, 2 );
  1170. } else if ( triPattern && uvs2.length / 2 === numFaceVertices ) {
  1171. // Per-face-vertex UV2 (faceVarying, no separate indices)
  1172. const uv2IndicesFromPattern = this._applyTriangulationPattern(
  1173. Array.from( { length: numFaceVertices }, ( _, i ) => i ),
  1174. triPattern
  1175. );
  1176. uv2Data = this._expandAttribute( uvs2, uv2IndicesFromPattern, 2 );
  1177. }
  1178. geometry.setAttribute( 'uv1', new BufferAttribute( new Float32Array( uv2Data ), 2 ) );
  1179. }
  1180. // Add skinning attributes
  1181. if ( hasSkinning ) {
  1182. const jointIndices = fields[ 'primvars:skel:jointIndices' ];
  1183. const jointWeights = fields[ 'primvars:skel:jointWeights' ];
  1184. const elementSize = fields[ 'primvars:skel:jointIndices:elementSize' ] || 4;
  1185. if ( jointIndices && jointWeights ) {
  1186. const numVertices = positions.length / 3;
  1187. let skinIndexData, skinWeightData;
  1188. if ( indices && indices.length > 0 ) {
  1189. skinIndexData = this._expandAttribute( jointIndices, indices, elementSize );
  1190. skinWeightData = this._expandAttribute( jointWeights, indices, elementSize );
  1191. } else {
  1192. skinIndexData = jointIndices;
  1193. skinWeightData = jointWeights;
  1194. }
  1195. const skinIndices = new Uint16Array( numVertices * 4 );
  1196. const skinWeights = new Float32Array( numVertices * 4 );
  1197. this._selectTopWeights( skinIndexData, skinWeightData, elementSize, numVertices, skinIndices, skinWeights );
  1198. geometry.setAttribute( 'skinIndex', new BufferAttribute( skinIndices, 4 ) );
  1199. geometry.setAttribute( 'skinWeight', new BufferAttribute( skinWeights, 4 ) );
  1200. }
  1201. }
  1202. return geometry;
  1203. }
  1204. _buildGeometryWithSubsets( fields, geomSubsets, hasSkinning = false ) {
  1205. const geometry = new BufferGeometry();
  1206. const points = fields[ 'points' ];
  1207. if ( ! points || points.length === 0 ) return geometry;
  1208. const faceVertexIndices = fields[ 'faceVertexIndices' ];
  1209. const faceVertexCounts = fields[ 'faceVertexCounts' ];
  1210. if ( ! faceVertexCounts || faceVertexCounts.length === 0 ) return geometry;
  1211. const polygonHoles = fields[ 'primvars:arnold:polygon_holes' ];
  1212. const holeMap = this._buildHoleMap( polygonHoles );
  1213. const holeFaces = holeMap.holeFaces;
  1214. const parentToHoles = holeMap.parentToHoles;
  1215. const { uvs, uvIndices } = this._findUVPrimvar( fields );
  1216. const { uvs2, uv2Indices } = this._findUV2Primvar( fields );
  1217. const normals = fields[ 'normals' ] || fields[ 'primvars:normals' ];
  1218. const normalIndicesRaw = fields[ 'normals:indices' ] || fields[ 'primvars:normals:indices' ];
  1219. const jointIndices = hasSkinning ? fields[ 'primvars:skel:jointIndices' ] : null;
  1220. const jointWeights = hasSkinning ? fields[ 'primvars:skel:jointWeights' ] : null;
  1221. const elementSize = fields[ 'primvars:skel:jointIndices:elementSize' ] || 4;
  1222. // Build face-to-triangle mapping (accounting for holes)
  1223. const faceTriangleOffset = [];
  1224. let triangleCount = 0;
  1225. for ( let i = 0; i < faceVertexCounts.length; i ++ ) {
  1226. faceTriangleOffset.push( triangleCount );
  1227. // Skip hole faces - they're triangulated with their parent
  1228. if ( holeFaces.has( i ) ) continue;
  1229. const count = faceVertexCounts[ i ];
  1230. const holes = parentToHoles.get( i );
  1231. if ( holes && holes.length > 0 ) {
  1232. // For faces with holes, count triangles based on total vertices
  1233. // Earcut produces (total_vertices - 2) triangles for any polygon including holes
  1234. let totalVerts = count;
  1235. for ( const holeIdx of holes ) {
  1236. totalVerts += faceVertexCounts[ holeIdx ];
  1237. }
  1238. triangleCount += totalVerts - 2;
  1239. } else if ( count >= 3 ) {
  1240. triangleCount += count - 2;
  1241. }
  1242. }
  1243. const triangleToSubset = new Int32Array( triangleCount ).fill( - 1 );
  1244. for ( let si = 0; si < geomSubsets.length; si ++ ) {
  1245. const subset = geomSubsets[ si ];
  1246. for ( let i = 0; i < subset.indices.length; i ++ ) {
  1247. const faceIdx = subset.indices[ i ];
  1248. if ( faceIdx >= faceVertexCounts.length ) continue;
  1249. const triStart = faceTriangleOffset[ faceIdx ];
  1250. const triCount = faceVertexCounts[ faceIdx ] - 2;
  1251. for ( let t = 0; t < triCount; t ++ ) {
  1252. triangleToSubset[ triStart + t ] = si;
  1253. }
  1254. }
  1255. }
  1256. // Sort triangles by subset
  1257. const sortedTriangles = [];
  1258. for ( let tri = 0; tri < triangleCount; tri ++ ) {
  1259. sortedTriangles.push( { original: tri, subset: triangleToSubset[ tri ] } );
  1260. }
  1261. sortedTriangles.sort( ( a, b ) => a.subset - b.subset );
  1262. const groups = [];
  1263. let currentSubset = sortedTriangles.length > 0 ? sortedTriangles[ 0 ].subset : - 1;
  1264. let groupStart = 0;
  1265. for ( let i = 0; i < sortedTriangles.length; i ++ ) {
  1266. if ( sortedTriangles[ i ].subset !== currentSubset ) {
  1267. if ( currentSubset >= 0 ) {
  1268. groups.push( {
  1269. start: groupStart * 3,
  1270. count: ( i - groupStart ) * 3,
  1271. materialIndex: currentSubset
  1272. } );
  1273. }
  1274. currentSubset = sortedTriangles[ i ].subset;
  1275. groupStart = i;
  1276. }
  1277. }
  1278. if ( currentSubset >= 0 && sortedTriangles.length > groupStart ) {
  1279. groups.push( {
  1280. start: groupStart * 3,
  1281. count: ( sortedTriangles.length - groupStart ) * 3,
  1282. materialIndex: currentSubset
  1283. } );
  1284. }
  1285. for ( const group of groups ) {
  1286. geometry.addGroup( group.start, group.count, group.materialIndex );
  1287. }
  1288. // Triangulate original data using consistent pattern
  1289. const { indices: origIndices, pattern: triPattern } = this._triangulateIndicesWithPattern( faceVertexIndices, faceVertexCounts, points, holeMap );
  1290. const numFaceVertices = faceVertexCounts.reduce( ( a, b ) => a + b, 0 );
  1291. const faceVaryingIdentity = ( uvs && ! uvIndices && uvs.length / 2 === numFaceVertices ) ||
  1292. ( uvs2 && ! uv2Indices && uvs2.length / 2 === numFaceVertices )
  1293. ? this._applyTriangulationPattern( Array.from( { length: numFaceVertices }, ( _, i ) => i ), triPattern )
  1294. : null;
  1295. const origUvIndices = uvIndices
  1296. ? this._applyTriangulationPattern( uvIndices, triPattern )
  1297. : ( uvs && uvs.length / 2 === numFaceVertices ? faceVaryingIdentity : null );
  1298. const origUv2Indices = uv2Indices
  1299. ? this._applyTriangulationPattern( uv2Indices, triPattern )
  1300. : ( uvs2 && uvs2.length / 2 === numFaceVertices ? faceVaryingIdentity : null );
  1301. const hasIndexedNormals = normals && normalIndicesRaw && normalIndicesRaw.length > 0;
  1302. const hasFaceVaryingNormals = normals && normals.length / 3 === numFaceVertices;
  1303. const origNormalIndices = hasIndexedNormals
  1304. ? this._applyTriangulationPattern( normalIndicesRaw, triPattern )
  1305. : ( hasFaceVaryingNormals
  1306. ? this._applyTriangulationPattern( Array.from( { length: numFaceVertices }, ( _, i ) => i ), triPattern )
  1307. : null );
  1308. // When no normals are provided, compute vertex normals from
  1309. // the indexed topology so that shared vertices produce averaged normals.
  1310. const vertexNormals = ( ! normals && origIndices.length > 0 )
  1311. ? this._computeVertexNormals( points, origIndices )
  1312. : null;
  1313. // Build reordered vertex data
  1314. const vertexCount = triangleCount * 3;
  1315. const positions = new Float32Array( vertexCount * 3 );
  1316. const uvData = uvs ? new Float32Array( vertexCount * 2 ) : null;
  1317. const uv1Data = uvs2 ? new Float32Array( vertexCount * 2 ) : null;
  1318. const normalData = ( normals || vertexNormals ) ? new Float32Array( vertexCount * 3 ) : null;
  1319. const skinSrcIndices = jointIndices ? new Uint16Array( vertexCount * elementSize ) : null;
  1320. const skinSrcWeights = jointWeights ? new Float32Array( vertexCount * elementSize ) : null;
  1321. for ( let i = 0; i < sortedTriangles.length; i ++ ) {
  1322. const origTri = sortedTriangles[ i ].original;
  1323. for ( let v = 0; v < 3; v ++ ) {
  1324. const origIdx = origTri * 3 + v;
  1325. const newIdx = i * 3 + v;
  1326. const pointIdx = origIndices[ origIdx ];
  1327. positions[ newIdx * 3 ] = points[ pointIdx * 3 ];
  1328. positions[ newIdx * 3 + 1 ] = points[ pointIdx * 3 + 1 ];
  1329. positions[ newIdx * 3 + 2 ] = points[ pointIdx * 3 + 2 ];
  1330. if ( uvData && uvs ) {
  1331. if ( origUvIndices ) {
  1332. const uvIdx = origUvIndices[ origIdx ];
  1333. uvData[ newIdx * 2 ] = uvs[ uvIdx * 2 ];
  1334. uvData[ newIdx * 2 + 1 ] = uvs[ uvIdx * 2 + 1 ];
  1335. } else if ( uvs.length / 2 === points.length / 3 ) {
  1336. uvData[ newIdx * 2 ] = uvs[ pointIdx * 2 ];
  1337. uvData[ newIdx * 2 + 1 ] = uvs[ pointIdx * 2 + 1 ];
  1338. }
  1339. }
  1340. if ( uv1Data && uvs2 ) {
  1341. if ( origUv2Indices ) {
  1342. const uv2Idx = origUv2Indices[ origIdx ];
  1343. uv1Data[ newIdx * 2 ] = uvs2[ uv2Idx * 2 ];
  1344. uv1Data[ newIdx * 2 + 1 ] = uvs2[ uv2Idx * 2 + 1 ];
  1345. } else if ( uvs2.length / 2 === points.length / 3 ) {
  1346. uv1Data[ newIdx * 2 ] = uvs2[ pointIdx * 2 ];
  1347. uv1Data[ newIdx * 2 + 1 ] = uvs2[ pointIdx * 2 + 1 ];
  1348. }
  1349. }
  1350. if ( normalData ) {
  1351. if ( normals && origNormalIndices ) {
  1352. const normalIdx = origNormalIndices[ origIdx ];
  1353. normalData[ newIdx * 3 ] = normals[ normalIdx * 3 ];
  1354. normalData[ newIdx * 3 + 1 ] = normals[ normalIdx * 3 + 1 ];
  1355. normalData[ newIdx * 3 + 2 ] = normals[ normalIdx * 3 + 2 ];
  1356. } else if ( normals && normals.length === points.length ) {
  1357. normalData[ newIdx * 3 ] = normals[ pointIdx * 3 ];
  1358. normalData[ newIdx * 3 + 1 ] = normals[ pointIdx * 3 + 1 ];
  1359. normalData[ newIdx * 3 + 2 ] = normals[ pointIdx * 3 + 2 ];
  1360. } else if ( vertexNormals ) {
  1361. normalData[ newIdx * 3 ] = vertexNormals[ pointIdx * 3 ];
  1362. normalData[ newIdx * 3 + 1 ] = vertexNormals[ pointIdx * 3 + 1 ];
  1363. normalData[ newIdx * 3 + 2 ] = vertexNormals[ pointIdx * 3 + 2 ];
  1364. }
  1365. }
  1366. if ( skinSrcIndices && skinSrcWeights && jointIndices && jointWeights ) {
  1367. for ( let j = 0; j < elementSize; j ++ ) {
  1368. skinSrcIndices[ newIdx * elementSize + j ] = jointIndices[ pointIdx * elementSize + j ] || 0;
  1369. skinSrcWeights[ newIdx * elementSize + j ] = jointWeights[ pointIdx * elementSize + j ] || 0;
  1370. }
  1371. }
  1372. }
  1373. }
  1374. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  1375. if ( uvData ) {
  1376. geometry.setAttribute( 'uv', new BufferAttribute( uvData, 2 ) );
  1377. }
  1378. if ( uv1Data ) {
  1379. geometry.setAttribute( 'uv1', new BufferAttribute( uv1Data, 2 ) );
  1380. }
  1381. geometry.setAttribute( 'normal', new BufferAttribute( normalData, 3 ) );
  1382. if ( skinSrcIndices && skinSrcWeights ) {
  1383. const skinIndexData = new Uint16Array( vertexCount * 4 );
  1384. const skinWeightData = new Float32Array( vertexCount * 4 );
  1385. this._selectTopWeights( skinSrcIndices, skinSrcWeights, elementSize, vertexCount, skinIndexData, skinWeightData );
  1386. geometry.setAttribute( 'skinIndex', new BufferAttribute( skinIndexData, 4 ) );
  1387. geometry.setAttribute( 'skinWeight', new BufferAttribute( skinWeightData, 4 ) );
  1388. }
  1389. return geometry;
  1390. }
  1391. _selectTopWeights( srcIndices, srcWeights, elementSize, numVertices, dstIndices, dstWeights ) {
  1392. if ( elementSize <= 4 ) {
  1393. for ( let i = 0; i < numVertices; i ++ ) {
  1394. for ( let j = 0; j < 4; j ++ ) {
  1395. if ( j < elementSize ) {
  1396. dstIndices[ i * 4 + j ] = srcIndices[ i * elementSize + j ] || 0;
  1397. dstWeights[ i * 4 + j ] = srcWeights[ i * elementSize + j ] || 0;
  1398. } else {
  1399. dstIndices[ i * 4 + j ] = 0;
  1400. dstWeights[ i * 4 + j ] = 0;
  1401. }
  1402. }
  1403. }
  1404. return;
  1405. }
  1406. // When elementSize > 4, find the 4 largest weights per vertex
  1407. // using a partial selection sort (4 iterations of O(elementSize)).
  1408. const order = new Uint32Array( elementSize );
  1409. for ( let i = 0; i < numVertices; i ++ ) {
  1410. const base = i * elementSize;
  1411. for ( let j = 0; j < elementSize; j ++ ) order[ j ] = j;
  1412. for ( let k = 0; k < 4; k ++ ) {
  1413. let maxIdx = k;
  1414. let maxW = srcWeights[ base + order[ k ] ] || 0;
  1415. for ( let j = k + 1; j < elementSize; j ++ ) {
  1416. const w = srcWeights[ base + order[ j ] ] || 0;
  1417. if ( w > maxW ) {
  1418. maxW = w;
  1419. maxIdx = j;
  1420. }
  1421. }
  1422. if ( maxIdx !== k ) {
  1423. const tmp = order[ k ];
  1424. order[ k ] = order[ maxIdx ];
  1425. order[ maxIdx ] = tmp;
  1426. }
  1427. }
  1428. let total = 0;
  1429. for ( let j = 0; j < 4; j ++ ) {
  1430. total += srcWeights[ base + order[ j ] ] || 0;
  1431. }
  1432. for ( let j = 0; j < 4; j ++ ) {
  1433. const s = order[ j ];
  1434. if ( total > 0 ) {
  1435. dstIndices[ i * 4 + j ] = srcIndices[ base + s ] || 0;
  1436. dstWeights[ i * 4 + j ] = ( srcWeights[ base + s ] || 0 ) / total;
  1437. } else {
  1438. dstIndices[ i * 4 + j ] = 0;
  1439. dstWeights[ i * 4 + j ] = 0;
  1440. }
  1441. }
  1442. }
  1443. }
  1444. _findUVPrimvar( fields ) {
  1445. for ( const key in fields ) {
  1446. if ( ! key.startsWith( 'primvars:' ) ) continue;
  1447. if ( key.endsWith( ':typeName' ) || key.endsWith( ':elementSize' ) || key.endsWith( ':indices' ) ) continue;
  1448. if ( key.includes( 'skel:' ) ) continue;
  1449. const typeName = fields[ key + ':typeName' ];
  1450. if ( typeName && typeName.includes( 'texCoord' ) ) {
  1451. return {
  1452. uvs: fields[ key ],
  1453. uvIndices: fields[ key + ':indices' ]
  1454. };
  1455. }
  1456. }
  1457. const uvs = fields[ 'primvars:st' ] || fields[ 'primvars:UVMap' ];
  1458. const uvIndices = fields[ 'primvars:st:indices' ];
  1459. return { uvs, uvIndices };
  1460. }
  1461. _findUV2Primvar( fields ) {
  1462. const uvs2 = fields[ 'primvars:st1' ];
  1463. const uv2Indices = fields[ 'primvars:st1:indices' ];
  1464. return { uvs2, uv2Indices };
  1465. }
  1466. _buildHoleMap( polygonHoles ) {
  1467. // polygonHoles is in Arnold format: [holeFaceIdx, parentFaceIdx, holeFaceIdx, parentFaceIdx, ...]
  1468. // Returns a map: parentFaceIdx -> [holeFaceIdx1, holeFaceIdx2, ...]
  1469. // Also returns a set of hole face indices to skip during triangulation
  1470. if ( ! polygonHoles || polygonHoles.length === 0 ) {
  1471. return { parentToHoles: new Map(), holeFaces: new Set() };
  1472. }
  1473. const parentToHoles = new Map();
  1474. const holeFaces = new Set();
  1475. for ( let i = 0; i < polygonHoles.length; i += 2 ) {
  1476. const holeFaceIdx = polygonHoles[ i ];
  1477. const parentFaceIdx = polygonHoles[ i + 1 ];
  1478. holeFaces.add( holeFaceIdx );
  1479. if ( ! parentToHoles.has( parentFaceIdx ) ) {
  1480. parentToHoles.set( parentFaceIdx, [] );
  1481. }
  1482. parentToHoles.get( parentFaceIdx ).push( holeFaceIdx );
  1483. }
  1484. return { parentToHoles, holeFaces };
  1485. }
  1486. _triangulateIndicesWithPattern( indices, counts, points = null, holeMap = null ) {
  1487. const triangulated = [];
  1488. const pattern = []; // Stores face-local indices for each triangle vertex
  1489. // Build face offset lookup for accessing hole face data
  1490. const faceOffsets = [];
  1491. let offsetAccum = 0;
  1492. for ( let i = 0; i < counts.length; i ++ ) {
  1493. faceOffsets.push( offsetAccum );
  1494. offsetAccum += counts[ i ];
  1495. }
  1496. const parentToHoles = holeMap?.parentToHoles || new Map();
  1497. const holeFaces = holeMap?.holeFaces || new Set();
  1498. let offset = 0;
  1499. for ( let i = 0; i < counts.length; i ++ ) {
  1500. const count = counts[ i ];
  1501. // Skip faces that are holes - they will be triangulated with their parent
  1502. if ( holeFaces.has( i ) ) {
  1503. offset += count;
  1504. continue;
  1505. }
  1506. // Check if this face has holes
  1507. const holes = parentToHoles.get( i );
  1508. if ( holes && holes.length > 0 && points && points.length > 0 ) {
  1509. // Triangulate face with holes using vertex -> face-vertex mapping
  1510. const vertexToFaceVertex = new Map();
  1511. const faceIndices = [];
  1512. for ( let j = 0; j < count; j ++ ) {
  1513. const vertIdx = indices[ offset + j ];
  1514. faceIndices.push( vertIdx );
  1515. vertexToFaceVertex.set( vertIdx, offset + j );
  1516. }
  1517. const holeContours = [];
  1518. for ( const holeFaceIdx of holes ) {
  1519. const holeOffset = faceOffsets[ holeFaceIdx ];
  1520. const holeCount = counts[ holeFaceIdx ];
  1521. const holeIndices = [];
  1522. for ( let j = 0; j < holeCount; j ++ ) {
  1523. const vertIdx = indices[ holeOffset + j ];
  1524. holeIndices.push( vertIdx );
  1525. vertexToFaceVertex.set( vertIdx, holeOffset + j );
  1526. }
  1527. holeContours.push( holeIndices );
  1528. }
  1529. const triangles = this._triangulateNGonWithHoles( faceIndices, holeContours, points );
  1530. for ( const tri of triangles ) {
  1531. triangulated.push( tri[ 0 ], tri[ 1 ], tri[ 2 ] );
  1532. pattern.push(
  1533. vertexToFaceVertex.get( tri[ 0 ] ),
  1534. vertexToFaceVertex.get( tri[ 1 ] ),
  1535. vertexToFaceVertex.get( tri[ 2 ] )
  1536. );
  1537. }
  1538. } else if ( count === 3 ) {
  1539. triangulated.push(
  1540. indices[ offset ],
  1541. indices[ offset + 1 ],
  1542. indices[ offset + 2 ]
  1543. );
  1544. pattern.push( offset, offset + 1, offset + 2 );
  1545. } else if ( count === 4 ) {
  1546. triangulated.push(
  1547. indices[ offset ],
  1548. indices[ offset + 1 ],
  1549. indices[ offset + 2 ],
  1550. indices[ offset ],
  1551. indices[ offset + 2 ],
  1552. indices[ offset + 3 ]
  1553. );
  1554. pattern.push(
  1555. offset, offset + 1, offset + 2,
  1556. offset, offset + 2, offset + 3
  1557. );
  1558. } else if ( count > 4 ) {
  1559. // Use ear-clipping for complex n-gons if we have vertex positions
  1560. if ( points && points.length > 0 ) {
  1561. const faceIndices = [];
  1562. for ( let j = 0; j < count; j ++ ) {
  1563. faceIndices.push( indices[ offset + j ] );
  1564. }
  1565. const triangles = this._triangulateNGon( faceIndices, points );
  1566. for ( const tri of triangles ) {
  1567. triangulated.push( tri[ 0 ], tri[ 1 ], tri[ 2 ] );
  1568. // Find local indices within the face
  1569. pattern.push(
  1570. offset + faceIndices.indexOf( tri[ 0 ] ),
  1571. offset + faceIndices.indexOf( tri[ 1 ] ),
  1572. offset + faceIndices.indexOf( tri[ 2 ] )
  1573. );
  1574. }
  1575. } else {
  1576. // Fallback to fan triangulation
  1577. for ( let j = 1; j < count - 1; j ++ ) {
  1578. triangulated.push(
  1579. indices[ offset ],
  1580. indices[ offset + j ],
  1581. indices[ offset + j + 1 ]
  1582. );
  1583. pattern.push( offset, offset + j, offset + j + 1 );
  1584. }
  1585. }
  1586. }
  1587. offset += count;
  1588. }
  1589. return { indices: triangulated, pattern };
  1590. }
  1591. _applyTriangulationPattern( indices, pattern ) {
  1592. const result = [];
  1593. for ( let i = 0; i < pattern.length; i ++ ) {
  1594. result.push( indices[ pattern[ i ] ] );
  1595. }
  1596. return result;
  1597. }
  1598. _triangulateNGon( faceIndices, points ) {
  1599. // Project 3D polygon to 2D for triangulation using Newell's method for normal
  1600. const contour2D = [];
  1601. const contour3D = [];
  1602. for ( const idx of faceIndices ) {
  1603. contour3D.push( new Vector3(
  1604. points[ idx * 3 ],
  1605. points[ idx * 3 + 1 ],
  1606. points[ idx * 3 + 2 ]
  1607. ) );
  1608. }
  1609. // Calculate polygon normal using Newell's method
  1610. const normal = new Vector3();
  1611. for ( let i = 0; i < contour3D.length; i ++ ) {
  1612. const curr = contour3D[ i ];
  1613. const next = contour3D[ ( i + 1 ) % contour3D.length ];
  1614. normal.x += ( curr.y - next.y ) * ( curr.z + next.z );
  1615. normal.y += ( curr.z - next.z ) * ( curr.x + next.x );
  1616. normal.z += ( curr.x - next.x ) * ( curr.y + next.y );
  1617. }
  1618. normal.normalize();
  1619. // Create tangent basis for projection
  1620. const tangent = new Vector3();
  1621. const bitangent = new Vector3();
  1622. if ( Math.abs( normal.y ) > 0.9 ) {
  1623. tangent.set( 1, 0, 0 );
  1624. } else {
  1625. tangent.set( 0, 1, 0 );
  1626. }
  1627. bitangent.crossVectors( normal, tangent ).normalize();
  1628. tangent.crossVectors( bitangent, normal ).normalize();
  1629. // Project to 2D
  1630. for ( const p of contour3D ) {
  1631. contour2D.push( new Vector2( p.dot( tangent ), p.dot( bitangent ) ) );
  1632. }
  1633. // Triangulate using ShapeUtils
  1634. const triangles = ShapeUtils.triangulateShape( contour2D, [] );
  1635. // Map back to original indices
  1636. const result = [];
  1637. for ( const tri of triangles ) {
  1638. result.push( [
  1639. faceIndices[ tri[ 0 ] ],
  1640. faceIndices[ tri[ 1 ] ],
  1641. faceIndices[ tri[ 2 ] ]
  1642. ] );
  1643. }
  1644. return result;
  1645. }
  1646. _triangulateNGonWithHoles( outerIndices, holeContours, points ) {
  1647. // Project 3D polygon with holes to 2D for triangulation
  1648. const outer3D = [];
  1649. for ( const idx of outerIndices ) {
  1650. outer3D.push( new Vector3(
  1651. points[ idx * 3 ],
  1652. points[ idx * 3 + 1 ],
  1653. points[ idx * 3 + 2 ]
  1654. ) );
  1655. }
  1656. // Calculate polygon normal using Newell's method
  1657. const normal = new Vector3();
  1658. for ( let i = 0; i < outer3D.length; i ++ ) {
  1659. const curr = outer3D[ i ];
  1660. const next = outer3D[ ( i + 1 ) % outer3D.length ];
  1661. normal.x += ( curr.y - next.y ) * ( curr.z + next.z );
  1662. normal.y += ( curr.z - next.z ) * ( curr.x + next.x );
  1663. normal.z += ( curr.x - next.x ) * ( curr.y + next.y );
  1664. }
  1665. normal.normalize();
  1666. // Create tangent basis for projection
  1667. const tangent = new Vector3();
  1668. const bitangent = new Vector3();
  1669. if ( Math.abs( normal.y ) > 0.9 ) {
  1670. tangent.set( 1, 0, 0 );
  1671. } else {
  1672. tangent.set( 0, 1, 0 );
  1673. }
  1674. bitangent.crossVectors( normal, tangent ).normalize();
  1675. tangent.crossVectors( bitangent, normal ).normalize();
  1676. // Project outer contour to 2D
  1677. const outer2D = [];
  1678. for ( const p of outer3D ) {
  1679. outer2D.push( new Vector2( p.dot( tangent ), p.dot( bitangent ) ) );
  1680. }
  1681. // Project hole contours to 2D
  1682. const holes2D = [];
  1683. for ( const holeIndices of holeContours ) {
  1684. const hole2D = [];
  1685. for ( const idx of holeIndices ) {
  1686. const p = new Vector3(
  1687. points[ idx * 3 ],
  1688. points[ idx * 3 + 1 ],
  1689. points[ idx * 3 + 2 ]
  1690. );
  1691. hole2D.push( new Vector2( p.dot( tangent ), p.dot( bitangent ) ) );
  1692. }
  1693. holes2D.push( hole2D );
  1694. }
  1695. // Build combined index array: outer contour followed by all holes
  1696. const allIndices = [ ...outerIndices ];
  1697. for ( const holeIndices of holeContours ) {
  1698. allIndices.push( ...holeIndices );
  1699. }
  1700. // Triangulate using ShapeUtils with holes
  1701. const triangles = ShapeUtils.triangulateShape( outer2D, holes2D );
  1702. // Map back to original vertex indices
  1703. const result = [];
  1704. for ( const tri of triangles ) {
  1705. result.push( [
  1706. allIndices[ tri[ 0 ] ],
  1707. allIndices[ tri[ 1 ] ],
  1708. allIndices[ tri[ 2 ] ]
  1709. ] );
  1710. }
  1711. return result;
  1712. }
  1713. _triangulateIndices( indices, counts ) {
  1714. const triangulated = [];
  1715. let offset = 0;
  1716. for ( let i = 0; i < counts.length; i ++ ) {
  1717. const count = counts[ i ];
  1718. if ( count === 3 ) {
  1719. triangulated.push(
  1720. indices[ offset ],
  1721. indices[ offset + 1 ],
  1722. indices[ offset + 2 ]
  1723. );
  1724. } else if ( count === 4 ) {
  1725. triangulated.push(
  1726. indices[ offset ],
  1727. indices[ offset + 1 ],
  1728. indices[ offset + 2 ],
  1729. indices[ offset ],
  1730. indices[ offset + 2 ],
  1731. indices[ offset + 3 ]
  1732. );
  1733. } else if ( count > 4 ) {
  1734. // Fan triangulation for n-gons
  1735. for ( let j = 1; j < count - 1; j ++ ) {
  1736. triangulated.push(
  1737. indices[ offset ],
  1738. indices[ offset + j ],
  1739. indices[ offset + j + 1 ]
  1740. );
  1741. }
  1742. }
  1743. offset += count;
  1744. }
  1745. return triangulated;
  1746. }
  1747. _expandAttribute( data, indices, itemSize ) {
  1748. const expanded = new Array( indices.length * itemSize );
  1749. for ( let i = 0; i < indices.length; i ++ ) {
  1750. const srcIdx = indices[ i ];
  1751. for ( let j = 0; j < itemSize; j ++ ) {
  1752. expanded[ i * itemSize + j ] = data[ srcIdx * itemSize + j ];
  1753. }
  1754. }
  1755. return expanded;
  1756. }
  1757. /**
  1758. * Compute per-vertex normals from indexed triangle data.
  1759. * Accumulates area-weighted face normals at each shared vertex and normalizes.
  1760. */
  1761. _computeVertexNormals( points, indices ) {
  1762. const numVertices = points.length / 3;
  1763. const normals = new Float32Array( numVertices * 3 );
  1764. for ( let i = 0; i < indices.length; i += 3 ) {
  1765. const a = indices[ i ];
  1766. const b = indices[ i + 1 ];
  1767. const c = indices[ i + 2 ];
  1768. const ax = points[ a * 3 ], ay = points[ a * 3 + 1 ], az = points[ a * 3 + 2 ];
  1769. const bx = points[ b * 3 ], by = points[ b * 3 + 1 ], bz = points[ b * 3 + 2 ];
  1770. const cx = points[ c * 3 ], cy = points[ c * 3 + 1 ], cz = points[ c * 3 + 2 ];
  1771. const e1x = bx - ax, e1y = by - ay, e1z = bz - az;
  1772. const e2x = cx - ax, e2y = cy - ay, e2z = cz - az;
  1773. const nx = e1y * e2z - e1z * e2y;
  1774. const ny = e1z * e2x - e1x * e2z;
  1775. const nz = e1x * e2y - e1y * e2x;
  1776. normals[ a * 3 ] += nx; normals[ a * 3 + 1 ] += ny; normals[ a * 3 + 2 ] += nz;
  1777. normals[ b * 3 ] += nx; normals[ b * 3 + 1 ] += ny; normals[ b * 3 + 2 ] += nz;
  1778. normals[ c * 3 ] += nx; normals[ c * 3 + 1 ] += ny; normals[ c * 3 + 2 ] += nz;
  1779. }
  1780. for ( let i = 0; i < numVertices; i ++ ) {
  1781. const x = normals[ i * 3 ], y = normals[ i * 3 + 1 ], z = normals[ i * 3 + 2 ];
  1782. const len = Math.sqrt( x * x + y * y + z * z );
  1783. if ( len > 0 ) {
  1784. normals[ i * 3 ] /= len;
  1785. normals[ i * 3 + 1 ] /= len;
  1786. normals[ i * 3 + 2 ] /= len;
  1787. }
  1788. }
  1789. return normals;
  1790. }
  1791. /**
  1792. * Get the material path for a mesh, checking various binding sources.
  1793. */
  1794. _getMaterialPath( meshPath, fields ) {
  1795. let materialPath = null;
  1796. const materialBinding = fields[ 'material:binding' ];
  1797. if ( materialBinding ) {
  1798. materialPath = Array.isArray( materialBinding ) ? materialBinding[ 0 ] : materialBinding;
  1799. }
  1800. // Use variant-aware lookup if no direct binding in fields
  1801. if ( ! materialPath ) {
  1802. materialPath = this._getMaterialBindingTarget( meshPath );
  1803. }
  1804. return materialPath;
  1805. }
  1806. _buildMaterial( meshPath, fields ) {
  1807. const material = new MeshPhysicalMaterial();
  1808. let materialPath = null;
  1809. const materialBinding = fields[ 'material:binding' ];
  1810. if ( materialBinding ) {
  1811. materialPath = Array.isArray( materialBinding ) ? materialBinding[ 0 ] : materialBinding;
  1812. }
  1813. // Use variant-aware lookup if no direct binding in fields
  1814. if ( ! materialPath ) {
  1815. materialPath = this._getMaterialBindingTarget( meshPath );
  1816. }
  1817. if ( ! materialPath ) {
  1818. const materialPaths = [];
  1819. const prefix = meshPath + '/';
  1820. for ( const path in this.specsByPath ) {
  1821. if ( ! path.startsWith( prefix ) ) continue;
  1822. if ( ! path.endsWith( '.material:binding' ) ) continue;
  1823. const bindingSpec = this.specsByPath[ path ];
  1824. if ( ! bindingSpec ) continue;
  1825. const targetPaths = bindingSpec.fields.targetPaths;
  1826. if ( targetPaths && targetPaths.length > 0 ) {
  1827. materialPaths.push( targetPaths[ 0 ] );
  1828. }
  1829. }
  1830. if ( materialPaths.length > 0 ) {
  1831. materialPath = this._pickBestMaterial( materialPaths );
  1832. }
  1833. }
  1834. if ( ! materialPath ) {
  1835. // Use material index for O(1) lookup instead of O(n) iteration
  1836. const meshParts = meshPath.split( '/' );
  1837. const rootPath = '/' + meshParts[ 1 ];
  1838. const materialsInRoot = this.materialsByRoot.get( rootPath );
  1839. if ( materialsInRoot ) {
  1840. for ( const path of materialsInRoot ) {
  1841. if ( path.startsWith( rootPath + '/Looks/' ) ||
  1842. path.startsWith( rootPath + '/Materials/' ) ) {
  1843. materialPath = path;
  1844. break;
  1845. }
  1846. }
  1847. }
  1848. }
  1849. if ( materialPath ) {
  1850. this._applyMaterial( material, materialPath );
  1851. }
  1852. return material;
  1853. }
  1854. _buildMaterialForPath( materialPath ) {
  1855. const material = new MeshPhysicalMaterial();
  1856. if ( materialPath ) {
  1857. this._applyMaterial( material, materialPath );
  1858. }
  1859. return material;
  1860. }
  1861. /**
  1862. * Apply material binding from a prim path to a mesh.
  1863. * Used when merging referenced geometry into a prim that has material binding.
  1864. */
  1865. _applyMaterialBinding( mesh, primPath ) {
  1866. // Look for material:binding on this prim
  1867. const bindingPath = primPath + '.material:binding';
  1868. const bindingSpec = this.specsByPath[ bindingPath ];
  1869. if ( ! bindingSpec ) return;
  1870. let materialPath = null;
  1871. const targetPaths = bindingSpec.fields?.targetPaths || bindingSpec.fields?.default;
  1872. if ( targetPaths ) {
  1873. materialPath = Array.isArray( targetPaths ) ? targetPaths[ 0 ] : targetPaths;
  1874. }
  1875. if ( ! materialPath ) return;
  1876. // Clean the material path
  1877. materialPath = String( materialPath ).replace( /^<|>$/g, '' );
  1878. // Build and apply the material
  1879. const material = new MeshPhysicalMaterial();
  1880. this._applyMaterial( material, materialPath );
  1881. mesh.material = material;
  1882. }
  1883. _pickBestMaterial( materialPaths ) {
  1884. for ( const materialPath of materialPaths ) {
  1885. const shaderPaths = this.shadersByMaterialPath.get( materialPath );
  1886. if ( ! shaderPaths ) continue;
  1887. for ( const path of shaderPaths ) {
  1888. const attrs = this._getAttributes( path );
  1889. if ( attrs[ 'info:id' ] === 'UsdUVTexture' && attrs[ 'inputs:file' ] ) {
  1890. return materialPath;
  1891. }
  1892. }
  1893. }
  1894. return materialPaths[ 0 ];
  1895. }
  1896. _applyMaterial( material, materialPath ) {
  1897. const materialSpec = this.specsByPath[ materialPath ];
  1898. if ( ! materialSpec ) return;
  1899. const shaderPaths = this.shadersByMaterialPath.get( materialPath );
  1900. if ( ! shaderPaths ) return;
  1901. for ( const path of shaderPaths ) {
  1902. const spec = this.specsByPath[ path ];
  1903. if ( ! spec ) continue;
  1904. const shaderAttrs = this._getAttributes( path );
  1905. const infoId = shaderAttrs[ 'info:id' ] || spec.fields[ 'info:id' ];
  1906. if ( infoId === 'UsdPreviewSurface' || infoId === 'ND_UsdPreviewSurface_surfaceshader' ) {
  1907. this._applyPreviewSurface( material, path );
  1908. } else if ( infoId === 'arnold:openpbr_surface' ) {
  1909. this._applyOpenPBRSurface( material, path );
  1910. }
  1911. }
  1912. }
  1913. /**
  1914. * Shared helper for applying texture or value from shader attribute.
  1915. * Reduces duplication between _applyPreviewSurface and _applyOpenPBRSurface.
  1916. */
  1917. _applyTextureOrValue( material, shaderPath, fields, attrName, textureProperty, colorSpace, valueCallback, textureGetter ) {
  1918. const attrPath = shaderPath + '.' + attrName;
  1919. const spec = this.specsByPath[ attrPath ];
  1920. if ( spec && spec.fields.connectionPaths && spec.fields.connectionPaths.length > 0 ) {
  1921. // For OpenPBR, try all connection paths; for PreviewSurface, just the first
  1922. const paths = textureGetter === this._getTextureFromOpenPBRConnection
  1923. ? spec.fields.connectionPaths
  1924. : [ spec.fields.connectionPaths[ 0 ] ];
  1925. for ( const connPath of paths ) {
  1926. const texture = textureGetter.call( this, connPath );
  1927. if ( texture ) {
  1928. texture.colorSpace = colorSpace;
  1929. material[ textureProperty ] = texture;
  1930. return true;
  1931. }
  1932. }
  1933. }
  1934. if ( fields[ attrName ] !== undefined && valueCallback ) {
  1935. valueCallback( fields[ attrName ] );
  1936. }
  1937. return false;
  1938. }
  1939. _applyPreviewSurface( material, shaderPath ) {
  1940. const fields = this._getAttributes( shaderPath );
  1941. const applyTexture = ( attrName, textureProperty, colorSpace, valueCallback ) => {
  1942. return this._applyTextureOrValue(
  1943. material, shaderPath, fields, attrName, textureProperty, colorSpace, valueCallback,
  1944. this._getTextureFromConnection
  1945. );
  1946. };
  1947. const getAttrSpec = ( attrName ) => {
  1948. const attrPath = shaderPath + '.' + attrName;
  1949. return this.specsByPath[ attrPath ];
  1950. };
  1951. // Diffuse color / base color map
  1952. applyTexture(
  1953. 'inputs:diffuseColor',
  1954. 'map',
  1955. SRGBColorSpace,
  1956. ( color ) => {
  1957. if ( Array.isArray( color ) && color.length >= 3 ) {
  1958. material.color.setRGB( color[ 0 ], color[ 1 ], color[ 2 ], SRGBColorSpace );
  1959. }
  1960. }
  1961. );
  1962. // Apply UsdUVTexture scale to diffuse color (output = texture * scale + bias)
  1963. if ( material.map && material.map.userData.scale ) {
  1964. const scale = material.map.userData.scale;
  1965. if ( Array.isArray( scale ) && scale.length >= 3 ) {
  1966. material.color.setRGB( scale[ 0 ], scale[ 1 ], scale[ 2 ], SRGBColorSpace );
  1967. }
  1968. }
  1969. // Emissive
  1970. applyTexture(
  1971. 'inputs:emissiveColor',
  1972. 'emissiveMap',
  1973. SRGBColorSpace,
  1974. ( color ) => {
  1975. if ( Array.isArray( color ) && color.length >= 3 ) {
  1976. material.emissive.setRGB( color[ 0 ], color[ 1 ], color[ 2 ], SRGBColorSpace );
  1977. }
  1978. }
  1979. );
  1980. if ( material.emissiveMap ) {
  1981. if ( material.emissiveMap.userData.scale ) {
  1982. const scale = material.emissiveMap.userData.scale;
  1983. if ( Array.isArray( scale ) && scale.length >= 3 ) {
  1984. material.emissive.setRGB( scale[ 0 ], scale[ 1 ], scale[ 2 ], SRGBColorSpace );
  1985. }
  1986. } else {
  1987. material.emissive.set( 0xffffff );
  1988. }
  1989. }
  1990. // Normal map
  1991. applyTexture( 'inputs:normal', 'normalMap', NoColorSpace, null );
  1992. // Apply normal map scale from UsdUVTexture scale input
  1993. if ( material.normalMap && material.normalMap.userData.scale ) {
  1994. const scale = material.normalMap.userData.scale;
  1995. // UsdUVTexture scale is float4 (r,g,b,a), use first two components for normalScale
  1996. material.normalScale = new Vector2( scale[ 0 ], scale[ 1 ] );
  1997. }
  1998. // Roughness
  1999. const hasRoughnessMap = applyTexture(
  2000. 'inputs:roughness',
  2001. 'roughnessMap',
  2002. NoColorSpace,
  2003. ( value ) => {
  2004. material.roughness = value;
  2005. }
  2006. );
  2007. if ( hasRoughnessMap ) {
  2008. material.roughness = 1.0;
  2009. }
  2010. // Metallic
  2011. const hasMetalnessMap = applyTexture(
  2012. 'inputs:metallic',
  2013. 'metalnessMap',
  2014. NoColorSpace,
  2015. ( value ) => {
  2016. material.metalness = value;
  2017. }
  2018. );
  2019. if ( hasMetalnessMap ) {
  2020. material.metalness = 1.0;
  2021. }
  2022. // Occlusion
  2023. applyTexture( 'inputs:occlusion', 'aoMap', NoColorSpace, null );
  2024. // IOR
  2025. if ( fields[ 'inputs:ior' ] !== undefined ) {
  2026. material.ior = fields[ 'inputs:ior' ];
  2027. }
  2028. // Specular color
  2029. applyTexture(
  2030. 'inputs:specularColor',
  2031. 'specularColorMap',
  2032. SRGBColorSpace,
  2033. ( color ) => {
  2034. if ( Array.isArray( color ) && color.length >= 3 ) {
  2035. material.specularColor.setRGB( color[ 0 ], color[ 1 ], color[ 2 ], SRGBColorSpace );
  2036. }
  2037. }
  2038. );
  2039. // Apply UsdUVTexture scale to specular color
  2040. if ( material.specularColorMap && material.specularColorMap.userData.scale ) {
  2041. const scale = material.specularColorMap.userData.scale;
  2042. if ( Array.isArray( scale ) && scale.length >= 3 ) {
  2043. material.specularColor.setRGB( scale[ 0 ], scale[ 1 ], scale[ 2 ], SRGBColorSpace );
  2044. }
  2045. }
  2046. // Clearcoat
  2047. if ( fields[ 'inputs:clearcoat' ] !== undefined ) {
  2048. material.clearcoat = fields[ 'inputs:clearcoat' ];
  2049. }
  2050. // Clearcoat roughness
  2051. if ( fields[ 'inputs:clearcoatRoughness' ] !== undefined ) {
  2052. material.clearcoatRoughness = fields[ 'inputs:clearcoatRoughness' ];
  2053. }
  2054. // Opacity and opacity modes
  2055. const opacityThreshold = fields[ 'inputs:opacityThreshold' ] !== undefined ? fields[ 'inputs:opacityThreshold' ] : 0.0;
  2056. // Check if opacity is connected to a texture (e.g., diffuse texture's alpha)
  2057. const opacitySpec = getAttrSpec( 'inputs:opacity' );
  2058. const hasOpacityConnection = opacitySpec?.fields?.connectionPaths?.length > 0;
  2059. if ( hasOpacityConnection ) {
  2060. // Opacity from texture alpha - use the diffuse map's alpha channel
  2061. if ( opacityThreshold > 0 ) {
  2062. // Alpha cutoff mode
  2063. material.alphaTest = opacityThreshold;
  2064. material.transparent = false;
  2065. } else {
  2066. // Alpha blend mode
  2067. material.transparent = true;
  2068. }
  2069. } else {
  2070. // Direct opacity value
  2071. const opacity = fields[ 'inputs:opacity' ] !== undefined ? fields[ 'inputs:opacity' ] : 1.0;
  2072. if ( opacity < 1.0 ) {
  2073. material.transparent = true;
  2074. material.opacity = opacity;
  2075. }
  2076. }
  2077. }
  2078. _applyOpenPBRSurface( material, shaderPath ) {
  2079. const fields = this._getAttributes( shaderPath );
  2080. const applyTexture = ( attrName, textureProperty, colorSpace, valueCallback ) => {
  2081. return this._applyTextureOrValue(
  2082. material, shaderPath, fields, attrName, textureProperty, colorSpace, valueCallback,
  2083. this._getTextureFromOpenPBRConnection
  2084. );
  2085. };
  2086. // Base color (diffuse)
  2087. applyTexture(
  2088. 'inputs:base_color',
  2089. 'map',
  2090. SRGBColorSpace,
  2091. ( color ) => {
  2092. if ( Array.isArray( color ) && color.length >= 3 ) {
  2093. material.color.setRGB( color[ 0 ], color[ 1 ], color[ 2 ], SRGBColorSpace );
  2094. }
  2095. }
  2096. );
  2097. // Apply UsdUVTexture scale to base color
  2098. if ( material.map && material.map.userData.scale ) {
  2099. const scale = material.map.userData.scale;
  2100. if ( Array.isArray( scale ) && scale.length >= 3 ) {
  2101. material.color.setRGB( scale[ 0 ], scale[ 1 ], scale[ 2 ], SRGBColorSpace );
  2102. }
  2103. }
  2104. // Base metalness
  2105. applyTexture(
  2106. 'inputs:base_metalness',
  2107. 'metalnessMap',
  2108. NoColorSpace,
  2109. ( value ) => {
  2110. if ( typeof value === 'number' ) {
  2111. material.metalness = value;
  2112. }
  2113. }
  2114. );
  2115. // Specular roughness
  2116. applyTexture(
  2117. 'inputs:specular_roughness',
  2118. 'roughnessMap',
  2119. NoColorSpace,
  2120. ( value ) => {
  2121. if ( typeof value === 'number' ) {
  2122. material.roughness = value;
  2123. }
  2124. }
  2125. );
  2126. // Emission color
  2127. const hasEmissionMap = applyTexture(
  2128. 'inputs:emission_color',
  2129. 'emissiveMap',
  2130. SRGBColorSpace,
  2131. ( color ) => {
  2132. if ( Array.isArray( color ) && color.length >= 3 ) {
  2133. material.emissive.setRGB( color[ 0 ], color[ 1 ], color[ 2 ], SRGBColorSpace );
  2134. }
  2135. }
  2136. );
  2137. // Emission luminance/weight - multiply emissive by this factor
  2138. const emissionLuminance = fields[ 'inputs:emission_luminance' ];
  2139. if ( emissionLuminance !== undefined && emissionLuminance > 0 ) {
  2140. if ( hasEmissionMap ) {
  2141. material.emissiveIntensity = emissionLuminance;
  2142. } else {
  2143. // Scale the emissive color by luminance
  2144. material.emissive.multiplyScalar( emissionLuminance );
  2145. }
  2146. }
  2147. // Transmission (transparency)
  2148. const transmissionWeight = fields[ 'inputs:transmission_weight' ];
  2149. if ( transmissionWeight !== undefined && transmissionWeight > 0 ) {
  2150. material.transmission = transmissionWeight;
  2151. const transmissionDepth = fields[ 'inputs:transmission_depth' ];
  2152. if ( transmissionDepth !== undefined ) {
  2153. material.thickness = transmissionDepth;
  2154. }
  2155. const transmissionColor = fields[ 'inputs:transmission_color' ];
  2156. if ( transmissionColor !== undefined && Array.isArray( transmissionColor ) ) {
  2157. material.attenuationColor.setRGB( transmissionColor[ 0 ], transmissionColor[ 1 ], transmissionColor[ 2 ] );
  2158. material.attenuationDistance = transmissionDepth || 1.0;
  2159. }
  2160. }
  2161. // Geometry opacity (overall surface opacity)
  2162. const geometryOpacity = fields[ 'inputs:geometry_opacity' ];
  2163. if ( geometryOpacity !== undefined && geometryOpacity < 1.0 ) {
  2164. material.opacity = geometryOpacity;
  2165. material.transparent = true;
  2166. }
  2167. // Specular IOR
  2168. const specularIOR = fields[ 'inputs:specular_ior' ];
  2169. if ( specularIOR !== undefined ) {
  2170. material.ior = specularIOR;
  2171. }
  2172. // Coat (clearcoat)
  2173. const coatWeight = fields[ 'inputs:coat_weight' ];
  2174. if ( coatWeight !== undefined && coatWeight > 0 ) {
  2175. material.clearcoat = coatWeight;
  2176. const coatRoughness = fields[ 'inputs:coat_roughness' ];
  2177. if ( coatRoughness !== undefined ) {
  2178. material.clearcoatRoughness = coatRoughness;
  2179. }
  2180. }
  2181. // Thin film (iridescence)
  2182. const thinFilmWeight = fields[ 'inputs:thin_film_weight' ];
  2183. if ( thinFilmWeight !== undefined && thinFilmWeight > 0 ) {
  2184. material.iridescence = thinFilmWeight;
  2185. const thinFilmIOR = fields[ 'inputs:thin_film_ior' ];
  2186. if ( thinFilmIOR !== undefined ) {
  2187. material.iridescenceIOR = thinFilmIOR;
  2188. }
  2189. const thinFilmThickness = fields[ 'inputs:thin_film_thickness' ];
  2190. if ( thinFilmThickness !== undefined ) {
  2191. // OpenPBR uses micrometers, Three.js uses nanometers
  2192. const thicknessNm = thinFilmThickness * 1000;
  2193. material.iridescenceThicknessRange = [ thicknessNm, thicknessNm ];
  2194. }
  2195. }
  2196. // Specular
  2197. const specularWeight = fields[ 'inputs:specular_weight' ];
  2198. if ( specularWeight !== undefined ) {
  2199. material.specularIntensity = specularWeight;
  2200. }
  2201. const specularColor = fields[ 'inputs:specular_color' ];
  2202. if ( specularColor !== undefined && Array.isArray( specularColor ) ) {
  2203. material.specularColor.setRGB( specularColor[ 0 ], specularColor[ 1 ], specularColor[ 2 ] );
  2204. }
  2205. // Anisotropy
  2206. const anisotropy = fields[ 'inputs:specular_roughness_anisotropy' ];
  2207. if ( anisotropy !== undefined && anisotropy > 0 ) {
  2208. material.anisotropy = anisotropy;
  2209. }
  2210. // Geometry normal (normal map)
  2211. applyTexture(
  2212. 'inputs:geometry_normal',
  2213. 'normalMap',
  2214. NoColorSpace,
  2215. null
  2216. );
  2217. }
  2218. _getTextureFromOpenPBRConnection( connPath ) {
  2219. // connPath is like /Material/NodeGraph.outputs:baseColor or /Material/Shader.outputs:out
  2220. const cleanPath = connPath.replace( /<|>/g, '' );
  2221. const shaderPath = cleanPath.split( '.' )[ 0 ];
  2222. const shaderSpec = this.specsByPath[ shaderPath ];
  2223. if ( ! shaderSpec ) return null;
  2224. const attrs = this._getAttributes( shaderPath );
  2225. const infoId = attrs[ 'info:id' ] || shaderSpec.fields[ 'info:id' ];
  2226. const typeName = shaderSpec.fields.typeName;
  2227. // Handle NodeGraph - follow output connection to internal shader
  2228. if ( typeName === 'NodeGraph' ) {
  2229. // Get the output attribute that's connected
  2230. const outputName = cleanPath.split( '.' )[ 1 ]; // e.g., "outputs:baseColor"
  2231. const outputAttrPath = shaderPath + '.' + outputName;
  2232. const outputSpec = this.specsByPath[ outputAttrPath ];
  2233. if ( outputSpec?.fields?.connectionPaths?.length > 0 ) {
  2234. // Follow the internal connection
  2235. return this._getTextureFromOpenPBRConnection( outputSpec.fields.connectionPaths[ 0 ] );
  2236. }
  2237. return null;
  2238. }
  2239. // Handle arnold:image - Arnold's texture node
  2240. if ( infoId === 'arnold:image' ) {
  2241. const filePath = attrs[ 'inputs:filename' ];
  2242. if ( ! filePath ) return null;
  2243. return this._loadTextureFromPath( filePath );
  2244. }
  2245. // Handle MaterialX image nodes (ND_image_color4, ND_image_color3, etc.)
  2246. if ( infoId && infoId.startsWith( 'ND_image_' ) ) {
  2247. const filePath = attrs[ 'inputs:file' ];
  2248. if ( ! filePath ) return null;
  2249. return this._loadTextureFromPath( filePath );
  2250. }
  2251. // Handle Maya file texture - follow the inColor connection to the actual image
  2252. if ( infoId === 'MayaND_fileTexture_color4' ) {
  2253. const inColorPath = shaderPath + '.inputs:inColor';
  2254. const inColorSpec = this.specsByPath[ inColorPath ];
  2255. if ( inColorSpec?.fields?.connectionPaths?.length > 0 ) {
  2256. return this._getTextureFromOpenPBRConnection( inColorSpec.fields.connectionPaths[ 0 ] );
  2257. }
  2258. return null;
  2259. }
  2260. // Handle color conversion nodes - follow the input connection
  2261. if ( infoId && infoId.startsWith( 'ND_convert_' ) ) {
  2262. const inPath = shaderPath + '.inputs:in';
  2263. const inSpec = this.specsByPath[ inPath ];
  2264. if ( inSpec?.fields?.connectionPaths?.length > 0 ) {
  2265. return this._getTextureFromOpenPBRConnection( inSpec.fields.connectionPaths[ 0 ] );
  2266. }
  2267. return null;
  2268. }
  2269. // Handle Arnold bump2d - follow the bump_map input
  2270. if ( infoId === 'arnold:bump2d' ) {
  2271. const bumpMapPath = shaderPath + '.inputs:bump_map';
  2272. const bumpMapSpec = this.specsByPath[ bumpMapPath ];
  2273. if ( bumpMapSpec?.fields?.connectionPaths?.length > 0 ) {
  2274. return this._getTextureFromOpenPBRConnection( bumpMapSpec.fields.connectionPaths[ 0 ] );
  2275. }
  2276. return null;
  2277. }
  2278. // Handle Arnold color_correct - follow the input connection
  2279. if ( infoId === 'arnold:color_correct' ) {
  2280. const inputPath = shaderPath + '.inputs:input';
  2281. const inputSpec = this.specsByPath[ inputPath ];
  2282. if ( inputSpec?.fields?.connectionPaths?.length > 0 ) {
  2283. return this._getTextureFromOpenPBRConnection( inputSpec.fields.connectionPaths[ 0 ] );
  2284. }
  2285. return null;
  2286. }
  2287. // Handle nested shader paths (e.g., /Material/file2/cc.outputs:a)
  2288. // Check if parent path is an image node
  2289. const parentPath = shaderPath.substring( 0, shaderPath.lastIndexOf( '/' ) );
  2290. if ( parentPath ) {
  2291. const parentSpec = this.specsByPath[ parentPath ];
  2292. if ( parentSpec ) {
  2293. const parentAttrs = this._getAttributes( parentPath );
  2294. const parentInfoId = parentAttrs[ 'info:id' ] || parentSpec.fields[ 'info:id' ];
  2295. if ( parentInfoId === 'arnold:image' ) {
  2296. const filePath = parentAttrs[ 'inputs:filename' ];
  2297. if ( filePath ) return this._loadTextureFromPath( filePath );
  2298. }
  2299. }
  2300. }
  2301. return null;
  2302. }
  2303. _loadTextureFromPath( filePath ) {
  2304. if ( ! filePath ) return null;
  2305. // Check cache first
  2306. if ( this.textureCache[ filePath ] ) {
  2307. return this.textureCache[ filePath ];
  2308. }
  2309. const texture = this._loadTexture( filePath, null, null );
  2310. if ( texture ) {
  2311. this.textureCache[ filePath ] = texture;
  2312. }
  2313. return texture;
  2314. }
  2315. _getTextureFromConnection( connPath ) {
  2316. // connPath is like /Material/Shader.outputs:rgb
  2317. const shaderPath = connPath.split( '.' )[ 0 ];
  2318. const shaderSpec = this.specsByPath[ shaderPath ];
  2319. if ( ! shaderSpec ) return null;
  2320. const attrs = this._getAttributes( shaderPath );
  2321. const infoId = attrs[ 'info:id' ] || shaderSpec.fields[ 'info:id' ];
  2322. if ( infoId !== 'UsdUVTexture' ) return null;
  2323. const filePath = attrs[ 'inputs:file' ];
  2324. if ( ! filePath ) return null;
  2325. // Check for UsdTransform2d connection via inputs:st and trace to PrimvarReader
  2326. let transformAttrs = null;
  2327. let uvChannel = 0; // Default to first UV set
  2328. const stAttrPath = shaderPath + '.inputs:st';
  2329. const stAttrSpec = this.specsByPath[ stAttrPath ];
  2330. if ( stAttrSpec?.fields?.connectionPaths?.length > 0 ) {
  2331. const stConnPath = stAttrSpec.fields.connectionPaths[ 0 ];
  2332. const stPath = stConnPath.replace( /<|>/g, '' ).split( '.' )[ 0 ];
  2333. const stSpec = this.specsByPath[ stPath ];
  2334. if ( stSpec ) {
  2335. const stAttrs = this._getAttributes( stPath );
  2336. const stInfoId = stAttrs[ 'info:id' ] || stSpec.fields[ 'info:id' ];
  2337. if ( stInfoId === 'UsdTransform2d' ) {
  2338. transformAttrs = stAttrs;
  2339. // Trace to PrimvarReader to find UV set
  2340. const inAttrPath = stPath + '.inputs:in';
  2341. const inAttrSpec = this.specsByPath[ inAttrPath ];
  2342. if ( inAttrSpec?.fields?.connectionPaths?.length > 0 ) {
  2343. const inConnPath = inAttrSpec.fields.connectionPaths[ 0 ];
  2344. const primvarPath = inConnPath.replace( /<|>/g, '' ).split( '.' )[ 0 ];
  2345. const primvarAttrs = this._getAttributes( primvarPath );
  2346. // Check varname to determine UV channel
  2347. const varname = primvarAttrs[ 'inputs:varname' ];
  2348. if ( varname === 'st1' ) uvChannel = 1;
  2349. else if ( varname === 'st2' ) uvChannel = 2;
  2350. }
  2351. } else if ( stInfoId === 'UsdPrimvarReader_float2' ) {
  2352. // Direct connection to PrimvarReader
  2353. const varname = stAttrs[ 'inputs:varname' ];
  2354. if ( varname === 'st1' ) uvChannel = 1;
  2355. else if ( varname === 'st2' ) uvChannel = 2;
  2356. }
  2357. }
  2358. }
  2359. // Extract scale and bias for texture value modification
  2360. const scale = attrs[ 'inputs:scale' ];
  2361. const bias = attrs[ 'inputs:bias' ];
  2362. // Create cache key that includes scale/bias if present
  2363. let cacheKey = filePath;
  2364. if ( scale ) cacheKey += ':s' + scale.join( ',' );
  2365. if ( bias ) cacheKey += ':b' + bias.join( ',' );
  2366. if ( this.textureCache[ cacheKey ] ) {
  2367. return this.textureCache[ cacheKey ];
  2368. }
  2369. const texture = this._loadTexture( filePath, attrs, transformAttrs );
  2370. if ( texture ) {
  2371. // Store scale/bias and UV channel in userData
  2372. if ( scale ) texture.userData.scale = scale;
  2373. if ( bias ) texture.userData.bias = bias;
  2374. if ( uvChannel !== 0 ) texture.channel = uvChannel;
  2375. this.textureCache[ cacheKey ] = texture;
  2376. }
  2377. return texture;
  2378. }
  2379. _applyTextureTransforms( texture, attrs ) {
  2380. if ( ! attrs ) return;
  2381. const scale = attrs[ 'inputs:scale' ];
  2382. if ( scale && Array.isArray( scale ) && scale.length >= 2 ) {
  2383. texture.repeat.set( scale[ 0 ], scale[ 1 ] );
  2384. }
  2385. const translation = attrs[ 'inputs:translation' ];
  2386. if ( translation && Array.isArray( translation ) && translation.length >= 2 ) {
  2387. texture.offset.set( translation[ 0 ], translation[ 1 ] );
  2388. }
  2389. const rotation = attrs[ 'inputs:rotation' ];
  2390. if ( typeof rotation === 'number' ) {
  2391. texture.rotation = rotation * Math.PI / 180;
  2392. }
  2393. }
  2394. _loadTexture( filePath, textureAttrs, transformAttrs ) {
  2395. let cleanPath = filePath;
  2396. if ( cleanPath.startsWith( '@' ) ) cleanPath = cleanPath.slice( 1 );
  2397. if ( cleanPath.endsWith( '@' ) ) cleanPath = cleanPath.slice( 0, - 1 );
  2398. // Resolve relative to basePath first
  2399. const resolvedPath = this._resolveFilePath( cleanPath );
  2400. let assetData = this.assets[ resolvedPath ];
  2401. // Fallback to unresolved path
  2402. if ( ! assetData ) {
  2403. assetData = this.assets[ cleanPath ];
  2404. }
  2405. // Last resort: search by basename
  2406. if ( ! assetData ) {
  2407. const baseName = cleanPath.split( '/' ).pop();
  2408. for ( const key in this.assets ) {
  2409. if ( key.endsWith( baseName ) || key.endsWith( '/' + baseName ) ) {
  2410. return this._createTextureFromData( this.assets[ key ], textureAttrs, transformAttrs );
  2411. }
  2412. }
  2413. // Try loading via LoadingManager if available
  2414. if ( this.manager ) {
  2415. const url = this.manager.resolveURL( baseName );
  2416. if ( url !== baseName ) {
  2417. // URL modifier found a match - load it
  2418. return this._createTextureFromData( url, textureAttrs, transformAttrs );
  2419. }
  2420. }
  2421. console.warn( 'USDLoader: Texture not found:', cleanPath );
  2422. return null;
  2423. }
  2424. return this._createTextureFromData( assetData, textureAttrs, transformAttrs );
  2425. }
  2426. _createTextureFromData( data, textureAttrs, transformAttrs ) {
  2427. if ( ! data ) return null;
  2428. const scope = this;
  2429. const texture = new Texture();
  2430. let url;
  2431. if ( typeof data === 'string' ) {
  2432. url = data;
  2433. } else if ( data instanceof Uint8Array || data instanceof ArrayBuffer ) {
  2434. const blob = new Blob( [ data ] );
  2435. url = URL.createObjectURL( blob );
  2436. } else {
  2437. return null;
  2438. }
  2439. const image = new Image();
  2440. image.onload = function () {
  2441. texture.image = image;
  2442. if ( textureAttrs ) {
  2443. texture.wrapS = scope._getWrapMode( textureAttrs[ 'inputs:wrapS' ] );
  2444. texture.wrapT = scope._getWrapMode( textureAttrs[ 'inputs:wrapT' ] );
  2445. }
  2446. scope._applyTextureTransforms( texture, transformAttrs );
  2447. texture.needsUpdate = true;
  2448. if ( typeof data !== 'string' ) {
  2449. URL.revokeObjectURL( url );
  2450. }
  2451. };
  2452. image.src = url;
  2453. return texture;
  2454. }
  2455. _getWrapMode( wrapValue ) {
  2456. if ( wrapValue === 'repeat' ) return RepeatWrapping;
  2457. if ( wrapValue === 'mirror' ) return MirroredRepeatWrapping;
  2458. if ( wrapValue === 'clamp' ) return ClampToEdgeWrapping;
  2459. return RepeatWrapping;
  2460. }
  2461. // ========================================================================
  2462. // Skeletal Animation
  2463. // ========================================================================
  2464. _buildSkeleton( path ) {
  2465. const attrs = this._getAttributes( path );
  2466. // Get joint names (paths like "root", "root/body_joint", etc.)
  2467. const joints = attrs[ 'joints' ];
  2468. if ( ! joints || joints.length === 0 ) return null;
  2469. // Get bind transforms (world-space bind pose matrices)
  2470. // These can be nested arrays (USDA) or flat arrays (USDC)
  2471. const rawBindTransforms = attrs[ 'bindTransforms' ];
  2472. const rawRestTransforms = attrs[ 'restTransforms' ];
  2473. const bindTransforms = this._flattenMatrixArray( rawBindTransforms, joints.length );
  2474. const restTransforms = this._flattenMatrixArray( rawRestTransforms, joints.length );
  2475. // Build bones
  2476. const bones = [];
  2477. const bonesByPath = {};
  2478. const boneInverses = [];
  2479. for ( let i = 0; i < joints.length; i ++ ) {
  2480. const jointPath = joints[ i ];
  2481. const jointName = jointPath.split( '/' ).pop();
  2482. const bone = new Bone();
  2483. bone.name = jointName;
  2484. bones.push( bone );
  2485. bonesByPath[ jointPath ] = { bone, index: i };
  2486. // Compute inverse bind matrix
  2487. if ( bindTransforms && bindTransforms.length >= ( i + 1 ) * 16 ) {
  2488. const bindMatrix = new Matrix4();
  2489. // USD matrices are row-major, Three.js is column-major - need to transpose
  2490. const m = bindTransforms.slice( i * 16, ( i + 1 ) * 16 );
  2491. bindMatrix.set(
  2492. m[ 0 ], m[ 4 ], m[ 8 ], m[ 12 ],
  2493. m[ 1 ], m[ 5 ], m[ 9 ], m[ 13 ],
  2494. m[ 2 ], m[ 6 ], m[ 10 ], m[ 14 ],
  2495. m[ 3 ], m[ 7 ], m[ 11 ], m[ 15 ]
  2496. );
  2497. const inverseBindMatrix = bindMatrix.clone().invert();
  2498. boneInverses.push( inverseBindMatrix );
  2499. } else {
  2500. boneInverses.push( new Matrix4() );
  2501. }
  2502. }
  2503. // Build parent-child relationships based on joint paths
  2504. for ( let i = 0; i < joints.length; i ++ ) {
  2505. const jointPath = joints[ i ];
  2506. const parts = jointPath.split( '/' );
  2507. if ( parts.length > 1 ) {
  2508. const parentPath = parts.slice( 0, - 1 ).join( '/' );
  2509. const parentData = bonesByPath[ parentPath ];
  2510. if ( parentData ) {
  2511. parentData.bone.add( bones[ i ] );
  2512. }
  2513. }
  2514. }
  2515. // Apply rest transforms as bone local transforms.
  2516. // Rest transforms are the skeleton's default local-space pose and match
  2517. // the reference frame used by SkelAnimation data. Bind transforms are
  2518. // world-space matrices used only for computing inverse bind matrices.
  2519. if ( restTransforms && restTransforms.length >= joints.length * 16 ) {
  2520. for ( let i = 0; i < joints.length; i ++ ) {
  2521. const matrix = new Matrix4();
  2522. const m = restTransforms.slice( i * 16, ( i + 1 ) * 16 );
  2523. matrix.set(
  2524. m[ 0 ], m[ 4 ], m[ 8 ], m[ 12 ],
  2525. m[ 1 ], m[ 5 ], m[ 9 ], m[ 13 ],
  2526. m[ 2 ], m[ 6 ], m[ 10 ], m[ 14 ],
  2527. m[ 3 ], m[ 7 ], m[ 11 ], m[ 15 ]
  2528. );
  2529. matrix.decompose( bones[ i ].position, bones[ i ].quaternion, bones[ i ].scale );
  2530. }
  2531. }
  2532. // Find root bone(s) - bones without a parent bone
  2533. const rootBones = bones.filter( bone => ! bone.parent || ! bone.parent.isBone );
  2534. // Get animation source path
  2535. const animSourceSpec = this.specsByPath[ path + '.skel:animationSource' ];
  2536. let animationPath = null;
  2537. if ( animSourceSpec && animSourceSpec.fields.targetPaths && animSourceSpec.fields.targetPaths.length > 0 ) {
  2538. animationPath = animSourceSpec.fields.targetPaths[ 0 ];
  2539. }
  2540. return {
  2541. skeleton: new Skeleton( bones, boneInverses ),
  2542. joints: joints,
  2543. rootBones: rootBones,
  2544. animationPath: animationPath,
  2545. path: path
  2546. };
  2547. }
  2548. _bindSkeletons() {
  2549. for ( const meshData of this.skinnedMeshes ) {
  2550. const { mesh, skeletonPath, localJoints, geomBindTransform } = meshData;
  2551. let skeletonData = null;
  2552. // Try exact match first
  2553. if ( skeletonPath && this.skeletons[ skeletonPath ] ) {
  2554. skeletonData = this.skeletons[ skeletonPath ];
  2555. }
  2556. // Try includes match as fallback
  2557. if ( ! skeletonData ) {
  2558. for ( const skelPath in this.skeletons ) {
  2559. if ( skeletonPath && ( skeletonPath.includes( skelPath ) || skelPath.includes( skeletonPath ) ) ) {
  2560. skeletonData = this.skeletons[ skelPath ];
  2561. break;
  2562. }
  2563. }
  2564. }
  2565. // Fallback to first skeleton for single-skeleton files
  2566. if ( ! skeletonData ) {
  2567. const skeletonPaths = Object.keys( this.skeletons );
  2568. if ( skeletonPaths.length > 0 ) {
  2569. skeletonData = this.skeletons[ skeletonPaths[ 0 ] ];
  2570. }
  2571. }
  2572. if ( ! skeletonData ) {
  2573. console.warn( 'USDComposer: No skeleton found for skinned mesh', mesh.name );
  2574. continue;
  2575. }
  2576. const { skeleton, rootBones, joints } = skeletonData;
  2577. if ( localJoints && localJoints.length > 0 ) {
  2578. const skinIndex = mesh.geometry.attributes.skinIndex;
  2579. if ( skinIndex ) {
  2580. const localToGlobal = [];
  2581. for ( let i = 0; i < localJoints.length; i ++ ) {
  2582. const jointName = localJoints[ i ];
  2583. const globalIdx = joints.indexOf( jointName );
  2584. localToGlobal[ i ] = globalIdx >= 0 ? globalIdx : 0;
  2585. }
  2586. const arr = skinIndex.array;
  2587. for ( let i = 0; i < arr.length; i ++ ) {
  2588. const localIdx = arr[ i ];
  2589. if ( localIdx < localToGlobal.length ) {
  2590. arr[ i ] = localToGlobal[ localIdx ];
  2591. }
  2592. }
  2593. }
  2594. }
  2595. for ( const rootBone of rootBones ) {
  2596. mesh.add( rootBone );
  2597. }
  2598. // Use geomBindTransform if available, otherwise fall back to identity.
  2599. // Estimating bind transforms from vertex/joint samples is not robust and can
  2600. // produce severe skinning distortion for valid assets.
  2601. const bindMatrix = new Matrix4();
  2602. if ( geomBindTransform && geomBindTransform.length === 16 ) {
  2603. // USD matrices are row-major, Three.js is column-major - need to transpose
  2604. const m = geomBindTransform;
  2605. bindMatrix.set(
  2606. m[ 0 ], m[ 4 ], m[ 8 ], m[ 12 ],
  2607. m[ 1 ], m[ 5 ], m[ 9 ], m[ 13 ],
  2608. m[ 2 ], m[ 6 ], m[ 10 ], m[ 14 ],
  2609. m[ 3 ], m[ 7 ], m[ 11 ], m[ 15 ]
  2610. );
  2611. }
  2612. mesh.bind( skeleton, bindMatrix );
  2613. }
  2614. }
  2615. _buildAnimations() {
  2616. const animations = [];
  2617. // Find all SkelAnimation prims
  2618. for ( const path in this.specsByPath ) {
  2619. const spec = this.specsByPath[ path ];
  2620. if ( spec.specType !== SpecType.Prim ) continue;
  2621. if ( spec.fields.typeName !== 'SkelAnimation' ) continue;
  2622. const clip = this._buildAnimationClip( path );
  2623. if ( clip ) {
  2624. animations.push( clip );
  2625. }
  2626. }
  2627. // Build transform animations from time-sampled xformOps
  2628. const transformTracks = this._buildTransformAnimations();
  2629. if ( transformTracks.length > 0 ) {
  2630. animations.push( new AnimationClip( 'TransformAnimation', - 1, transformTracks ) );
  2631. }
  2632. return animations;
  2633. }
  2634. _buildTransformAnimations() {
  2635. const tracks = [];
  2636. for ( const path in this.specsByPath ) {
  2637. const spec = this.specsByPath[ path ];
  2638. if ( spec.specType !== SpecType.Prim ) continue;
  2639. const typeName = spec.fields?.typeName;
  2640. if ( typeName !== 'Xform' && typeName !== 'Scope' && typeName !== 'Mesh' ) continue;
  2641. const objectName = path.split( '/' ).pop();
  2642. // Check for animated xformOp:orient
  2643. const orientPath = path + '.xformOp:orient';
  2644. const orientSpec = this.specsByPath[ orientPath ];
  2645. if ( orientSpec?.fields?.timeSamples ) {
  2646. const { times, values } = orientSpec.fields.timeSamples;
  2647. const keyframeTimes = [];
  2648. const keyframeValues = [];
  2649. for ( let i = 0; i < times.length; i ++ ) {
  2650. keyframeTimes.push( times[ i ] / this.fps );
  2651. const q = values[ i ];
  2652. keyframeValues.push( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  2653. }
  2654. if ( keyframeTimes.length > 0 ) {
  2655. tracks.push( new QuaternionKeyframeTrack(
  2656. objectName + '.quaternion',
  2657. new Float32Array( keyframeTimes ),
  2658. new Float32Array( keyframeValues )
  2659. ) );
  2660. }
  2661. }
  2662. // Check for animated xformOp:rotateXYZ
  2663. const rotateXYZPath = path + '.xformOp:rotateXYZ';
  2664. const rotateXYZSpec = this.specsByPath[ rotateXYZPath ];
  2665. if ( rotateXYZSpec?.fields?.timeSamples ) {
  2666. const { times, values } = rotateXYZSpec.fields.timeSamples;
  2667. const keyframeTimes = [];
  2668. const keyframeValues = [];
  2669. const tempEuler = new Euler();
  2670. const tempQuat = new Quaternion();
  2671. for ( let i = 0; i < times.length; i ++ ) {
  2672. keyframeTimes.push( times[ i ] / this.fps );
  2673. const r = values[ i ];
  2674. // USD rotateXYZ: matrix = Rx * Ry * Rz, use 'ZYX' order in Three.js
  2675. tempEuler.set(
  2676. r[ 0 ] * Math.PI / 180,
  2677. r[ 1 ] * Math.PI / 180,
  2678. r[ 2 ] * Math.PI / 180,
  2679. 'ZYX'
  2680. );
  2681. tempQuat.setFromEuler( tempEuler );
  2682. keyframeValues.push( tempQuat.x, tempQuat.y, tempQuat.z, tempQuat.w );
  2683. }
  2684. if ( keyframeTimes.length > 0 ) {
  2685. tracks.push( new QuaternionKeyframeTrack(
  2686. objectName + '.quaternion',
  2687. new Float32Array( keyframeTimes ),
  2688. new Float32Array( keyframeValues )
  2689. ) );
  2690. }
  2691. }
  2692. // Check for animated xformOp:translate
  2693. const translatePath = path + '.xformOp:translate';
  2694. const translateSpec = this.specsByPath[ translatePath ];
  2695. if ( translateSpec?.fields?.timeSamples ) {
  2696. const { times, values } = translateSpec.fields.timeSamples;
  2697. const keyframeTimes = [];
  2698. const keyframeValues = [];
  2699. for ( let i = 0; i < times.length; i ++ ) {
  2700. keyframeTimes.push( times[ i ] / this.fps );
  2701. const t = values[ i ];
  2702. keyframeValues.push( t[ 0 ], t[ 1 ], t[ 2 ] );
  2703. }
  2704. if ( keyframeTimes.length > 0 ) {
  2705. tracks.push( new VectorKeyframeTrack(
  2706. objectName + '.position',
  2707. new Float32Array( keyframeTimes ),
  2708. new Float32Array( keyframeValues )
  2709. ) );
  2710. }
  2711. }
  2712. // Check for animated xformOp:scale
  2713. const scalePath = path + '.xformOp:scale';
  2714. const scaleSpec = this.specsByPath[ scalePath ];
  2715. if ( scaleSpec?.fields?.timeSamples ) {
  2716. const { times, values } = scaleSpec.fields.timeSamples;
  2717. const keyframeTimes = [];
  2718. const keyframeValues = [];
  2719. for ( let i = 0; i < times.length; i ++ ) {
  2720. keyframeTimes.push( times[ i ] / this.fps );
  2721. const s = values[ i ];
  2722. keyframeValues.push( s[ 0 ], s[ 1 ], s[ 2 ] );
  2723. }
  2724. if ( keyframeTimes.length > 0 ) {
  2725. tracks.push( new VectorKeyframeTrack(
  2726. objectName + '.scale',
  2727. new Float32Array( keyframeTimes ),
  2728. new Float32Array( keyframeValues )
  2729. ) );
  2730. }
  2731. }
  2732. // Check for animated xformOp:transform (matrix animations)
  2733. // These can have suffixes like xformOp:transform:transform
  2734. const properties = spec.fields?.properties || [];
  2735. for ( const prop of properties ) {
  2736. if ( ! prop.startsWith( 'xformOp:transform' ) ) continue;
  2737. const transformPath = path + '.' + prop;
  2738. const transformSpec = this.specsByPath[ transformPath ];
  2739. if ( ! transformSpec?.fields?.timeSamples ) continue;
  2740. const { times, values } = transformSpec.fields.timeSamples;
  2741. const positionTimes = [];
  2742. const positionValues = [];
  2743. const quaternionTimes = [];
  2744. const quaternionValues = [];
  2745. const scaleTimes = [];
  2746. const scaleValues = [];
  2747. const matrix = new Matrix4();
  2748. const position = new Vector3();
  2749. const quaternion = new Quaternion();
  2750. const scale = new Vector3();
  2751. for ( let i = 0; i < times.length; i ++ ) {
  2752. const m = values[ i ];
  2753. if ( ! m || m.length < 16 ) continue;
  2754. const t = times[ i ] / this.fps;
  2755. // USD matrices are row-major, Three.js is column-major
  2756. matrix.set(
  2757. m[ 0 ], m[ 4 ], m[ 8 ], m[ 12 ],
  2758. m[ 1 ], m[ 5 ], m[ 9 ], m[ 13 ],
  2759. m[ 2 ], m[ 6 ], m[ 10 ], m[ 14 ],
  2760. m[ 3 ], m[ 7 ], m[ 11 ], m[ 15 ]
  2761. );
  2762. matrix.decompose( position, quaternion, scale );
  2763. positionTimes.push( t );
  2764. positionValues.push( position.x, position.y, position.z );
  2765. quaternionTimes.push( t );
  2766. quaternionValues.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  2767. scaleTimes.push( t );
  2768. scaleValues.push( scale.x, scale.y, scale.z );
  2769. }
  2770. if ( positionTimes.length > 0 ) {
  2771. tracks.push( new VectorKeyframeTrack(
  2772. objectName + '.position',
  2773. new Float32Array( positionTimes ),
  2774. new Float32Array( positionValues )
  2775. ) );
  2776. tracks.push( new QuaternionKeyframeTrack(
  2777. objectName + '.quaternion',
  2778. new Float32Array( quaternionTimes ),
  2779. new Float32Array( quaternionValues )
  2780. ) );
  2781. tracks.push( new VectorKeyframeTrack(
  2782. objectName + '.scale',
  2783. new Float32Array( scaleTimes ),
  2784. new Float32Array( scaleValues )
  2785. ) );
  2786. }
  2787. break; // Only process first transform op
  2788. }
  2789. }
  2790. return tracks;
  2791. }
  2792. _buildAnimationClip( path ) {
  2793. const attrs = this._getAttributes( path );
  2794. const joints = attrs[ 'joints' ];
  2795. if ( ! joints || joints.length === 0 ) return null;
  2796. const tracks = [];
  2797. // Get rotation time samples
  2798. const rotationsAttr = this._getTimeSampledAttribute( path, 'rotations' );
  2799. if ( rotationsAttr && rotationsAttr.times && rotationsAttr.values ) {
  2800. const { times, values } = rotationsAttr;
  2801. for ( let jointIdx = 0; jointIdx < joints.length; jointIdx ++ ) {
  2802. const jointName = joints[ jointIdx ].split( '/' ).pop();
  2803. const keyframeTimes = [];
  2804. const keyframeValues = [];
  2805. for ( let t = 0; t < times.length; t ++ ) {
  2806. const quatData = values[ t ];
  2807. if ( ! quatData || quatData.length < ( jointIdx + 1 ) * 4 ) continue;
  2808. keyframeTimes.push( times[ t ] / this.fps );
  2809. // USD GfQuatf stores imaginary (x,y,z) first, then real (w)
  2810. // This matches Three.js quaternion order (x,y,z,w)
  2811. const x = quatData[ jointIdx * 4 + 0 ];
  2812. const y = quatData[ jointIdx * 4 + 1 ];
  2813. const z = quatData[ jointIdx * 4 + 2 ];
  2814. const w = quatData[ jointIdx * 4 + 3 ];
  2815. keyframeValues.push( x, y, z, w );
  2816. }
  2817. if ( keyframeTimes.length > 0 ) {
  2818. tracks.push( new QuaternionKeyframeTrack(
  2819. jointName + '.quaternion',
  2820. new Float32Array( keyframeTimes ),
  2821. new Float32Array( keyframeValues )
  2822. ) );
  2823. }
  2824. }
  2825. }
  2826. // Get translation time samples
  2827. const translationsAttr = this._getTimeSampledAttribute( path, 'translations' );
  2828. if ( translationsAttr && translationsAttr.times && translationsAttr.values ) {
  2829. const { times, values } = translationsAttr;
  2830. for ( let jointIdx = 0; jointIdx < joints.length; jointIdx ++ ) {
  2831. const jointName = joints[ jointIdx ].split( '/' ).pop();
  2832. const keyframeTimes = [];
  2833. const keyframeValues = [];
  2834. for ( let t = 0; t < times.length; t ++ ) {
  2835. const transData = values[ t ];
  2836. if ( ! transData || transData.length < ( jointIdx + 1 ) * 3 ) continue;
  2837. keyframeTimes.push( times[ t ] / this.fps );
  2838. keyframeValues.push(
  2839. transData[ jointIdx * 3 + 0 ],
  2840. transData[ jointIdx * 3 + 1 ],
  2841. transData[ jointIdx * 3 + 2 ]
  2842. );
  2843. }
  2844. if ( keyframeTimes.length > 0 ) {
  2845. tracks.push( new VectorKeyframeTrack(
  2846. jointName + '.position',
  2847. new Float32Array( keyframeTimes ),
  2848. new Float32Array( keyframeValues )
  2849. ) );
  2850. }
  2851. }
  2852. }
  2853. // Get scale time samples
  2854. const scalesAttr = this._getTimeSampledAttribute( path, 'scales' );
  2855. if ( scalesAttr && scalesAttr.times && scalesAttr.values ) {
  2856. const { times, values } = scalesAttr;
  2857. for ( let jointIdx = 0; jointIdx < joints.length; jointIdx ++ ) {
  2858. const jointName = joints[ jointIdx ].split( '/' ).pop();
  2859. const keyframeTimes = [];
  2860. const keyframeValues = [];
  2861. for ( let t = 0; t < times.length; t ++ ) {
  2862. const scaleData = values[ t ];
  2863. if ( ! scaleData || scaleData.length < ( jointIdx + 1 ) * 3 ) continue;
  2864. keyframeTimes.push( times[ t ] / this.fps );
  2865. keyframeValues.push(
  2866. scaleData[ jointIdx * 3 + 0 ],
  2867. scaleData[ jointIdx * 3 + 1 ],
  2868. scaleData[ jointIdx * 3 + 2 ]
  2869. );
  2870. }
  2871. if ( keyframeTimes.length > 0 ) {
  2872. tracks.push( new VectorKeyframeTrack(
  2873. jointName + '.scale',
  2874. new Float32Array( keyframeTimes ),
  2875. new Float32Array( keyframeValues )
  2876. ) );
  2877. }
  2878. }
  2879. }
  2880. if ( tracks.length === 0 ) return null;
  2881. const clipName = path.split( '/' ).pop();
  2882. return new AnimationClip( clipName, - 1, tracks );
  2883. }
  2884. _getTimeSampledAttribute( primPath, attrName ) {
  2885. // Look for the attribute spec with time samples
  2886. const attrPath = primPath + '.' + attrName;
  2887. const attrSpec = this.specsByPath[ attrPath ];
  2888. if ( attrSpec && attrSpec.fields.timeSamples ) {
  2889. const timeSamples = attrSpec.fields.timeSamples;
  2890. if ( timeSamples.times && timeSamples.values ) {
  2891. return timeSamples;
  2892. }
  2893. }
  2894. return null;
  2895. }
  2896. _flattenMatrixArray( matrices, numMatrices ) {
  2897. if ( ! matrices || matrices.length === 0 ) return null;
  2898. if ( typeof matrices[ 0 ] === 'number' ) return matrices;
  2899. const flatArray = [];
  2900. for ( let m = 0; m < numMatrices; m ++ ) {
  2901. for ( let row = 0; row < 4; row ++ ) {
  2902. const rowData = matrices[ m * 4 + row ];
  2903. if ( rowData && rowData.length === 4 ) {
  2904. flatArray.push( rowData[ 0 ], rowData[ 1 ], rowData[ 2 ], rowData[ 3 ] );
  2905. } else {
  2906. flatArray.push( row === 0 ? 1 : 0, row === 1 ? 1 : 0, row === 2 ? 1 : 0, row === 3 ? 1 : 0 );
  2907. }
  2908. }
  2909. }
  2910. return flatArray;
  2911. }
  2912. }
  2913. export { USDComposer, SpecType };
粤ICP备19079148号