USDZExporter.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. import {
  2. DoubleSide
  3. } from 'three';
  4. import * as fflate from '../libs/fflate.module.js';
  5. class USDZExporter {
  6. async parse( scene, options = { ar: { anchoring: { type: 'plane' }, planeAnchoring: { alignment: 'horizontal' } } } ) {
  7. const files = {};
  8. const modelFileName = 'model.usda';
  9. // model file should be first in USDZ archive so we init it here
  10. files[ modelFileName ] = null;
  11. let output = buildHeader();
  12. output += buildSceneStart( options );
  13. const materials = {};
  14. const textures = {};
  15. scene.traverseVisible( ( object ) => {
  16. if ( object.isMesh ) {
  17. const geometry = object.geometry;
  18. const material = object.material;
  19. if ( material.isMeshStandardMaterial ) {
  20. const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usd';
  21. if ( ! ( geometryFileName in files ) ) {
  22. const meshObject = buildMeshObject( geometry );
  23. files[ geometryFileName ] = buildUSDFileAsString( meshObject );
  24. }
  25. if ( ! ( material.uuid in materials ) ) {
  26. materials[ material.uuid ] = material;
  27. }
  28. output += buildXform( object, geometry, material );
  29. } else {
  30. console.warn( 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)', object );
  31. }
  32. } else if ( object.isCamera ) {
  33. output += buildCamera( object );
  34. }
  35. } );
  36. output += buildSceneEnd();
  37. output += buildMaterials( materials, textures );
  38. files[ modelFileName ] = fflate.strToU8( output );
  39. output = null;
  40. for ( const id in textures ) {
  41. const texture = textures[ id ];
  42. const color = id.split( '_' )[ 1 ];
  43. const isRGBA = texture.format === 1023;
  44. const canvas = imageToCanvas( texture.image, color );
  45. const blob = await new Promise( resolve => canvas.toBlob( resolve, isRGBA ? 'image/png' : 'image/jpeg', 1 ) );
  46. files[ `textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }` ] = new Uint8Array( await blob.arrayBuffer() );
  47. }
  48. // 64 byte alignment
  49. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  50. let offset = 0;
  51. for ( const filename in files ) {
  52. const file = files[ filename ];
  53. const headerSize = 34 + filename.length;
  54. offset += headerSize;
  55. const offsetMod64 = offset & 63;
  56. if ( offsetMod64 !== 4 ) {
  57. const padLength = 64 - offsetMod64;
  58. const padding = new Uint8Array( padLength );
  59. files[ filename ] = [ file, { extra: { 12345: padding } } ];
  60. }
  61. offset = file.length;
  62. }
  63. return fflate.zipSync( files, { level: 0 } );
  64. }
  65. }
  66. function imageToCanvas( image, color ) {
  67. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  68. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  69. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  70. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  71. const scale = 1024 / Math.max( image.width, image.height );
  72. const canvas = document.createElement( 'canvas' );
  73. canvas.width = image.width * Math.min( 1, scale );
  74. canvas.height = image.height * Math.min( 1, scale );
  75. const context = canvas.getContext( '2d' );
  76. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  77. if ( color !== undefined ) {
  78. const hex = parseInt( color, 16 );
  79. const r = ( hex >> 16 & 255 ) / 255;
  80. const g = ( hex >> 8 & 255 ) / 255;
  81. const b = ( hex & 255 ) / 255;
  82. const imagedata = context.getImageData( 0, 0, canvas.width, canvas.height );
  83. const data = imagedata.data;
  84. for ( let i = 0; i < data.length; i += 4 ) {
  85. data[ i + 0 ] = data[ i + 0 ] * r;
  86. data[ i + 1 ] = data[ i + 1 ] * g;
  87. data[ i + 2 ] = data[ i + 2 ] * b;
  88. }
  89. context.putImageData( imagedata, 0, 0 );
  90. }
  91. return canvas;
  92. }
  93. }
  94. //
  95. const PRECISION = 7;
  96. function buildHeader() {
  97. return `#usda 1.0
  98. (
  99. customLayerData = {
  100. string creator = "Three.js USDZExporter"
  101. }
  102. metersPerUnit = 1
  103. upAxis = "Y"
  104. )
  105. `;
  106. }
  107. function buildSceneStart( options ) {
  108. return `def Xform "Root"
  109. {
  110. def Scope "Scenes" (
  111. kind = "sceneLibrary"
  112. )
  113. {
  114. def Xform "Scene" (
  115. customData = {
  116. bool preliminary_collidesWithEnvironment = 0
  117. string sceneName = "Scene"
  118. }
  119. sceneName = "Scene"
  120. )
  121. {
  122. token preliminary:anchoring:type = "${options.ar.anchoring.type}"
  123. token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}"
  124. `;
  125. }
  126. function buildSceneEnd() {
  127. return `
  128. }
  129. }
  130. }
  131. `;
  132. }
  133. function buildUSDFileAsString( dataToInsert ) {
  134. let output = buildHeader();
  135. output += dataToInsert;
  136. return fflate.strToU8( output );
  137. }
  138. // Xform
  139. function buildXform( object, geometry, material ) {
  140. const name = 'Object_' + object.id;
  141. const transform = buildMatrix( object.matrixWorld );
  142. if ( object.matrixWorld.determinant() < 0 ) {
  143. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object );
  144. }
  145. return `def Xform "${ name }" (
  146. prepend references = @./geometries/Geometry_${ geometry.id }.usd@</Geometry>
  147. )
  148. {
  149. matrix4d xformOp:transform = ${ transform }
  150. uniform token[] xformOpOrder = ["xformOp:transform"]
  151. rel material:binding = </Materials/Material_${ material.id }>
  152. }
  153. `;
  154. }
  155. function buildMatrix( matrix ) {
  156. const array = matrix.elements;
  157. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  158. }
  159. function buildMatrixRow( array, offset ) {
  160. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  161. }
  162. // Mesh
  163. function buildMeshObject( geometry ) {
  164. const mesh = buildMesh( geometry );
  165. return `
  166. def "Geometry"
  167. {
  168. ${mesh}
  169. }
  170. `;
  171. }
  172. function buildMesh( geometry ) {
  173. const name = 'Geometry';
  174. const attributes = geometry.attributes;
  175. const count = attributes.position.count;
  176. return `
  177. def Mesh "${ name }"
  178. {
  179. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  180. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  181. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  182. interpolation = "vertex"
  183. )
  184. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  185. float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
  186. interpolation = "vertex"
  187. )
  188. uniform token subdivisionScheme = "none"
  189. }
  190. `;
  191. }
  192. function buildMeshVertexCount( geometry ) {
  193. const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count;
  194. return Array( count / 3 ).fill( 3 ).join( ', ' );
  195. }
  196. function buildMeshVertexIndices( geometry ) {
  197. const index = geometry.index;
  198. const array = [];
  199. if ( index !== null ) {
  200. for ( let i = 0; i < index.count; i ++ ) {
  201. array.push( index.getX( i ) );
  202. }
  203. } else {
  204. const length = geometry.attributes.position.count;
  205. for ( let i = 0; i < length; i ++ ) {
  206. array.push( i );
  207. }
  208. }
  209. return array.join( ', ' );
  210. }
  211. function buildVector3Array( attribute, count ) {
  212. if ( attribute === undefined ) {
  213. console.warn( 'USDZExporter: Normals missing.' );
  214. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  215. }
  216. const array = [];
  217. for ( let i = 0; i < attribute.count; i ++ ) {
  218. const x = attribute.getX( i );
  219. const y = attribute.getY( i );
  220. const z = attribute.getZ( i );
  221. array.push( `(${ x.toPrecision( PRECISION ) }, ${ y.toPrecision( PRECISION ) }, ${ z.toPrecision( PRECISION ) })` );
  222. }
  223. return array.join( ', ' );
  224. }
  225. function buildVector2Array( attribute, count ) {
  226. if ( attribute === undefined ) {
  227. console.warn( 'USDZExporter: UVs missing.' );
  228. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  229. }
  230. const array = [];
  231. for ( let i = 0; i < attribute.count; i ++ ) {
  232. const x = attribute.getX( i );
  233. const y = attribute.getY( i );
  234. array.push( `(${ x.toPrecision( PRECISION ) }, ${ 1 - y.toPrecision( PRECISION ) })` );
  235. }
  236. return array.join( ', ' );
  237. }
  238. // Materials
  239. function buildMaterials( materials, textures ) {
  240. const array = [];
  241. for ( const uuid in materials ) {
  242. const material = materials[ uuid ];
  243. array.push( buildMaterial( material, textures ) );
  244. }
  245. return `def "Materials"
  246. {
  247. ${ array.join( '' ) }
  248. }
  249. `;
  250. }
  251. function buildMaterial( material, textures ) {
  252. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  253. const pad = ' ';
  254. const inputs = [];
  255. const samplers = [];
  256. function buildTexture( texture, mapType, color ) {
  257. const id = texture.id + ( color ? '_' + color.getHexString() : '' );
  258. const isRGBA = texture.format === 1023;
  259. textures[ id ] = texture;
  260. return `
  261. def Shader "Transform2d_${ mapType }" (
  262. sdrMetadata = {
  263. string role = "math"
  264. }
  265. )
  266. {
  267. uniform token info:id = "UsdTransform2d"
  268. float2 inputs:in.connect = </Materials/Material_${ material.id }/uvReader_st.outputs:result>
  269. float2 inputs:scale = ${ buildVector2( texture.repeat ) }
  270. float2 inputs:translation = ${ buildVector2( texture.offset ) }
  271. float2 outputs:result
  272. }
  273. def Shader "Texture_${ texture.id }_${ mapType }"
  274. {
  275. uniform token info:id = "UsdUVTexture"
  276. asset inputs:file = @textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }@
  277. float2 inputs:st.connect = </Materials/Material_${ material.id }/Transform2d_${ mapType }.outputs:result>
  278. token inputs:wrapS = "repeat"
  279. token inputs:wrapT = "repeat"
  280. float outputs:r
  281. float outputs:g
  282. float outputs:b
  283. float3 outputs:rgb
  284. ${ material.transparent || material.alphaTest > 0.0 ? 'float outputs:a' : '' }
  285. }`;
  286. }
  287. if ( material.side === DoubleSide ) {
  288. console.warn( 'THREE.USDZExporter: USDZ does not support double sided materials', material );
  289. }
  290. if ( material.map !== null ) {
  291. inputs.push( `${ pad }color3f inputs:diffuseColor.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:rgb>` );
  292. if ( material.transparent ) {
  293. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  294. } else if ( material.alphaTest > 0.0 ) {
  295. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  296. inputs.push( `${ pad }float inputs:opacityThreshold = ${material.alphaTest}` );
  297. }
  298. samplers.push( buildTexture( material.map, 'diffuse', material.color ) );
  299. } else {
  300. inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  301. }
  302. if ( material.emissiveMap !== null ) {
  303. inputs.push( `${ pad }color3f inputs:emissiveColor.connect = </Materials/Material_${ material.id }/Texture_${ material.emissiveMap.id }_emissive.outputs:rgb>` );
  304. samplers.push( buildTexture( material.emissiveMap, 'emissive' ) );
  305. } else if ( material.emissive.getHex() > 0 ) {
  306. inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  307. }
  308. if ( material.normalMap !== null ) {
  309. inputs.push( `${ pad }normal3f inputs:normal.connect = </Materials/Material_${ material.id }/Texture_${ material.normalMap.id }_normal.outputs:rgb>` );
  310. samplers.push( buildTexture( material.normalMap, 'normal' ) );
  311. }
  312. if ( material.aoMap !== null ) {
  313. inputs.push( `${ pad }float inputs:occlusion.connect = </Materials/Material_${ material.id }/Texture_${ material.aoMap.id }_occlusion.outputs:r>` );
  314. samplers.push( buildTexture( material.aoMap, 'occlusion' ) );
  315. }
  316. if ( material.roughnessMap !== null && material.roughness === 1 ) {
  317. inputs.push( `${ pad }float inputs:roughness.connect = </Materials/Material_${ material.id }/Texture_${ material.roughnessMap.id }_roughness.outputs:g>` );
  318. samplers.push( buildTexture( material.roughnessMap, 'roughness' ) );
  319. } else {
  320. inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  321. }
  322. if ( material.metalnessMap !== null && material.metalness === 1 ) {
  323. inputs.push( `${ pad }float inputs:metallic.connect = </Materials/Material_${ material.id }/Texture_${ material.metalnessMap.id }_metallic.outputs:b>` );
  324. samplers.push( buildTexture( material.metalnessMap, 'metallic' ) );
  325. } else {
  326. inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  327. }
  328. if ( material.alphaMap !== null ) {
  329. inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
  330. inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
  331. samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
  332. } else {
  333. inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
  334. }
  335. if ( material.isMeshPhysicalMaterial ) {
  336. inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` );
  337. inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` );
  338. inputs.push( `${ pad }float inputs:ior = ${ material.ior }` );
  339. }
  340. return `
  341. def Material "Material_${ material.id }"
  342. {
  343. def Shader "PreviewSurface"
  344. {
  345. uniform token info:id = "UsdPreviewSurface"
  346. ${ inputs.join( '\n' ) }
  347. int inputs:useSpecularWorkflow = 0
  348. token outputs:surface
  349. }
  350. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  351. token inputs:frame:stPrimvarName = "st"
  352. def Shader "uvReader_st"
  353. {
  354. uniform token info:id = "UsdPrimvarReader_float2"
  355. token inputs:varname.connect = </Materials/Material_${ material.id }.inputs:frame:stPrimvarName>
  356. float2 inputs:fallback = (0.0, 0.0)
  357. float2 outputs:result
  358. }
  359. ${ samplers.join( '\n' ) }
  360. }
  361. `;
  362. }
  363. function buildColor( color ) {
  364. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  365. }
  366. function buildVector2( vector ) {
  367. return `(${ vector.x }, ${ vector.y })`;
  368. }
  369. function buildCamera( camera ) {
  370. const name = camera.name ? camera.name : 'Camera_' + camera.id;
  371. const transform = buildMatrix( camera.matrixWorld );
  372. if ( camera.matrixWorld.determinant() < 0 ) {
  373. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', camera );
  374. }
  375. if ( camera.isOrthographicCamera ) {
  376. return `def Camera "${name}"
  377. {
  378. matrix4d xformOp:transform = ${ transform }
  379. uniform token[] xformOpOrder = ["xformOp:transform"]
  380. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  381. float horizontalAperture = ${ ( ( Math.abs( camera.left ) + Math.abs( camera.right ) ) * 10 ).toPrecision( PRECISION ) }
  382. float verticalAperture = ${ ( ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) * 10 ).toPrecision( PRECISION ) }
  383. token projection = "orthographic"
  384. }
  385. `;
  386. } else {
  387. return `def Camera "${name}"
  388. {
  389. matrix4d xformOp:transform = ${ transform }
  390. uniform token[] xformOpOrder = ["xformOp:transform"]
  391. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  392. float focalLength = ${ camera.getFocalLength().toPrecision( PRECISION ) }
  393. float focusDistance = ${ camera.focus.toPrecision( PRECISION ) }
  394. float horizontalAperture = ${ camera.getFilmWidth().toPrecision( PRECISION ) }
  395. token projection = "perspective"
  396. float verticalAperture = ${ camera.getFilmHeight().toPrecision( PRECISION ) }
  397. }
  398. `;
  399. }
  400. }
  401. export { USDZExporter };