USDZExporter.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 ) {
  13. if ( object.material.isMeshStandardMaterial ) {
  14. const geometry = object.geometry;
  15. const material = object.material;
  16. const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usd';
  17. if ( ! ( geometryFileName in files ) ) {
  18. const meshObject = buildMeshObject( geometry );
  19. files[ geometryFileName ] = buildUSDFileAsString( meshObject );
  20. }
  21. if ( ! ( material.uuid in materials ) ) {
  22. materials[ material.uuid ] = material;
  23. }
  24. output += buildXform( object, geometry, material );
  25. } else {
  26. console.warn( 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)', object );
  27. }
  28. }
  29. } );
  30. output += buildMaterials( materials, textures );
  31. files[ modelFileName ] = fflate.strToU8( output );
  32. output = null;
  33. for ( const id in textures ) {
  34. const texture = textures[ id ];
  35. const color = id.split( '_' )[ 1 ];
  36. const isRGBA = texture.format === 1023;
  37. const canvas = imageToCanvas( texture.image, color );
  38. const blob = await new Promise( resolve => canvas.toBlob( resolve, isRGBA ? 'image/png' : 'image/jpeg', 1 ) );
  39. files[ `textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }` ] = new Uint8Array( await blob.arrayBuffer() );
  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. function imageToCanvas( image, color ) {
  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. if ( color !== undefined ) {
  71. const hex = parseInt( color, 16 );
  72. const r = ( hex >> 16 & 255 ) / 255;
  73. const g = ( hex >> 8 & 255 ) / 255;
  74. const b = ( hex & 255 ) / 255;
  75. const imagedata = context.getImageData( 0, 0, canvas.width, canvas.height );
  76. const data = imagedata.data;
  77. for ( let i = 0; i < data.length; i += 4 ) {
  78. data[ i + 0 ] = data[ i + 0 ] * r;
  79. data[ i + 1 ] = data[ i + 1 ] * g;
  80. data[ i + 2 ] = data[ i + 2 ] * b;
  81. }
  82. context.putImageData( imagedata, 0, 0 );
  83. }
  84. return canvas;
  85. }
  86. }
  87. //
  88. const PRECISION = 7;
  89. function buildHeader() {
  90. return `#usda 1.0
  91. (
  92. customLayerData = {
  93. string creator = "Three.js USDZExporter"
  94. }
  95. metersPerUnit = 1
  96. upAxis = "Y"
  97. )
  98. `;
  99. }
  100. function buildUSDFileAsString( dataToInsert ) {
  101. let output = buildHeader();
  102. output += dataToInsert;
  103. return fflate.strToU8( output );
  104. }
  105. // Xform
  106. function buildXform( object, geometry, material ) {
  107. const name = 'Object_' + object.id;
  108. const transform = buildMatrix( object.matrixWorld );
  109. if ( object.matrixWorld.determinant() < 0 ) {
  110. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object );
  111. }
  112. return `def Xform "${ name }" (
  113. prepend references = @./geometries/Geometry_${ geometry.id }.usd@</Geometry>
  114. )
  115. {
  116. matrix4d xformOp:transform = ${ transform }
  117. uniform token[] xformOpOrder = ["xformOp:transform"]
  118. rel material:binding = </Materials/Material_${ material.id }>
  119. }
  120. `;
  121. }
  122. function buildMatrix( matrix ) {
  123. const array = matrix.elements;
  124. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  125. }
  126. function buildMatrixRow( array, offset ) {
  127. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  128. }
  129. // Mesh
  130. function buildMeshObject( geometry ) {
  131. const mesh = buildMesh( geometry );
  132. return `
  133. def "Geometry"
  134. {
  135. ${mesh}
  136. }
  137. `;
  138. }
  139. function buildMesh( geometry ) {
  140. const name = 'Geometry';
  141. const attributes = geometry.attributes;
  142. const count = attributes.position.count;
  143. return `
  144. def Mesh "${ name }"
  145. {
  146. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  147. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  148. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  149. interpolation = "vertex"
  150. )
  151. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  152. float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
  153. interpolation = "vertex"
  154. )
  155. uniform token subdivisionScheme = "none"
  156. }
  157. `;
  158. }
  159. function buildMeshVertexCount( geometry ) {
  160. const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count;
  161. return Array( count / 3 ).fill( 3 ).join( ', ' );
  162. }
  163. function buildMeshVertexIndices( geometry ) {
  164. const index = geometry.index;
  165. const array = [];
  166. if ( index !== null ) {
  167. for ( let i = 0; i < index.count; i ++ ) {
  168. array.push( index.getX( i ) );
  169. }
  170. } else {
  171. const length = geometry.attributes.position.count;
  172. for ( let i = 0; i < length; i ++ ) {
  173. array.push( i );
  174. }
  175. }
  176. return array.join( ', ' );
  177. }
  178. function buildVector3Array( attribute, count ) {
  179. if ( attribute === undefined ) {
  180. console.warn( 'USDZExporter: Normals missing.' );
  181. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  182. }
  183. const array = [];
  184. for ( let i = 0; i < attribute.count; i ++ ) {
  185. const x = attribute.getX( i );
  186. const y = attribute.getY( i );
  187. const z = attribute.getZ( i );
  188. array.push( `(${ x.toPrecision( PRECISION ) }, ${ y.toPrecision( PRECISION ) }, ${ z.toPrecision( PRECISION ) })` );
  189. }
  190. return array.join( ', ' );
  191. }
  192. function buildVector2Array( attribute, count ) {
  193. if ( attribute === undefined ) {
  194. console.warn( 'USDZExporter: UVs missing.' );
  195. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  196. }
  197. const array = [];
  198. for ( let i = 0; i < attribute.count; i ++ ) {
  199. const x = attribute.getX( i );
  200. const y = attribute.getY( i );
  201. array.push( `(${ x.toPrecision( PRECISION ) }, ${ 1 - y.toPrecision( PRECISION ) })` );
  202. }
  203. return array.join( ', ' );
  204. }
  205. // Materials
  206. function buildMaterials( materials, textures ) {
  207. const array = [];
  208. for ( const uuid in materials ) {
  209. const material = materials[ uuid ];
  210. array.push( buildMaterial( material, textures ) );
  211. }
  212. return `def "Materials"
  213. {
  214. ${ array.join( '' ) }
  215. }
  216. `;
  217. }
  218. function buildMaterial( material, textures ) {
  219. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  220. const pad = ' ';
  221. const inputs = [];
  222. const samplers = [];
  223. function buildTexture( texture, mapType, color ) {
  224. const id = texture.id + ( color ? '_' + color.getHexString() : '' );
  225. const isRGBA = texture.format === 1023;
  226. textures[ id ] = texture;
  227. return `
  228. def Shader "Transform2d_${ mapType }" (
  229. sdrMetadata = {
  230. string role = "math"
  231. }
  232. )
  233. {
  234. uniform token info:id = "UsdTransform2d"
  235. float2 inputs:in.connect = </Materials/Material_${ material.id }/uvReader_st.outputs:result>
  236. float2 inputs:scale = ${ buildVector2( texture.repeat ) }
  237. float2 inputs:translation = ${ buildVector2( texture.offset ) }
  238. float2 outputs:result
  239. }
  240. def Shader "Texture_${ texture.id }_${ mapType }"
  241. {
  242. uniform token info:id = "UsdUVTexture"
  243. asset inputs:file = @textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }@
  244. float2 inputs:st.connect = </Materials/Material_${ material.id }/Transform2d_${ mapType }.outputs:result>
  245. token inputs:wrapS = "repeat"
  246. token inputs:wrapT = "repeat"
  247. float outputs:r
  248. float outputs:g
  249. float outputs:b
  250. float3 outputs:rgb
  251. }`;
  252. }
  253. if ( material.map !== null ) {
  254. inputs.push( `${ pad }color3f inputs:diffuseColor.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:rgb>` );
  255. samplers.push( buildTexture( material.map, 'diffuse', material.color ) );
  256. } else {
  257. inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  258. }
  259. if ( material.emissiveMap !== null ) {
  260. inputs.push( `${ pad }color3f inputs:emissiveColor.connect = </Materials/Material_${ material.id }/Texture_${ material.emissiveMap.id }_emissive.outputs:rgb>` );
  261. samplers.push( buildTexture( material.emissiveMap, 'emissive' ) );
  262. } else if ( material.emissive.getHex() > 0 ) {
  263. inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  264. }
  265. if ( material.normalMap !== null ) {
  266. inputs.push( `${ pad }normal3f inputs:normal.connect = </Materials/Material_${ material.id }/Texture_${ material.normalMap.id }_normal.outputs:rgb>` );
  267. samplers.push( buildTexture( material.normalMap, 'normal' ) );
  268. }
  269. if ( material.aoMap !== null ) {
  270. inputs.push( `${ pad }float inputs:occlusion.connect = </Materials/Material_${ material.id }/Texture_${ material.aoMap.id }_occlusion.outputs:r>` );
  271. samplers.push( buildTexture( material.aoMap, 'occlusion' ) );
  272. }
  273. if ( material.roughnessMap !== null && material.roughness === 1 ) {
  274. inputs.push( `${ pad }float inputs:roughness.connect = </Materials/Material_${ material.id }/Texture_${ material.roughnessMap.id }_roughness.outputs:g>` );
  275. samplers.push( buildTexture( material.roughnessMap, 'roughness' ) );
  276. } else {
  277. inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  278. }
  279. if ( material.metalnessMap !== null && material.metalness === 1 ) {
  280. inputs.push( `${ pad }float inputs:metallic.connect = </Materials/Material_${ material.id }/Texture_${ material.metalnessMap.id }_metallic.outputs:b>` );
  281. samplers.push( buildTexture( material.metalnessMap, 'metallic' ) );
  282. } else {
  283. inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  284. }
  285. if ( material.alphaMap !== null ) {
  286. inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
  287. inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
  288. samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
  289. } else {
  290. inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
  291. }
  292. if ( material.isMeshPhysicalMaterial ) {
  293. inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` );
  294. inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` );
  295. inputs.push( `${ pad }float inputs:ior = ${ material.ior }` );
  296. }
  297. return `
  298. def Material "Material_${ material.id }"
  299. {
  300. def Shader "PreviewSurface"
  301. {
  302. uniform token info:id = "UsdPreviewSurface"
  303. ${ inputs.join( '\n' ) }
  304. int inputs:useSpecularWorkflow = 0
  305. token outputs:surface
  306. }
  307. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  308. token inputs:frame:stPrimvarName = "st"
  309. def Shader "uvReader_st"
  310. {
  311. uniform token info:id = "UsdPrimvarReader_float2"
  312. token inputs:varname.connect = </Materials/Material_${ material.id }.inputs:frame:stPrimvarName>
  313. float2 inputs:fallback = (0.0, 0.0)
  314. float2 outputs:result
  315. }
  316. ${ samplers.join( '\n' ) }
  317. }
  318. `;
  319. }
  320. function buildColor( color ) {
  321. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  322. }
  323. function buildVector2( vector ) {
  324. return `(${ vector.x }, ${ vector.y })`;
  325. }
  326. export { USDZExporter };