USDZLoader.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. ClampToEdgeWrapping,
  5. FileLoader,
  6. Group,
  7. NoColorSpace,
  8. Loader,
  9. Mesh,
  10. MeshPhysicalMaterial,
  11. MirroredRepeatWrapping,
  12. RepeatWrapping,
  13. SRGBColorSpace,
  14. TextureLoader,
  15. Object3D,
  16. Vector2
  17. } from 'three';
  18. import * as fflate from '../libs/fflate.module.js';
  19. class USDAParser {
  20. parse( text ) {
  21. const data = {};
  22. const lines = text.split( '\n' );
  23. let string = null;
  24. let target = data;
  25. const stack = [ data ];
  26. // debugger;
  27. for ( const line of lines ) {
  28. // console.log( line );
  29. if ( line.includes( '=' ) ) {
  30. const assignment = line.split( '=' );
  31. const lhs = assignment[ 0 ].trim();
  32. const rhs = assignment[ 1 ].trim();
  33. if ( rhs.endsWith( '{' ) ) {
  34. const group = {};
  35. stack.push( group );
  36. target[ lhs ] = group;
  37. target = group;
  38. } else {
  39. target[ lhs ] = rhs;
  40. }
  41. } else if ( line.endsWith( '{' ) ) {
  42. const group = target[ string ] || {};
  43. stack.push( group );
  44. target[ string ] = group;
  45. target = group;
  46. } else if ( line.endsWith( '}' ) ) {
  47. stack.pop();
  48. if ( stack.length === 0 ) continue;
  49. target = stack[ stack.length - 1 ];
  50. } else if ( line.endsWith( '(' ) ) {
  51. const meta = {};
  52. stack.push( meta );
  53. string = line.split( '(' )[ 0 ].trim() || string;
  54. target[ string ] = meta;
  55. target = meta;
  56. } else if ( line.endsWith( ')' ) ) {
  57. stack.pop();
  58. target = stack[ stack.length - 1 ];
  59. } else {
  60. string = line.trim();
  61. }
  62. }
  63. return data;
  64. }
  65. }
  66. class USDZLoader extends Loader {
  67. constructor( manager ) {
  68. super( manager );
  69. }
  70. load( url, onLoad, onProgress, onError ) {
  71. const scope = this;
  72. const loader = new FileLoader( scope.manager );
  73. loader.setPath( scope.path );
  74. loader.setResponseType( 'arraybuffer' );
  75. loader.setRequestHeader( scope.requestHeader );
  76. loader.setWithCredentials( scope.withCredentials );
  77. loader.load( url, function ( text ) {
  78. try {
  79. onLoad( scope.parse( text ) );
  80. } catch ( e ) {
  81. if ( onError ) {
  82. onError( e );
  83. } else {
  84. console.error( e );
  85. }
  86. scope.manager.itemError( url );
  87. }
  88. }, onProgress, onError );
  89. }
  90. parse( buffer ) {
  91. const parser = new USDAParser();
  92. function parseAssets( zip ) {
  93. const data = {};
  94. const loader = new FileLoader();
  95. loader.setResponseType( 'arraybuffer' );
  96. for ( const filename in zip ) {
  97. if ( filename.endsWith( 'png' ) ) {
  98. const blob = new Blob( [ zip[ filename ] ], { type: { type: 'image/png' } } );
  99. data[ filename ] = URL.createObjectURL( blob );
  100. }
  101. if ( filename.endsWith( 'usd' ) || filename.endsWith( 'usda' ) ) {
  102. if ( isCrateFile( zip[ filename ] ) ) {
  103. console.warn( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
  104. continue;
  105. }
  106. const text = fflate.strFromU8( zip[ filename ] );
  107. data[ filename ] = parser.parse( text );
  108. }
  109. }
  110. return data;
  111. }
  112. function isCrateFile( buffer ) {
  113. // Check if this a crate file. First 7 bytes of a crate file are "PXR-USDC".
  114. const fileHeader = buffer.slice( 0, 7 );
  115. const crateHeader = new Uint8Array( [ 0x50, 0x58, 0x52, 0x2D, 0x55, 0x53, 0x44, 0x43 ] );
  116. // If this is not a crate file, we assume it is a plain USDA file.
  117. return fileHeader.every( ( value, index ) => value === crateHeader[ index ] );
  118. }
  119. function findUSD( zip ) {
  120. if ( zip.length < 1 ) return undefined;
  121. const firstFileName = Object.keys( zip )[ 0 ];
  122. let isCrate = false;
  123. // As per the USD specification, the first entry in the zip archive is used as the main file ("UsdStage").
  124. // ASCII files can end in either .usda or .usd.
  125. // See https://openusd.org/release/spec_usdz.html#layout
  126. if ( firstFileName.endsWith( 'usda' ) ) return zip[ firstFileName ];
  127. if ( firstFileName.endsWith( 'usdc' ) ) {
  128. isCrate = true;
  129. } else if ( firstFileName.endsWith( 'usd' ) ) {
  130. // If this is not a crate file, we assume it is a plain USDA file.
  131. if ( ! isCrateFile( zip[ firstFileName ] ) ) {
  132. return zip[ firstFileName ];
  133. } else {
  134. isCrate = true;
  135. }
  136. }
  137. if ( isCrate ) {
  138. console.warn( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
  139. }
  140. return undefined;
  141. }
  142. const zip = fflate.unzipSync( new Uint8Array( buffer ) );
  143. // console.log( zip );
  144. const assets = parseAssets( zip );
  145. // console.log( assets )
  146. const file = findUSD( zip );
  147. if ( file === undefined ) {
  148. console.warn( 'THREE.USDZLoader: No usda file found.' );
  149. return new Group();
  150. }
  151. // Parse file
  152. const text = fflate.strFromU8( file );
  153. const root = parser.parse( text );
  154. // Build scene
  155. function findMeshGeometry( data ) {
  156. if ( ! data ) return undefined;
  157. if ( 'prepend references' in data ) {
  158. const reference = data[ 'prepend references' ];
  159. const parts = reference.split( '@' );
  160. const path = parts[ 1 ].replace( /^.\//, '' );
  161. const id = parts[ 2 ].replace( /^<\//, '' ).replace( />$/, '' );
  162. return findGeometry( assets[ path ], id );
  163. }
  164. return findGeometry( data );
  165. }
  166. function findGeometry( data, id ) {
  167. if ( ! data ) return undefined;
  168. if ( id !== undefined ) {
  169. const def = `def Mesh "${id}"`;
  170. if ( def in data ) {
  171. return data[ def ];
  172. }
  173. }
  174. for ( const name in data ) {
  175. const object = data[ name ];
  176. if ( name.startsWith( 'def Mesh' ) ) {
  177. // Move points to Mesh
  178. if ( 'point3f[] points' in data ) {
  179. object[ 'point3f[] points' ] = data[ 'point3f[] points' ];
  180. }
  181. // Move st to Mesh
  182. if ( 'texCoord2f[] primvars:st' in data ) {
  183. object[ 'texCoord2f[] primvars:st' ] = data[ 'texCoord2f[] primvars:st' ];
  184. }
  185. // Move st indices to Mesh
  186. if ( 'int[] primvars:st:indices' in data ) {
  187. object[ 'int[] primvars:st:indices' ] = data[ 'int[] primvars:st:indices' ];
  188. }
  189. return object;
  190. }
  191. if ( typeof object === 'object' ) {
  192. const geometry = findGeometry( object );
  193. if ( geometry ) return geometry;
  194. }
  195. }
  196. }
  197. function buildGeometry( data ) {
  198. if ( ! data ) return undefined;
  199. let geometry = new BufferGeometry();
  200. if ( 'int[] faceVertexIndices' in data ) {
  201. const indices = JSON.parse( data[ 'int[] faceVertexIndices' ] );
  202. geometry.setIndex( indices );
  203. }
  204. if ( 'point3f[] points' in data ) {
  205. const positions = JSON.parse( data[ 'point3f[] points' ].replace( /[()]*/g, '' ) );
  206. const attribute = new BufferAttribute( new Float32Array( positions ), 3 );
  207. geometry.setAttribute( 'position', attribute );
  208. }
  209. if ( 'normal3f[] normals' in data ) {
  210. const normals = JSON.parse( data[ 'normal3f[] normals' ].replace( /[()]*/g, '' ) );
  211. const attribute = new BufferAttribute( new Float32Array( normals ), 3 );
  212. geometry.setAttribute( 'normal', attribute );
  213. } else {
  214. geometry.computeVertexNormals();
  215. }
  216. if ( 'float2[] primvars:st' in data ) {
  217. data[ 'texCoord2f[] primvars:st' ] = data[ 'float2[] primvars:st' ];
  218. }
  219. if ( 'texCoord2f[] primvars:st' in data ) {
  220. const uvs = JSON.parse( data[ 'texCoord2f[] primvars:st' ].replace( /[()]*/g, '' ) );
  221. const attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
  222. if ( 'int[] primvars:st:indices' in data ) {
  223. geometry = geometry.toNonIndexed();
  224. const indices = JSON.parse( data[ 'int[] primvars:st:indices' ] );
  225. geometry.setAttribute( 'uv', toFlatBufferAttribute( attribute, indices ) );
  226. } else {
  227. geometry.setAttribute( 'uv', attribute );
  228. }
  229. }
  230. return geometry;
  231. }
  232. function toFlatBufferAttribute( attribute, indices ) {
  233. const array = attribute.array;
  234. const itemSize = attribute.itemSize;
  235. const array2 = new array.constructor( indices.length * itemSize );
  236. let index = 0, index2 = 0;
  237. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  238. index = indices[ i ] * itemSize;
  239. for ( let j = 0; j < itemSize; j ++ ) {
  240. array2[ index2 ++ ] = array[ index ++ ];
  241. }
  242. }
  243. return new BufferAttribute( array2, itemSize );
  244. }
  245. function findMeshMaterial( data ) {
  246. if ( ! data ) return undefined;
  247. if ( 'rel material:binding' in data ) {
  248. const reference = data[ 'rel material:binding' ];
  249. const id = reference.replace( /^<\//, '' ).replace( />$/, '' );
  250. const parts = id.split( '/' );
  251. return findMaterial( root, ` "${ parts[ 1 ] }"` );
  252. }
  253. return findMaterial( data );
  254. }
  255. function findMaterial( data, id = '' ) {
  256. for ( const name in data ) {
  257. const object = data[ name ];
  258. if ( name.startsWith( 'def Material' + id ) ) {
  259. return object;
  260. }
  261. if ( typeof object === 'object' ) {
  262. const material = findMaterial( object, id );
  263. if ( material ) return material;
  264. }
  265. }
  266. }
  267. function setTextureParams( map, data_value ) {
  268. // rotation, scale and translation
  269. if ( data_value[ 'float inputs:rotation' ] ) {
  270. map.rotation = parseFloat( data_value[ 'float inputs:rotation' ] );
  271. }
  272. if ( data_value[ 'float2 inputs:scale' ] ) {
  273. map.repeat = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:scale' ].replace( /[()]*/g, '' ) + ']' ) );
  274. }
  275. if ( data_value[ 'float2 inputs:translation' ] ) {
  276. map.offset = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:translation' ].replace( /[()]*/g, '' ) + ']' ) );
  277. }
  278. }
  279. function buildMaterial( data ) {
  280. const material = new MeshPhysicalMaterial();
  281. if ( data !== undefined ) {
  282. if ( 'def Shader "PreviewSurface"' in data ) {
  283. const surface = data[ 'def Shader "PreviewSurface"' ];
  284. if ( 'color3f inputs:diffuseColor.connect' in surface ) {
  285. const path = surface[ 'color3f inputs:diffuseColor.connect' ];
  286. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  287. material.map = buildTexture( sampler );
  288. material.map.colorSpace = SRGBColorSpace;
  289. if ( 'def Shader "Transform2d_diffuse"' in data ) {
  290. setTextureParams( material.map, data[ 'def Shader "Transform2d_diffuse"' ] );
  291. }
  292. } else if ( 'color3f inputs:diffuseColor' in surface ) {
  293. const color = surface[ 'color3f inputs:diffuseColor' ].replace( /[()]*/g, '' );
  294. material.color.fromArray( JSON.parse( '[' + color + ']' ) );
  295. }
  296. if ( 'color3f inputs:emissiveColor.connect' in surface ) {
  297. const path = surface[ 'color3f inputs:emissiveColor.connect' ];
  298. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  299. material.emissiveMap = buildTexture( sampler );
  300. material.emissiveMap.colorSpace = SRGBColorSpace;
  301. material.emissive.set( 0xffffff );
  302. if ( 'def Shader "Transform2d_emissive"' in data ) {
  303. setTextureParams( material.emissiveMap, data[ 'def Shader "Transform2d_emissive"' ] );
  304. }
  305. } else if ( 'color3f inputs:emissiveColor' in surface ) {
  306. const color = surface[ 'color3f inputs:emissiveColor' ].replace( /[()]*/g, '' );
  307. material.emissive.fromArray( JSON.parse( '[' + color + ']' ) );
  308. }
  309. if ( 'normal3f inputs:normal.connect' in surface ) {
  310. const path = surface[ 'normal3f inputs:normal.connect' ];
  311. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  312. material.normalMap = buildTexture( sampler );
  313. material.normalMap.colorSpace = NoColorSpace;
  314. if ( 'def Shader "Transform2d_normal"' in data ) {
  315. setTextureParams( material.normalMap, data[ 'def Shader "Transform2d_normal"' ] );
  316. }
  317. }
  318. if ( 'float inputs:roughness.connect' in surface ) {
  319. const path = surface[ 'float inputs:roughness.connect' ];
  320. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  321. material.roughness = 1.0;
  322. material.roughnessMap = buildTexture( sampler );
  323. material.roughnessMap.colorSpace = NoColorSpace;
  324. if ( 'def Shader "Transform2d_roughness"' in data ) {
  325. setTextureParams( material.roughnessMap, data[ 'def Shader "Transform2d_roughness"' ] );
  326. }
  327. } else if ( 'float inputs:roughness' in surface ) {
  328. material.roughness = parseFloat( surface[ 'float inputs:roughness' ] );
  329. }
  330. if ( 'float inputs:metallic.connect' in surface ) {
  331. const path = surface[ 'float inputs:metallic.connect' ];
  332. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  333. material.metalness = 1.0;
  334. material.metalnessMap = buildTexture( sampler );
  335. material.metalnessMap.colorSpace = NoColorSpace;
  336. if ( 'def Shader "Transform2d_metallic"' in data ) {
  337. setTextureParams( material.metalnessMap, data[ 'def Shader "Transform2d_metallic"' ] );
  338. }
  339. } else if ( 'float inputs:metallic' in surface ) {
  340. material.metalness = parseFloat( surface[ 'float inputs:metallic' ] );
  341. }
  342. if ( 'float inputs:clearcoat.connect' in surface ) {
  343. const path = surface[ 'float inputs:clearcoat.connect' ];
  344. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  345. material.clearcoat = 1.0;
  346. material.clearcoatMap = buildTexture( sampler );
  347. material.clearcoatMap.colorSpace = NoColorSpace;
  348. if ( 'def Shader "Transform2d_clearcoat"' in data ) {
  349. setTextureParams( material.clearcoatMap, data[ 'def Shader "Transform2d_clearcoat"' ] );
  350. }
  351. } else if ( 'float inputs:clearcoat' in surface ) {
  352. material.clearcoat = parseFloat( surface[ 'float inputs:clearcoat' ] );
  353. }
  354. if ( 'float inputs:clearcoatRoughness.connect' in surface ) {
  355. const path = surface[ 'float inputs:clearcoatRoughness.connect' ];
  356. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  357. material.clearcoatRoughness = 1.0;
  358. material.clearcoatRoughnessMap = buildTexture( sampler );
  359. material.clearcoatRoughnessMap.colorSpace = NoColorSpace;
  360. if ( 'def Shader "Transform2d_clearcoatRoughness"' in data ) {
  361. setTextureParams( material.clearcoatRoughnessMap, data[ 'def Shader "Transform2d_clearcoatRoughness"' ] );
  362. }
  363. } else if ( 'float inputs:clearcoatRoughness' in surface ) {
  364. material.clearcoatRoughness = parseFloat( surface[ 'float inputs:clearcoatRoughness' ] );
  365. }
  366. if ( 'float inputs:ior' in surface ) {
  367. material.ior = parseFloat( surface[ 'float inputs:ior' ] );
  368. }
  369. if ( 'float inputs:occlusion.connect' in surface ) {
  370. const path = surface[ 'float inputs:occlusion.connect' ];
  371. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  372. material.aoMap = buildTexture( sampler );
  373. material.aoMap.colorSpace = NoColorSpace;
  374. if ( 'def Shader "Transform2d_occlusion"' in data ) {
  375. setTextureParams( material.aoMap, data[ 'def Shader "Transform2d_occlusion"' ] );
  376. }
  377. }
  378. }
  379. if ( 'def Shader "diffuseColor_texture"' in data ) {
  380. const sampler = data[ 'def Shader "diffuseColor_texture"' ];
  381. material.map = buildTexture( sampler );
  382. material.map.colorSpace = SRGBColorSpace;
  383. }
  384. if ( 'def Shader "normal_texture"' in data ) {
  385. const sampler = data[ 'def Shader "normal_texture"' ];
  386. material.normalMap = buildTexture( sampler );
  387. material.normalMap.colorSpace = NoColorSpace;
  388. }
  389. }
  390. return material;
  391. }
  392. function findTexture( data, id ) {
  393. for ( const name in data ) {
  394. const object = data[ name ];
  395. if ( name.startsWith( `def Shader "${ id }"` ) ) {
  396. return object;
  397. }
  398. if ( typeof object === 'object' ) {
  399. const texture = findTexture( object, id );
  400. if ( texture ) return texture;
  401. }
  402. }
  403. }
  404. function buildTexture( data ) {
  405. if ( 'asset inputs:file' in data ) {
  406. const path = data[ 'asset inputs:file' ].replace( /@*/g, '' );
  407. const loader = new TextureLoader();
  408. const texture = loader.load( assets[ path ] );
  409. const map = {
  410. '"clamp"': ClampToEdgeWrapping,
  411. '"mirror"': MirroredRepeatWrapping,
  412. '"repeat"': RepeatWrapping
  413. };
  414. if ( 'token inputs:wrapS' in data ) {
  415. texture.wrapS = map[ data[ 'token inputs:wrapS' ] ];
  416. }
  417. if ( 'token inputs:wrapT' in data ) {
  418. texture.wrapT = map[ data[ 'token inputs:wrapT' ] ];
  419. }
  420. return texture;
  421. }
  422. return null;
  423. }
  424. function buildObject( data ) {
  425. const geometry = buildGeometry( findMeshGeometry( data ) );
  426. const material = buildMaterial( findMeshMaterial( data ) );
  427. const mesh = geometry ? new Mesh( geometry, material ) : new Object3D();
  428. if ( 'matrix4d xformOp:transform' in data ) {
  429. const array = JSON.parse( '[' + data[ 'matrix4d xformOp:transform' ].replace( /[()]*/g, '' ) + ']' );
  430. mesh.matrix.fromArray( array );
  431. mesh.matrix.decompose( mesh.position, mesh.quaternion, mesh.scale );
  432. }
  433. return mesh;
  434. }
  435. function buildHierarchy( data, group ) {
  436. for ( const name in data ) {
  437. if ( name.startsWith( 'def Scope' ) ) {
  438. buildHierarchy( data[ name ], group );
  439. } else if ( name.startsWith( 'def Xform' ) ) {
  440. const mesh = buildObject( data[ name ] );
  441. if ( /def Xform "(\w+)"/.test( name ) ) {
  442. mesh.name = /def Xform "(\w+)"/.exec( name )[ 1 ];
  443. }
  444. group.add( mesh );
  445. buildHierarchy( data[ name ], mesh );
  446. }
  447. }
  448. }
  449. const group = new Group();
  450. buildHierarchy( root, group );
  451. return group;
  452. }
  453. }
  454. export { USDZLoader };