USDZExporter.js 21 KB

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