USDZLoader.js 15 KB

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