USDZExporter.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import * as THREE from 'three';
  2. import * as fflate from '../libs/fflate.module.js';
  3. class USDZExporter {
  4. async parse( scene, options = {} ) {
  5. options = Object.assign( {
  6. ar: {
  7. anchoring: { type: 'plane' },
  8. planeAnchoring: { alignment: 'horizontal' }
  9. },
  10. quickLookCompatible: false,
  11. }, options );
  12. const files = {};
  13. const modelFileName = 'model.usda';
  14. // model file should be first in USDZ archive so we init it here
  15. files[ modelFileName ] = null;
  16. let output = buildHeader();
  17. output += buildSceneStart( options );
  18. const materials = {};
  19. const textures = {};
  20. scene.traverseVisible( ( object ) => {
  21. if ( object.isMesh ) {
  22. const geometry = object.geometry;
  23. const material = object.material;
  24. if ( material.isMeshStandardMaterial ) {
  25. const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usda';
  26. if ( ! ( geometryFileName in files ) ) {
  27. const meshObject = buildMeshObject( geometry );
  28. files[ geometryFileName ] = buildUSDFileAsString( meshObject );
  29. }
  30. if ( ! ( material.uuid in materials ) ) {
  31. materials[ material.uuid ] = material;
  32. }
  33. output += buildXform( object, geometry, material );
  34. } else {
  35. console.warn( 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)', object );
  36. }
  37. } else if ( object.isCamera ) {
  38. output += buildCamera( object );
  39. }
  40. } );
  41. output += buildSceneEnd();
  42. output += buildMaterials( materials, textures, options.quickLookCompatible );
  43. files[ modelFileName ] = fflate.strToU8( output );
  44. output = null;
  45. for ( const id in textures ) {
  46. const texture = textures[ id ];
  47. const canvas = imageToCanvas( texture.image, texture.flipY );
  48. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/png', 1 ) );
  49. files[ `textures/Texture_${ id }.png` ] = new Uint8Array( await blob.arrayBuffer() );
  50. }
  51. // 64 byte alignment
  52. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  53. let offset = 0;
  54. for ( const filename in files ) {
  55. const file = files[ filename ];
  56. const headerSize = 34 + filename.length;
  57. offset += headerSize;
  58. const offsetMod64 = offset & 63;
  59. if ( offsetMod64 !== 4 ) {
  60. const padLength = 64 - offsetMod64;
  61. const padding = new Uint8Array( padLength );
  62. files[ filename ] = [ file, { extra: { 12345: padding } } ];
  63. }
  64. offset = file.length;
  65. }
  66. return fflate.zipSync( files, { level: 0 } );
  67. }
  68. }
  69. function imageToCanvas( image, flipY ) {
  70. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  71. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  72. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  73. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  74. const scale = 1024 / Math.max( image.width, image.height );
  75. const canvas = document.createElement( 'canvas' );
  76. canvas.width = image.width * Math.min( 1, scale );
  77. canvas.height = image.height * Math.min( 1, scale );
  78. const context = canvas.getContext( '2d' );
  79. // TODO: We should be able to do this in the UsdTransform2d?
  80. if ( flipY === true ) {
  81. context.translate( 0, canvas.height );
  82. context.scale( 1, - 1 );
  83. }
  84. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  85. return canvas;
  86. } else {
  87. throw new Error( 'THREE.USDZExporter: No valid image data found. Unable to process texture.' );
  88. }
  89. }
  90. //
  91. const PRECISION = 7;
  92. function buildHeader() {
  93. return `#usda 1.0
  94. (
  95. customLayerData = {
  96. string creator = "Three.js USDZExporter"
  97. }
  98. metersPerUnit = 1
  99. upAxis = "Y"
  100. )
  101. `;
  102. }
  103. function buildSceneStart( options ) {
  104. return `def Xform "Root"
  105. {
  106. def Scope "Scenes" (
  107. kind = "sceneLibrary"
  108. )
  109. {
  110. def Xform "Scene" (
  111. customData = {
  112. bool preliminary_collidesWithEnvironment = 0
  113. string sceneName = "Scene"
  114. }
  115. sceneName = "Scene"
  116. )
  117. {
  118. token preliminary:anchoring:type = "${options.ar.anchoring.type}"
  119. token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}"
  120. `;
  121. }
  122. function buildSceneEnd() {
  123. return `
  124. }
  125. }
  126. }
  127. `;
  128. }
  129. function buildUSDFileAsString( dataToInsert ) {
  130. let output = buildHeader();
  131. output += dataToInsert;
  132. return fflate.strToU8( output );
  133. }
  134. // Xform
  135. function buildXform( object, geometry, material ) {
  136. const name = 'Object_' + object.id;
  137. const transform = buildMatrix( object.matrixWorld );
  138. if ( object.matrixWorld.determinant() < 0 ) {
  139. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object );
  140. }
  141. return `def Xform "${ name }" (
  142. prepend references = @./geometries/Geometry_${ geometry.id }.usda@</Geometry>
  143. prepend apiSchemas = ["MaterialBindingAPI"]
  144. )
  145. {
  146. matrix4d xformOp:transform = ${ transform }
  147. uniform token[] xformOpOrder = ["xformOp:transform"]
  148. rel material:binding = </Materials/Material_${ material.id }>
  149. }
  150. `;
  151. }
  152. function buildMatrix( matrix ) {
  153. const array = matrix.elements;
  154. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  155. }
  156. function buildMatrixRow( array, offset ) {
  157. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  158. }
  159. // Mesh
  160. function buildMeshObject( geometry ) {
  161. const mesh = buildMesh( geometry );
  162. return `
  163. def "Geometry"
  164. {
  165. ${mesh}
  166. }
  167. `;
  168. }
  169. function buildMesh( geometry ) {
  170. const name = 'Geometry';
  171. const attributes = geometry.attributes;
  172. const count = attributes.position.count;
  173. return `
  174. def Mesh "${ name }"
  175. {
  176. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  177. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  178. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  179. interpolation = "vertex"
  180. )
  181. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  182. ${ buildPrimvars( attributes, count ) }
  183. uniform token subdivisionScheme = "none"
  184. }
  185. `;
  186. }
  187. function buildMeshVertexCount( geometry ) {
  188. const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count;
  189. return Array( count / 3 ).fill( 3 ).join( ', ' );
  190. }
  191. function buildMeshVertexIndices( geometry ) {
  192. const index = geometry.index;
  193. const array = [];
  194. if ( index !== null ) {
  195. for ( let i = 0; i < index.count; i ++ ) {
  196. array.push( index.getX( i ) );
  197. }
  198. } else {
  199. const length = geometry.attributes.position.count;
  200. for ( let i = 0; i < length; i ++ ) {
  201. array.push( i );
  202. }
  203. }
  204. return array.join( ', ' );
  205. }
  206. function buildVector3Array( attribute, count ) {
  207. if ( attribute === undefined ) {
  208. console.warn( 'USDZExporter: Normals missing.' );
  209. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  210. }
  211. const array = [];
  212. for ( let i = 0; i < attribute.count; i ++ ) {
  213. const x = attribute.getX( i );
  214. const y = attribute.getY( i );
  215. const z = attribute.getZ( i );
  216. array.push( `(${ x.toPrecision( PRECISION ) }, ${ y.toPrecision( PRECISION ) }, ${ z.toPrecision( PRECISION ) })` );
  217. }
  218. return array.join( ', ' );
  219. }
  220. function buildVector2Array( attribute, count ) {
  221. if ( attribute === undefined ) {
  222. console.warn( 'USDZExporter: UVs missing.' );
  223. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  224. }
  225. const array = [];
  226. for ( let i = 0; i < attribute.count; i ++ ) {
  227. const x = attribute.getX( i );
  228. const y = attribute.getY( i );
  229. array.push( `(${ x.toPrecision( PRECISION ) }, ${ 1 - y.toPrecision( PRECISION ) })` );
  230. }
  231. return array.join( ', ' );
  232. }
  233. function buildPrimvars( attributes, count ) {
  234. let string = '';
  235. for ( let i = 0; i < 4; i ++ ) {
  236. const id = ( i > 0 ? i : '' );
  237. const attribute = attributes[ 'uv' + id ];
  238. if ( attribute !== undefined ) {
  239. string += `
  240. texCoord2f[] primvars:st${ id } = [${ buildVector2Array( attribute, count )}] (
  241. interpolation = "vertex"
  242. )`;
  243. }
  244. }
  245. return string;
  246. }
  247. // Materials
  248. function buildMaterials( materials, textures, quickLookCompatible = false ) {
  249. const array = [];
  250. for ( const uuid in materials ) {
  251. const material = materials[ uuid ];
  252. array.push( buildMaterial( material, textures, quickLookCompatible ) );
  253. }
  254. return `def "Materials"
  255. {
  256. ${ array.join( '' ) }
  257. }
  258. `;
  259. }
  260. function buildMaterial( material, textures, quickLookCompatible = false ) {
  261. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  262. const pad = ' ';
  263. const inputs = [];
  264. const samplers = [];
  265. function buildTexture( texture, mapType, color ) {
  266. const id = texture.source.id + '_' + texture.flipY;
  267. textures[ id ] = texture;
  268. const uv = texture.channel > 0 ? 'st' + texture.channel : 'st';
  269. const WRAPPINGS = {
  270. 1000: 'repeat', // RepeatWrapping
  271. 1001: 'clamp', // ClampToEdgeWrapping
  272. 1002: 'mirror' // MirroredRepeatWrapping
  273. };
  274. const repeat = texture.repeat.clone();
  275. const offset = texture.offset.clone();
  276. const rotation = texture.rotation;
  277. // rotation is around the wrong point. after rotation we need to shift offset again so that we're rotating around the right spot
  278. const xRotationOffset = Math.sin( rotation );
  279. const yRotationOffset = Math.cos( rotation );
  280. // texture coordinates start in the opposite corner, need to correct
  281. offset.y = 1 - offset.y - repeat.y;
  282. // turns out QuickLook is buggy and interprets texture repeat inverted/applies operations in a different order.
  283. // Apple Feedback: FB10036297 and FB11442287
  284. if ( quickLookCompatible ) {
  285. // This is NOT correct yet in QuickLook, but comes close for a range of models.
  286. // It becomes more incorrect the bigger the offset is
  287. offset.x = offset.x / repeat.x;
  288. offset.y = offset.y / repeat.y;
  289. offset.x += xRotationOffset / repeat.x;
  290. offset.y += yRotationOffset - 1;
  291. } else {
  292. // results match glTF results exactly. verified correct in usdview.
  293. offset.x += xRotationOffset * repeat.x;
  294. offset.y += ( 1 - yRotationOffset ) * repeat.y;
  295. }
  296. return `
  297. def Shader "PrimvarReader_${ mapType }"
  298. {
  299. uniform token info:id = "UsdPrimvarReader_float2"
  300. float2 inputs:fallback = (0.0, 0.0)
  301. token inputs:varname = "${ uv }"
  302. float2 outputs:result
  303. }
  304. def Shader "Transform2d_${ mapType }"
  305. {
  306. uniform token info:id = "UsdTransform2d"
  307. token inputs:in.connect = </Materials/Material_${ material.id }/PrimvarReader_${ mapType }.outputs:result>
  308. float inputs:rotation = ${ ( rotation * ( 180 / Math.PI ) ).toFixed( PRECISION ) }
  309. float2 inputs:scale = ${ buildVector2( repeat ) }
  310. float2 inputs:translation = ${ buildVector2( offset ) }
  311. float2 outputs:result
  312. }
  313. def Shader "Texture_${ texture.id }_${ mapType }"
  314. {
  315. uniform token info:id = "UsdUVTexture"
  316. asset inputs:file = @textures/Texture_${ id }.png@
  317. float2 inputs:st.connect = </Materials/Material_${ material.id }/Transform2d_${ mapType }.outputs:result>
  318. ${ color !== undefined ? 'float4 inputs:scale = ' + buildColor4( color ) : '' }
  319. token inputs:sourceColorSpace = "${ texture.colorSpace === THREE.NoColorSpace ? 'raw' : 'sRGB' }"
  320. token inputs:wrapS = "${ WRAPPINGS[ texture.wrapS ] }"
  321. token inputs:wrapT = "${ WRAPPINGS[ texture.wrapT ] }"
  322. float outputs:r
  323. float outputs:g
  324. float outputs:b
  325. float3 outputs:rgb
  326. ${ material.transparent || material.alphaTest > 0.0 ? 'float outputs:a' : '' }
  327. }`;
  328. }
  329. if ( material.side === THREE.DoubleSide ) {
  330. console.warn( 'THREE.USDZExporter: USDZ does not support double sided materials', material );
  331. }
  332. if ( material.map !== null ) {
  333. inputs.push( `${ pad }color3f inputs:diffuseColor.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:rgb>` );
  334. if ( material.transparent ) {
  335. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  336. } else if ( material.alphaTest > 0.0 ) {
  337. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  338. inputs.push( `${ pad }float inputs:opacityThreshold = ${material.alphaTest}` );
  339. }
  340. samplers.push( buildTexture( material.map, 'diffuse', material.color ) );
  341. } else {
  342. inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  343. }
  344. if ( material.emissiveMap !== null ) {
  345. inputs.push( `${ pad }color3f inputs:emissiveColor.connect = </Materials/Material_${ material.id }/Texture_${ material.emissiveMap.id }_emissive.outputs:rgb>` );
  346. samplers.push( buildTexture( material.emissiveMap, 'emissive' ) );
  347. } else if ( material.emissive.getHex() > 0 ) {
  348. inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  349. }
  350. if ( material.normalMap !== null ) {
  351. inputs.push( `${ pad }normal3f inputs:normal.connect = </Materials/Material_${ material.id }/Texture_${ material.normalMap.id }_normal.outputs:rgb>` );
  352. samplers.push( buildTexture( material.normalMap, 'normal' ) );
  353. }
  354. if ( material.aoMap !== null ) {
  355. inputs.push( `${ pad }float inputs:occlusion.connect = </Materials/Material_${ material.id }/Texture_${ material.aoMap.id }_occlusion.outputs:r>` );
  356. samplers.push( buildTexture( material.aoMap, 'occlusion' ) );
  357. }
  358. if ( material.roughnessMap !== null && material.roughness === 1 ) {
  359. inputs.push( `${ pad }float inputs:roughness.connect = </Materials/Material_${ material.id }/Texture_${ material.roughnessMap.id }_roughness.outputs:g>` );
  360. samplers.push( buildTexture( material.roughnessMap, 'roughness' ) );
  361. } else {
  362. inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  363. }
  364. if ( material.metalnessMap !== null && material.metalness === 1 ) {
  365. inputs.push( `${ pad }float inputs:metallic.connect = </Materials/Material_${ material.id }/Texture_${ material.metalnessMap.id }_metallic.outputs:b>` );
  366. samplers.push( buildTexture( material.metalnessMap, 'metallic' ) );
  367. } else {
  368. inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  369. }
  370. if ( material.alphaMap !== null ) {
  371. inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
  372. inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
  373. samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
  374. } else {
  375. inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
  376. }
  377. if ( material.isMeshPhysicalMaterial ) {
  378. inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` );
  379. inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` );
  380. inputs.push( `${ pad }float inputs:ior = ${ material.ior }` );
  381. }
  382. return `
  383. def Material "Material_${ material.id }"
  384. {
  385. def Shader "PreviewSurface"
  386. {
  387. uniform token info:id = "UsdPreviewSurface"
  388. ${ inputs.join( '\n' ) }
  389. int inputs:useSpecularWorkflow = 0
  390. token outputs:surface
  391. }
  392. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  393. ${ samplers.join( '\n' ) }
  394. }
  395. `;
  396. }
  397. function buildColor( color ) {
  398. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  399. }
  400. function buildColor4( color ) {
  401. return `(${ color.r }, ${ color.g }, ${ color.b }, 1.0)`;
  402. }
  403. function buildVector2( vector ) {
  404. return `(${ vector.x }, ${ vector.y })`;
  405. }
  406. function buildCamera( camera ) {
  407. const name = camera.name ? camera.name : 'Camera_' + camera.id;
  408. const transform = buildMatrix( camera.matrixWorld );
  409. if ( camera.matrixWorld.determinant() < 0 ) {
  410. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', camera );
  411. }
  412. if ( camera.isOrthographicCamera ) {
  413. return `def Camera "${name}"
  414. {
  415. matrix4d xformOp:transform = ${ transform }
  416. uniform token[] xformOpOrder = ["xformOp:transform"]
  417. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  418. float horizontalAperture = ${ ( ( Math.abs( camera.left ) + Math.abs( camera.right ) ) * 10 ).toPrecision( PRECISION ) }
  419. float verticalAperture = ${ ( ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) * 10 ).toPrecision( PRECISION ) }
  420. token projection = "orthographic"
  421. }
  422. `;
  423. } else {
  424. return `def Camera "${name}"
  425. {
  426. matrix4d xformOp:transform = ${ transform }
  427. uniform token[] xformOpOrder = ["xformOp:transform"]
  428. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  429. float focalLength = ${ camera.getFocalLength().toPrecision( PRECISION ) }
  430. float focusDistance = ${ camera.focus.toPrecision( PRECISION ) }
  431. float horizontalAperture = ${ camera.getFilmWidth().toPrecision( PRECISION ) }
  432. token projection = "perspective"
  433. float verticalAperture = ${ camera.getFilmHeight().toPrecision( PRECISION ) }
  434. }
  435. `;
  436. }
  437. }
  438. export { USDZExporter };