USDZExporter.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. import { zipSync, strToU8 } from '../libs/fflate.module.min.js';
  2. class USDZExporter {
  3. async parse( scene ) {
  4. let output = buildHeader();
  5. const materials = {};
  6. const textures = {};
  7. scene.traverse( ( object ) => {
  8. if ( object.isMesh ) {
  9. const geometry = object.geometry;
  10. const material = object.material;
  11. materials[ material.uuid ] = material;
  12. if ( material.map !== null ) textures[ material.map.uuid ] = material.map;
  13. if ( material.normalMap !== null ) textures[ material.normalMap.uuid ] = material.normalMap;
  14. if ( material.aoMap !== null ) textures[ material.aoMap.uuid ] = material.aoMap;
  15. if ( material.roughnessMap !== null ) textures[ material.roughnessMap.uuid ] = material.roughnessMap;
  16. if ( material.metalnessMap !== null ) textures[ material.metalnessMap.uuid ] = material.metalnessMap;
  17. if ( material.emissiveMap !== null ) textures[ material.emissiveMap.uuid ] = material.emissiveMap;
  18. output += buildXform( object, buildMesh( geometry, material ) );
  19. }
  20. } );
  21. output += buildMaterials( materials );
  22. output += buildTextures( textures );
  23. const files = {};
  24. for ( const uuid in textures ) {
  25. const texture = textures[ uuid ];
  26. files[ 'Texture_' + texture.id + '.jpg' ] = await imgToU8( texture.image );
  27. }
  28. return zipSync( { 'model.usda': strToU8( output ), 'textures': files }, { level: 0 } );
  29. }
  30. }
  31. async function imgToU8( image ) {
  32. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  33. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  34. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  35. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  36. const canvas = document.createElement( 'canvas' );
  37. canvas.width = image.width;
  38. canvas.height = image.height;
  39. const context = canvas.getContext( '2d' );
  40. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  41. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg' ) );
  42. return new Uint8Array( await blob.arrayBuffer() );
  43. }
  44. }
  45. //
  46. function buildHeader() {
  47. return `#usda 1.0
  48. (
  49. doc = "Three.js"
  50. metersPerUnit = 1
  51. upAxis = "Y"
  52. )
  53. `;
  54. }
  55. // Xform
  56. function buildXform( object, define ) {
  57. const name = 'Object_' + object.id;
  58. const transform = buildMatrix( object.matrixWorld );
  59. return `def Xform "${ name }"
  60. {
  61. matrix4d xformOp:transform = ${ transform }
  62. uniform token[] xformOpOrder = ["xformOp:transform"]
  63. ${ define }
  64. }
  65. `;
  66. }
  67. function buildMatrix( matrix ) {
  68. const array = matrix.elements;
  69. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  70. }
  71. function buildMatrixRow( array, offset ) {
  72. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  73. }
  74. // Mesh
  75. function buildMesh( geometry, material ) {
  76. const name = 'Geometry_' + geometry.id;
  77. const attributes = geometry.attributes;
  78. const count = attributes.position.count;
  79. return `def Mesh "${ name }"
  80. {
  81. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  82. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  83. rel material:binding = </Materials/Material_${ material.id }>
  84. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  85. interpolation = "vertex"
  86. )
  87. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  88. float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
  89. elementSize = 1
  90. interpolation = "vertex"
  91. )
  92. int[] primvars:st:indices
  93. uniform token subdivisionScheme = "none"
  94. }
  95. `;
  96. }
  97. function buildMeshVertexCount( geometry ) {
  98. const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;
  99. return Array( count / 3 ).fill( 3 ).join( ', ' );
  100. }
  101. function buildMeshVertexIndices( geometry ) {
  102. if ( geometry.index !== null ) {
  103. return geometry.index.array.join( ', ' );
  104. }
  105. const array = [];
  106. const length = geometry.attributes.position.count;
  107. for ( let i = 0; i < length; i ++ ) {
  108. array.push( i );
  109. }
  110. return array.join( ', ' );
  111. }
  112. function buildVector3Array( attribute, count ) {
  113. if ( attribute === undefined ) {
  114. console.warn( 'USDZExporter: Normals missing.' );
  115. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  116. }
  117. const array = [];
  118. const data = attribute.array;
  119. for ( let i = 0; i < data.length; i += 3 ) {
  120. array.push( `(${ data[ i + 0 ] }, ${ data[ i + 1 ] }, ${ data[ i + 2 ] })` );
  121. }
  122. return array.join( ', ' );
  123. }
  124. function buildVector2Array( attribute, count ) {
  125. if ( attribute === undefined ) {
  126. console.warn( 'USDZExporter: UVs missing.' );
  127. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  128. }
  129. const array = [];
  130. const data = attribute.array;
  131. for ( let i = 0; i < data.length; i += 2 ) {
  132. array.push( `(${ data[ i + 0 ] }, ${ 1 - data[ i + 1 ] })` );
  133. }
  134. return array.join( ', ' );
  135. }
  136. // Materials
  137. function buildMaterials( materials ) {
  138. const array = [];
  139. for ( const uuid in materials ) {
  140. const material = materials[ uuid ];
  141. array.push( buildMaterial( material ) );
  142. }
  143. return `def "Materials"
  144. {
  145. ${ array.join( '' ) }
  146. }
  147. `;
  148. }
  149. function buildMaterial( material ) {
  150. const pad = ' ';
  151. const parameters = [];
  152. if ( material.map !== null ) {
  153. parameters.push( `${ pad }float3 inputs:diffuseColor.connect = </Textures/Texture_${ material.map.id }.outputs:rgb>` );
  154. } else {
  155. parameters.push( `${ pad }float3 inputs:diffuseColor = ${ buildColor( material.color ) }` );
  156. }
  157. if ( material.normalMap !== null ) {
  158. parameters.push( `${ pad }float3 inputs:normal.connect = </Textures/Texture_${ material.normalMap.id }.outputs:rgb>` );
  159. }
  160. if ( material.aoMap !== null ) {
  161. parameters.push( `${ pad }float inputs:occlusion.connect = </Textures/Texture_${ material.aoMap.id }.outputs:rgb>` );
  162. }
  163. if ( material.roughnessMap !== null ) {
  164. parameters.push( `${ pad }float inputs:roughness.connect = </Textures/Texture_${ material.roughnessMap.id }.outputs:rgb>` );
  165. } else {
  166. parameters.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  167. }
  168. if ( material.metalnessMap !== null ) {
  169. parameters.push( `${ pad }float inputs:metalness.connect = </Textures/Texture_${ material.metalnessMap.id }.outputs:rgb>` );
  170. } else {
  171. parameters.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  172. }
  173. if ( material.emissiveMap !== null ) {
  174. parameters.push( `${ pad }float3 inputs:emissive.connect = </Textures/Texture_${ material.emissiveMap.id }.outputs:rgb>` );
  175. }
  176. return `
  177. def Material "Material_${ material.id }"
  178. {
  179. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  180. def Shader "PreviewSurface"
  181. {
  182. uniform token info:id = "UsdPreviewSurface"
  183. ${ parameters.join( '\n' ) }
  184. int inputs:useSpecularWorkflow = 0
  185. token outputs:surface
  186. }
  187. }
  188. `;
  189. }
  190. function buildTextures( textures ) {
  191. const array = [];
  192. for ( const uuid in textures ) {
  193. const texture = textures[ uuid ];
  194. array.push( buildTexture( texture ) );
  195. }
  196. return `def "Textures"
  197. {
  198. ${ array.join( '' ) }
  199. }
  200. `;
  201. }
  202. function buildTexture( texture ) {
  203. return `
  204. def Shader "Texture_${ texture.id }"
  205. {
  206. uniform token info:id = "UsdUVTexture"
  207. asset inputs:file = @textures/Texture_${ texture.id }.jpg@
  208. token inputs:isSRGB = "auto"
  209. token inputs:wrapS = "repeat"
  210. token inputs:wrapT = "repeat"
  211. float3 outputs:rgb
  212. }
  213. `;
  214. }
  215. function buildColor( color ) {
  216. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  217. }
  218. export { USDZExporter };