1
0

USDZLoader.js 18 KB

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