USDZExporter.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. import * as fflate from '../libs/fflate.module.js';
  2. class USDZExporter {
  3. async parse( scene ) {
  4. const files = {};
  5. const modelFileName = 'model.usda';
  6. const geometryFileName = 'geometry.usd';
  7. let output = buildHeader();
  8. const geometries = {};
  9. const materials = {};
  10. const textures = {};
  11. scene.traverse( ( object ) => {
  12. if ( object.isMesh ) {
  13. const geometry = object.geometry;
  14. const material = object.material;
  15. if ( ! ( geometry.uuid in geometries ) ) {
  16. geometries[ geometry.uuid ] = geometry;
  17. }
  18. if ( ! ( material.uuid in materials ) ) {
  19. materials[ material.uuid ] = material;
  20. if ( material.map !== null ) textures[ material.map.uuid ] = material.map;
  21. if ( material.normalMap !== null ) textures[ material.normalMap.uuid ] = material.normalMap;
  22. if ( material.aoMap !== null ) textures[ material.aoMap.uuid ] = material.aoMap;
  23. if ( material.roughnessMap !== null ) textures[ material.roughnessMap.uuid ] = material.roughnessMap;
  24. if ( material.metalnessMap !== null ) textures[ material.metalnessMap.uuid ] = material.metalnessMap;
  25. if ( material.emissiveMap !== null ) textures[ material.emissiveMap.uuid ] = material.emissiveMap;
  26. }
  27. const referencedMesh = `prepend references = @./${geometryFileName}@</Geometry_${ geometry.id }>`;
  28. const referencedMaterial = `rel material:binding = </Materials/Material_${ material.id }>`;
  29. output += buildXform( object, referencedMesh, referencedMaterial );
  30. }
  31. } );
  32. output += buildMaterials( materials );
  33. output += buildTextures( textures );
  34. files[ modelFileName ] = fflate.strToU8( output );
  35. output = null;
  36. files[ geometryFileName ] = fflate.strToU8( buildMeshFileString( geometries ) );
  37. for ( const uuid in textures ) {
  38. const texture = textures[ uuid ];
  39. files[ 'textures/Texture_' + texture.id + '.jpg' ] = await imgToU8( texture.image );
  40. }
  41. // 64 byte alignment
  42. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  43. let offset = 0;
  44. for ( const filename in files ) {
  45. const file = files[ filename ];
  46. const headerSize = 34 + filename.length;
  47. offset += headerSize;
  48. const offsetMod64 = offset & 63;
  49. if ( offsetMod64 !== 4 ) {
  50. const padLength = 64 - offsetMod64;
  51. const padding = new Uint8Array( padLength );
  52. files[ filename ] = [ file, { extra: { 12345: padding } } ];
  53. }
  54. offset = file.length;
  55. }
  56. return fflate.zipSync( files, { level: 0 } );
  57. }
  58. }
  59. async function imgToU8( image ) {
  60. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  61. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  62. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  63. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  64. const scale = 1024 / Math.max( image.width, image.height );
  65. const canvas = document.createElement( 'canvas' );
  66. canvas.width = image.width * Math.min( 1, scale );
  67. canvas.height = image.height * Math.min( 1, scale );
  68. const context = canvas.getContext( '2d' );
  69. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  70. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg', 1 ) );
  71. return new Uint8Array( await blob.arrayBuffer() );
  72. }
  73. }
  74. //
  75. const PRECISION = 7;
  76. function buildHeader() {
  77. return `#usda 1.0
  78. (
  79. customLayerData = {
  80. string creator = "Three.js USDZExporter"
  81. }
  82. metersPerUnit = 1
  83. upAxis = "Y"
  84. )
  85. `;
  86. }
  87. // Xform
  88. function buildXform( object, referencedMesh, referencedMaterial ) {
  89. const name = 'Object_' + object.id;
  90. const transform = buildMatrix( object.matrixWorld );
  91. return `def Xform "${ name }"
  92. (
  93. ${ referencedMesh }
  94. )
  95. {
  96. matrix4d xformOp:transform = ${ transform }
  97. uniform token[] xformOpOrder = ["xformOp:transform"]
  98. ${ referencedMaterial }
  99. }
  100. `;
  101. }
  102. function buildMatrix( matrix ) {
  103. const array = matrix.elements;
  104. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  105. }
  106. function buildMatrixRow( array, offset ) {
  107. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  108. }
  109. // Mesh
  110. function buildMeshFileString( geometries ) {
  111. let output = buildHeader();
  112. for ( const uuid in geometries ) {
  113. const geometry = geometries[ uuid ];
  114. output += buildMeshObject( geometry );
  115. }
  116. return output;
  117. }
  118. function buildMeshObject( geometry ) {
  119. const name = 'Geometry_' + geometry.id;
  120. const mesh = buildMesh( geometry );
  121. return `
  122. def "${name}"
  123. {
  124. ${mesh}
  125. }
  126. `;
  127. }
  128. function buildMesh( geometry ) {
  129. const name = 'Geometry_' + geometry.id;
  130. const attributes = geometry.attributes;
  131. const count = attributes.position.count;
  132. if ( 'uv2' in attributes ) {
  133. console.warn( 'THREE.USDZExporter: uv2 not supported yet.' );
  134. }
  135. return `
  136. def Mesh "${ name }"
  137. {
  138. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  139. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  140. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  141. interpolation = "vertex"
  142. )
  143. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  144. float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
  145. interpolation = "vertex"
  146. )
  147. uniform token subdivisionScheme = "none"
  148. }
  149. `;
  150. }
  151. function buildMeshVertexCount( geometry ) {
  152. const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;
  153. return Array( count / 3 ).fill( 3 ).join( ', ' );
  154. }
  155. function buildMeshVertexIndices( geometry ) {
  156. if ( geometry.index !== null ) {
  157. return geometry.index.array.join( ', ' );
  158. }
  159. const array = [];
  160. const length = geometry.attributes.position.count;
  161. for ( let i = 0; i < length; i ++ ) {
  162. array.push( i );
  163. }
  164. return array.join( ', ' );
  165. }
  166. function buildVector3Array( attribute, count ) {
  167. if ( attribute === undefined ) {
  168. console.warn( 'USDZExporter: Normals missing.' );
  169. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  170. }
  171. const array = [];
  172. const data = attribute.array;
  173. for ( let i = 0; i < data.length; i += 3 ) {
  174. array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ data[ i + 1 ].toPrecision( PRECISION ) }, ${ data[ i + 2 ].toPrecision( PRECISION ) })` );
  175. }
  176. return array.join( ', ' );
  177. }
  178. function buildVector2Array( attribute, count ) {
  179. if ( attribute === undefined ) {
  180. console.warn( 'USDZExporter: UVs missing.' );
  181. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  182. }
  183. const array = [];
  184. const data = attribute.array;
  185. for ( let i = 0; i < data.length; i += 2 ) {
  186. array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ 1 - data[ i + 1 ].toPrecision( PRECISION ) })` );
  187. }
  188. return array.join( ', ' );
  189. }
  190. // Materials
  191. function buildMaterials( materials ) {
  192. const array = [];
  193. for ( const uuid in materials ) {
  194. const material = materials[ uuid ];
  195. array.push( buildMaterial( material ) );
  196. }
  197. return `def "Materials"
  198. {
  199. ${ array.join( '' ) }
  200. }
  201. `;
  202. }
  203. function buildMaterial( material ) {
  204. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  205. const pad = ' ';
  206. const parameters = [];
  207. if ( material.map !== null ) {
  208. parameters.push( `${ pad }color3f inputs:diffuseColor.connect = </Textures/Texture_${ material.map.id }.outputs:rgb>` );
  209. } else {
  210. parameters.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  211. }
  212. if ( material.emissiveMap !== null ) {
  213. parameters.push( `${ pad }color3f inputs:emissiveColor.connect = </Textures/Texture_${ material.emissiveMap.id }.outputs:rgb>` );
  214. } else if ( material.emissive.getHex() > 0 ) {
  215. parameters.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  216. }
  217. if ( material.normalMap !== null ) {
  218. parameters.push( `${ pad }normal3f inputs:normal.connect = </Textures/Texture_${ material.normalMap.id }.outputs:rgb>` );
  219. }
  220. if ( material.aoMap !== null ) {
  221. parameters.push( `${ pad }float inputs:occlusion.connect = </Textures/Texture_${ material.aoMap.id }.outputs:r>` );
  222. }
  223. if ( material.roughnessMap !== null ) {
  224. parameters.push( `${ pad }float inputs:roughness.connect = </Textures/Texture_${ material.roughnessMap.id }.outputs:g>` );
  225. } else {
  226. parameters.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  227. }
  228. if ( material.metalnessMap !== null ) {
  229. parameters.push( `${ pad }float inputs:metallic.connect = </Textures/Texture_${ material.metalnessMap.id }.outputs:b>` );
  230. } else {
  231. parameters.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  232. }
  233. parameters.push( `${ pad }float inputs:opacity = ${ material.opacity }` );
  234. return `
  235. def Material "Material_${ material.id }"
  236. {
  237. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  238. def Shader "PreviewSurface"
  239. {
  240. uniform token info:id = "UsdPreviewSurface"
  241. ${ parameters.join( '\n' ) }
  242. int inputs:useSpecularWorkflow = 0
  243. token outputs:surface
  244. }
  245. }
  246. `;
  247. }
  248. function buildTextures( textures ) {
  249. const array = [];
  250. for ( const uuid in textures ) {
  251. const texture = textures[ uuid ];
  252. array.push( buildTexture( texture ) );
  253. }
  254. return `def "Textures"
  255. {
  256. ${ array.join( '' ) }
  257. }
  258. `;
  259. }
  260. function buildTexture( texture ) {
  261. return `
  262. def Shader "Texture_${ texture.id }"
  263. {
  264. uniform token info:id = "UsdUVTexture"
  265. asset inputs:file = @textures/Texture_${ texture.id }.jpg@
  266. token inputs:wrapS = "repeat"
  267. token inputs:wrapT = "repeat"
  268. float outputs:r
  269. float outputs:g
  270. float outputs:b
  271. float3 outputs:rgb
  272. }
  273. `;
  274. }
  275. function buildColor( color ) {
  276. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  277. }
  278. export { USDZExporter };