USDZExporter.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 + '.usda';
  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 }.usda@</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. ${ buildPrimvars( attributes, count ) }
  198. uniform token subdivisionScheme = "none"
  199. }
  200. `;
  201. }
  202. function buildMeshVertexCount( geometry ) {
  203. const count = geometry.index !== null ? geometry.index.count : geometry.attributes.position.count;
  204. return Array( count / 3 ).fill( 3 ).join( ', ' );
  205. }
  206. function buildMeshVertexIndices( geometry ) {
  207. const index = geometry.index;
  208. const array = [];
  209. if ( index !== null ) {
  210. for ( let i = 0; i < index.count; i ++ ) {
  211. array.push( index.getX( i ) );
  212. }
  213. } else {
  214. const length = geometry.attributes.position.count;
  215. for ( let i = 0; i < length; i ++ ) {
  216. array.push( i );
  217. }
  218. }
  219. return array.join( ', ' );
  220. }
  221. function buildVector3Array( attribute, count ) {
  222. if ( attribute === undefined ) {
  223. console.warn( 'USDZExporter: Normals missing.' );
  224. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  225. }
  226. const array = [];
  227. for ( let i = 0; i < attribute.count; i ++ ) {
  228. const x = attribute.getX( i );
  229. const y = attribute.getY( i );
  230. const z = attribute.getZ( i );
  231. array.push( `(${ x.toPrecision( PRECISION ) }, ${ y.toPrecision( PRECISION ) }, ${ z.toPrecision( PRECISION ) })` );
  232. }
  233. return array.join( ', ' );
  234. }
  235. function buildVector2Array( attribute, count ) {
  236. if ( attribute === undefined ) {
  237. console.warn( 'USDZExporter: UVs missing.' );
  238. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  239. }
  240. const array = [];
  241. for ( let i = 0; i < attribute.count; i ++ ) {
  242. const x = attribute.getX( i );
  243. const y = attribute.getY( i );
  244. array.push( `(${ x.toPrecision( PRECISION ) }, ${ 1 - y.toPrecision( PRECISION ) })` );
  245. }
  246. return array.join( ', ' );
  247. }
  248. function buildPrimvars( attributes, count ) {
  249. let string = '';
  250. for ( let i = 0; i < 4; i ++ ) {
  251. const id = ( i > 0 ? i : '' );
  252. const attribute = attributes[ 'uv' + id ];
  253. if ( attribute !== undefined ) {
  254. string += `
  255. float2[] primvars:st${ id } = [${ buildVector2Array( attribute, count )}] (
  256. interpolation = "vertex"
  257. )`;
  258. }
  259. }
  260. return string;
  261. }
  262. // Materials
  263. function buildMaterials( materials, textures ) {
  264. const array = [];
  265. for ( const uuid in materials ) {
  266. const material = materials[ uuid ];
  267. array.push( buildMaterial( material, textures ) );
  268. }
  269. return `def "Materials"
  270. {
  271. ${ array.join( '' ) }
  272. }
  273. `;
  274. }
  275. function buildMaterial( material, textures ) {
  276. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  277. const pad = ' ';
  278. const inputs = [];
  279. const samplers = [];
  280. function buildTexture( texture, mapType, color ) {
  281. const id = texture.id + ( color ? '_' + color.getHexString() : '' );
  282. const isRGBA = texture.format === 1023;
  283. textures[ id ] = texture;
  284. const uv = texture.channel > 0 ? 'st' + texture.channel : 'st';
  285. return `
  286. def Shader "PrimvarReader_${ mapType }"
  287. {
  288. uniform token info:id = "UsdPrimvarReader_float2"
  289. float2 inputs:fallback = (0.0, 0.0)
  290. token inputs:varname = "${ uv }"
  291. float2 outputs:result
  292. }
  293. def Shader "Transform2d_${ mapType }"
  294. {
  295. uniform token info:id = "UsdTransform2d"
  296. token inputs:in.connect = </Materials/Material_${ material.id }/PrimvarReader_${ mapType }.outputs:result>
  297. float2 inputs:scale = ${ buildVector2( texture.repeat ) }
  298. float2 inputs:translation = ${ buildVector2( texture.offset ) }
  299. float2 outputs:result
  300. }
  301. def Shader "Texture_${ texture.id }_${ mapType }"
  302. {
  303. uniform token info:id = "UsdUVTexture"
  304. asset inputs:file = @textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }@
  305. float2 inputs:st.connect = </Materials/Material_${ material.id }/Transform2d_${ mapType }.outputs:result>
  306. token inputs:wrapS = "repeat"
  307. token inputs:wrapT = "repeat"
  308. float outputs:r
  309. float outputs:g
  310. float outputs:b
  311. float3 outputs:rgb
  312. ${ material.transparent || material.alphaTest > 0.0 ? 'float outputs:a' : '' }
  313. }`;
  314. }
  315. if ( material.side === DoubleSide ) {
  316. console.warn( 'THREE.USDZExporter: USDZ does not support double sided materials', material );
  317. }
  318. if ( material.map !== null ) {
  319. inputs.push( `${ pad }color3f inputs:diffuseColor.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:rgb>` );
  320. if ( material.transparent ) {
  321. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  322. } else if ( material.alphaTest > 0.0 ) {
  323. inputs.push( `${ pad }float inputs:opacity.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:a>` );
  324. inputs.push( `${ pad }float inputs:opacityThreshold = ${material.alphaTest}` );
  325. }
  326. samplers.push( buildTexture( material.map, 'diffuse', material.color ) );
  327. } else {
  328. inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  329. }
  330. if ( material.emissiveMap !== null ) {
  331. inputs.push( `${ pad }color3f inputs:emissiveColor.connect = </Materials/Material_${ material.id }/Texture_${ material.emissiveMap.id }_emissive.outputs:rgb>` );
  332. samplers.push( buildTexture( material.emissiveMap, 'emissive' ) );
  333. } else if ( material.emissive.getHex() > 0 ) {
  334. inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  335. }
  336. if ( material.normalMap !== null ) {
  337. inputs.push( `${ pad }normal3f inputs:normal.connect = </Materials/Material_${ material.id }/Texture_${ material.normalMap.id }_normal.outputs:rgb>` );
  338. samplers.push( buildTexture( material.normalMap, 'normal' ) );
  339. }
  340. if ( material.aoMap !== null ) {
  341. inputs.push( `${ pad }float inputs:occlusion.connect = </Materials/Material_${ material.id }/Texture_${ material.aoMap.id }_occlusion.outputs:r>` );
  342. samplers.push( buildTexture( material.aoMap, 'occlusion' ) );
  343. }
  344. if ( material.roughnessMap !== null && material.roughness === 1 ) {
  345. inputs.push( `${ pad }float inputs:roughness.connect = </Materials/Material_${ material.id }/Texture_${ material.roughnessMap.id }_roughness.outputs:g>` );
  346. samplers.push( buildTexture( material.roughnessMap, 'roughness' ) );
  347. } else {
  348. inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  349. }
  350. if ( material.metalnessMap !== null && material.metalness === 1 ) {
  351. inputs.push( `${ pad }float inputs:metallic.connect = </Materials/Material_${ material.id }/Texture_${ material.metalnessMap.id }_metallic.outputs:b>` );
  352. samplers.push( buildTexture( material.metalnessMap, 'metallic' ) );
  353. } else {
  354. inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  355. }
  356. if ( material.alphaMap !== null ) {
  357. inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
  358. inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
  359. samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
  360. } else {
  361. inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
  362. }
  363. if ( material.isMeshPhysicalMaterial ) {
  364. inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` );
  365. inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` );
  366. inputs.push( `${ pad }float inputs:ior = ${ material.ior }` );
  367. }
  368. return `
  369. def Material "Material_${ material.id }"
  370. {
  371. def Shader "PreviewSurface"
  372. {
  373. uniform token info:id = "UsdPreviewSurface"
  374. ${ inputs.join( '\n' ) }
  375. int inputs:useSpecularWorkflow = 0
  376. token outputs:surface
  377. }
  378. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  379. ${ samplers.join( '\n' ) }
  380. }
  381. `;
  382. }
  383. function buildColor( color ) {
  384. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  385. }
  386. function buildVector2( vector ) {
  387. return `(${ vector.x }, ${ vector.y })`;
  388. }
  389. function buildCamera( camera ) {
  390. const name = camera.name ? camera.name : 'Camera_' + camera.id;
  391. const transform = buildMatrix( camera.matrixWorld );
  392. if ( camera.matrixWorld.determinant() < 0 ) {
  393. console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', camera );
  394. }
  395. if ( camera.isOrthographicCamera ) {
  396. return `def Camera "${name}"
  397. {
  398. matrix4d xformOp:transform = ${ transform }
  399. uniform token[] xformOpOrder = ["xformOp:transform"]
  400. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  401. float horizontalAperture = ${ ( ( Math.abs( camera.left ) + Math.abs( camera.right ) ) * 10 ).toPrecision( PRECISION ) }
  402. float verticalAperture = ${ ( ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) * 10 ).toPrecision( PRECISION ) }
  403. token projection = "orthographic"
  404. }
  405. `;
  406. } else {
  407. return `def Camera "${name}"
  408. {
  409. matrix4d xformOp:transform = ${ transform }
  410. uniform token[] xformOpOrder = ["xformOp:transform"]
  411. float2 clippingRange = (${ camera.near.toPrecision( PRECISION ) }, ${ camera.far.toPrecision( PRECISION ) })
  412. float focalLength = ${ camera.getFocalLength().toPrecision( PRECISION ) }
  413. float focusDistance = ${ camera.focus.toPrecision( PRECISION ) }
  414. float horizontalAperture = ${ camera.getFilmWidth().toPrecision( PRECISION ) }
  415. token projection = "perspective"
  416. float verticalAperture = ${ camera.getFilmHeight().toPrecision( PRECISION ) }
  417. }
  418. `;
  419. }
  420. }
  421. export { USDZExporter };