USDZExporter.js 16 KB

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