USDZExporter.js 11 KB

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