USDZExporter.js 17 KB

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