USDZExporter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. ( function () {
  2. class USDZExporter {
  3. async parse( scene ) {
  4. const files = {};
  5. const modelFileName = 'model.usda'; // model file should be first in USDZ archive so we init it here
  6. files[ modelFileName ] = null;
  7. let output = buildHeader();
  8. const materials = {};
  9. const textures = {};
  10. scene.traverseVisible( object => {
  11. if ( object.isMesh && object.material.isMeshStandardMaterial ) {
  12. const geometry = object.geometry;
  13. const material = object.material;
  14. const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usd';
  15. if ( ! ( geometryFileName in files ) ) {
  16. const meshObject = buildMeshObject( geometry );
  17. files[ geometryFileName ] = buildUSDFileAsString( meshObject );
  18. }
  19. if ( ! ( material.uuid in materials ) ) {
  20. materials[ material.uuid ] = material;
  21. }
  22. output += buildXform( object, geometry, material );
  23. }
  24. } );
  25. output += buildMaterials( materials, textures );
  26. files[ modelFileName ] = fflate.strToU8( output );
  27. output = null;
  28. for ( const id in textures ) {
  29. const texture = textures[ id ];
  30. const color = id.split( '_' )[ 1 ];
  31. files[ 'textures/Texture_' + id + '.jpg' ] = await imgToU8( texture.image, color );
  32. } // 64 byte alignment
  33. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  34. let offset = 0;
  35. for ( const filename in files ) {
  36. const file = files[ filename ];
  37. const headerSize = 34 + filename.length;
  38. offset += headerSize;
  39. const offsetMod64 = offset & 63;
  40. if ( offsetMod64 !== 4 ) {
  41. const padLength = 64 - offsetMod64;
  42. const padding = new Uint8Array( padLength );
  43. files[ filename ] = [ file, {
  44. extra: {
  45. 12345: padding
  46. }
  47. } ];
  48. }
  49. offset = file.length;
  50. }
  51. return fflate.zipSync( files, {
  52. level: 0
  53. } );
  54. }
  55. }
  56. async function imgToU8( image, color ) {
  57. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement || typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement || typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas || typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) {
  58. const scale = 1024 / Math.max( image.width, image.height );
  59. const canvas = document.createElement( 'canvas' );
  60. canvas.width = image.width * Math.min( 1, scale );
  61. canvas.height = image.height * Math.min( 1, scale );
  62. const context = canvas.getContext( '2d' );
  63. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  64. if ( color !== undefined ) {
  65. context.globalCompositeOperation = 'multiply';
  66. context.fillStyle = `#${color}`;
  67. context.fillRect( 0, 0, canvas.width, canvas.height );
  68. }
  69. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg', 1 ) );
  70. return new Uint8Array( await blob.arrayBuffer() );
  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. } // Xform
  90. function buildXform( object, geometry, material ) {
  91. const name = 'Object_' + object.id;
  92. const transform = buildMatrix( object.matrixWorld );
  93. if ( object.matrixWorld.determinant() < 0 ) {
  94. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object );
  95. }
  96. return `def Xform "${name}" (
  97. prepend references = @./geometries/Geometry_${geometry.id}.usd@</Geometry>
  98. )
  99. {
  100. matrix4d xformOp:transform = ${transform}
  101. uniform token[] xformOpOrder = ["xformOp:transform"]
  102. rel material:binding = </Materials/Material_${material.id}>
  103. }
  104. `;
  105. }
  106. function buildMatrix( matrix ) {
  107. const array = matrix.elements;
  108. return `( ${buildMatrixRow( array, 0 )}, ${buildMatrixRow( array, 4 )}, ${buildMatrixRow( array, 8 )}, ${buildMatrixRow( array, 12 )} )`;
  109. }
  110. function buildMatrixRow( array, offset ) {
  111. return `(${array[ offset + 0 ]}, ${array[ offset + 1 ]}, ${array[ offset + 2 ]}, ${array[ offset + 3 ]})`;
  112. } // Mesh
  113. function buildMeshObject( geometry ) {
  114. const mesh = buildMesh( geometry );
  115. return `
  116. def "Geometry"
  117. {
  118. ${mesh}
  119. }
  120. `;
  121. }
  122. function buildMesh( geometry ) {
  123. const name = 'Geometry';
  124. const attributes = geometry.attributes;
  125. const count = attributes.position.count;
  126. return `
  127. def Mesh "${name}"
  128. {
  129. int[] faceVertexCounts = [${buildMeshVertexCount( geometry )}]
  130. int[] faceVertexIndices = [${buildMeshVertexIndices( geometry )}]
  131. normal3f[] normals = [${buildVector3Array( attributes.normal, count )}] (
  132. interpolation = "vertex"
  133. )
  134. point3f[] points = [${buildVector3Array( attributes.position, count )}]
  135. float2[] primvars:st = [${buildVector2Array( attributes.uv, count )}] (
  136. interpolation = "vertex"
  137. )
  138. uniform token subdivisionScheme = "none"
  139. }
  140. `;
  141. }
  142. function buildMeshVertexCount( geometry ) {
  143. const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;
  144. return Array( count / 3 ).fill( 3 ).join( ', ' );
  145. }
  146. function buildMeshVertexIndices( geometry ) {
  147. if ( geometry.index !== null ) {
  148. return geometry.index.array.join( ', ' );
  149. }
  150. const array = [];
  151. const length = geometry.attributes.position.count;
  152. for ( let i = 0; i < length; i ++ ) {
  153. array.push( i );
  154. }
  155. return array.join( ', ' );
  156. }
  157. function buildVector3Array( attribute, count ) {
  158. if ( attribute === undefined ) {
  159. console.warn( 'USDZExporter: Normals missing.' );
  160. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  161. }
  162. const array = [];
  163. const data = attribute.array;
  164. for ( let i = 0; i < data.length; i += 3 ) {
  165. array.push( `(${data[ i + 0 ].toPrecision( PRECISION )}, ${data[ i + 1 ].toPrecision( PRECISION )}, ${data[ i + 2 ].toPrecision( PRECISION )})` );
  166. }
  167. return array.join( ', ' );
  168. }
  169. function buildVector2Array( attribute, count ) {
  170. if ( attribute === undefined ) {
  171. console.warn( 'USDZExporter: UVs missing.' );
  172. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  173. }
  174. const array = [];
  175. const data = attribute.array;
  176. for ( let i = 0; i < data.length; i += 2 ) {
  177. array.push( `(${data[ i + 0 ].toPrecision( PRECISION )}, ${1 - data[ i + 1 ].toPrecision( PRECISION )})` );
  178. }
  179. return array.join( ', ' );
  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. THREE.USDZExporter = USDZExporter;
  295. } )();