USDZExporter.js 9.9 KB

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