USDZExporter.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. import {
  2. NoColorSpace,
  3. DoubleSide,
  4. Color,
  5. } from 'three';
  6. import {
  7. strToU8,
  8. zipSync,
  9. } from '../libs/fflate.module.js';
  10. class USDNode {
  11. constructor( name, type = '', metadata = [], properties = [] ) {
  12. this.name = name;
  13. this.type = type;
  14. this.metadata = metadata;
  15. this.properties = properties;
  16. this.children = [];
  17. }
  18. addMetadata( key, value ) {
  19. this.metadata.push( { key, value } );
  20. }
  21. addProperty( property, metadata = [] ) {
  22. this.properties.push( { property, metadata } );
  23. }
  24. addChild( child ) {
  25. this.children.push( child );
  26. }
  27. toString( indent = 0 ) {
  28. const pad = '\t'.repeat( indent );
  29. const formattedMetadata = this.metadata.map( ( item ) => {
  30. const key = item.key;
  31. const value = item.value;
  32. if ( Array.isArray( value ) ) {
  33. const lines = [];
  34. lines.push( `${key} = {` );
  35. value.forEach( ( line ) => {
  36. lines.push( `${pad}\t\t${line}` );
  37. } );
  38. lines.push( `${pad}\t}` );
  39. return lines.join( '\n' );
  40. } else {
  41. return `${key} = ${value}`;
  42. }
  43. } );
  44. const meta = formattedMetadata.length
  45. ? ` (\n${formattedMetadata
  46. .map( ( l ) => `${pad}\t${l}` )
  47. .join( '\n' )}\n${pad})`
  48. : '';
  49. const properties = this.properties.map( ( l ) => {
  50. const property = l.property;
  51. const metadata = l.metadata.length
  52. ? ` (\n${l.metadata.map( ( m ) => `${pad}\t\t${m}` ).join( '\n' )}\n${pad}\t)`
  53. : '';
  54. return `${pad}\t${property}${metadata}`;
  55. } );
  56. const children = this.children.map( ( c ) => c.toString( indent + 1 ) );
  57. const bodyLines = [];
  58. if ( properties.length > 0 ) {
  59. bodyLines.push( ...properties );
  60. }
  61. if ( children.length > 0 ) {
  62. if ( properties.length > 0 ) {
  63. bodyLines.push( '' );
  64. }
  65. for ( let i = 0; i < children.length; i ++ ) {
  66. bodyLines.push( children[ i ] );
  67. if ( i < children.length - 1 ) {
  68. bodyLines.push( '' );
  69. }
  70. }
  71. }
  72. const bodyContent = bodyLines.join( '\n' );
  73. const type = this.type ? this.type + ' ' : '';
  74. return `${pad}def ${type}"${this.name}"${meta}\n${pad}{\n${bodyContent}\n${pad}}`;
  75. }
  76. }
  77. /**
  78. * An exporter for USDZ.
  79. *
  80. * ```js
  81. * const exporter = new USDZExporter();
  82. * const arraybuffer = await exporter.parseAsync( scene );
  83. * ```
  84. *
  85. * @three_import import { USDZExporter } from 'three/addons/exporters/USDZExporter.js';
  86. */
  87. class USDZExporter {
  88. /**
  89. * Constructs a new USDZ exporter.
  90. */
  91. constructor() {
  92. /**
  93. * A reference to a texture utils module.
  94. *
  95. * @type {?(WebGLTextureUtils|WebGPUTextureUtils)}
  96. * @default null
  97. */
  98. this.textureUtils = null;
  99. }
  100. /**
  101. * Sets the texture utils for this exporter. Only relevant when compressed textures have to be exported.
  102. *
  103. * Depending on whether you use {@link WebGLRenderer} or {@link WebGPURenderer}, you must inject the
  104. * corresponding texture utils {@link WebGLTextureUtils} or {@link WebGPUTextureUtils}.
  105. *
  106. * @param {WebGLTextureUtils|WebGPUTextureUtils} utils - The texture utils.
  107. */
  108. setTextureUtils( utils ) {
  109. this.textureUtils = utils;
  110. }
  111. /**
  112. * Parse the given 3D object and generates the USDZ output.
  113. *
  114. * @param {Object3D} scene - The 3D object to export.
  115. * @param {USDZExporter~OnDone} onDone - A callback function that is executed when the export has finished.
  116. * @param {USDZExporter~OnError} onError - A callback function that is executed when an error happens.
  117. * @param {USDZExporter~Options} options - The export options.
  118. */
  119. parse( scene, onDone, onError, options ) {
  120. this.parseAsync( scene, options ).then( onDone ).catch( onError );
  121. }
  122. /**
  123. * Async version of {@link USDZExporter#parse}.
  124. *
  125. * @async
  126. * @param {Object3D} scene - The 3D object to export.
  127. * @param {USDZExporter~Options} options - The export options.
  128. * @return {Promise<ArrayBuffer>} A Promise that resolved with the exported USDZ data.
  129. */
  130. async parseAsync( scene, options = {} ) {
  131. options = Object.assign(
  132. {
  133. ar: {
  134. anchoring: { type: 'plane' },
  135. planeAnchoring: { alignment: 'horizontal' },
  136. },
  137. includeAnchoringProperties: true,
  138. onlyVisible: true,
  139. quickLookCompatible: false,
  140. maxTextureSize: 1024,
  141. },
  142. options
  143. );
  144. const usedNames = new Set();
  145. const files = {};
  146. const modelFileName = 'model.usda';
  147. // model file should be first in USDZ archive so we init it here
  148. files[ modelFileName ] = null;
  149. const root = new USDNode( 'Root', 'Xform' );
  150. const scenesNode = new USDNode( 'Scenes', 'Scope' );
  151. scenesNode.addMetadata( 'kind', '"sceneLibrary"' );
  152. root.addChild( scenesNode );
  153. const sceneName = 'Scene';
  154. const sceneNode = new USDNode( sceneName, 'Xform' );
  155. sceneNode.addMetadata( 'customData', [
  156. 'bool preliminary_collidesWithEnvironment = 0',
  157. `string sceneName = "${sceneName}"`,
  158. ] );
  159. sceneNode.addMetadata( 'sceneName', `"${sceneName}"` );
  160. if ( options.includeAnchoringProperties ) {
  161. sceneNode.addProperty(
  162. `token preliminary:anchoring:type = "${options.ar.anchoring.type}"`
  163. );
  164. sceneNode.addProperty(
  165. `token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}"`
  166. );
  167. }
  168. scenesNode.addChild( sceneNode );
  169. let output;
  170. const materials = {};
  171. const textures = {};
  172. buildHierarchy( scene, sceneNode, materials, usedNames, files, options );
  173. const materialsNode = buildMaterials(
  174. materials,
  175. textures,
  176. options.quickLookCompatible
  177. );
  178. output =
  179. buildHeader() +
  180. '\n' +
  181. root.toString() +
  182. '\n\n' +
  183. materialsNode.toString();
  184. files[ modelFileName ] = strToU8( output );
  185. output = null;
  186. for ( const id in textures ) {
  187. let texture = textures[ id ];
  188. if ( texture.isCompressedTexture === true ) {
  189. if ( this.textureUtils === null ) {
  190. throw new Error(
  191. 'THREE.USDZExporter: setTextureUtils() must be called to process compressed textures.'
  192. );
  193. } else {
  194. texture = await this.textureUtils.decompress( texture );
  195. }
  196. }
  197. const canvas = imageToCanvas(
  198. texture.image,
  199. texture.flipY,
  200. options.maxTextureSize
  201. );
  202. const blob = await new Promise( ( resolve ) =>
  203. canvas.toBlob( resolve, 'image/png', 1 )
  204. );
  205. files[ `textures/Texture_${id}.png` ] = new Uint8Array(
  206. await blob.arrayBuffer()
  207. );
  208. }
  209. // 64 byte alignment
  210. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  211. let offset = 0;
  212. for ( const filename in files ) {
  213. const file = files[ filename ];
  214. const headerSize = 34 + filename.length;
  215. offset += headerSize;
  216. const offsetMod64 = offset & 63;
  217. if ( offsetMod64 !== 4 ) {
  218. const padLength = 64 - offsetMod64;
  219. const padding = new Uint8Array( padLength );
  220. files[ filename ] = [ file, { extra: { 12345: padding } } ];
  221. }
  222. offset = file.length;
  223. }
  224. return zipSync( files, { level: 0 } );
  225. }
  226. }
  227. function getName( object, namesSet ) {
  228. let name = object.name;
  229. name = name.replace( /[^A-Za-z0-9_]/g, '' );
  230. if ( /^[0-9]/.test( name ) ) {
  231. name = '_' + name;
  232. }
  233. if ( name === '' ) {
  234. if ( object.isCamera ) {
  235. name = 'Camera';
  236. } else {
  237. name = 'Object';
  238. }
  239. }
  240. if ( namesSet.has( name ) ) {
  241. name = name + '_' + object.id;
  242. }
  243. namesSet.add( name );
  244. return name;
  245. }
  246. function imageToCanvas( image, flipY, maxTextureSize ) {
  247. if (
  248. ( typeof HTMLImageElement !== 'undefined' &&
  249. image instanceof HTMLImageElement ) ||
  250. ( typeof HTMLCanvasElement !== 'undefined' &&
  251. image instanceof HTMLCanvasElement ) ||
  252. ( typeof OffscreenCanvas !== 'undefined' &&
  253. image instanceof OffscreenCanvas ) ||
  254. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap )
  255. ) {
  256. const scale = maxTextureSize / Math.max( image.width, image.height );
  257. const canvas = document.createElement( 'canvas' );
  258. canvas.width = image.width * Math.min( 1, scale );
  259. canvas.height = image.height * Math.min( 1, scale );
  260. const context = canvas.getContext( '2d' );
  261. // TODO: We should be able to do this in the UsdTransform2d?
  262. if ( flipY === true ) {
  263. context.translate( 0, canvas.height );
  264. context.scale( 1, - 1 );
  265. }
  266. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  267. return canvas;
  268. } else {
  269. throw new Error(
  270. 'THREE.USDZExporter: No valid image data found. Unable to process texture.'
  271. );
  272. }
  273. }
  274. //
  275. const PRECISION = 7;
  276. function buildHeader() {
  277. return `#usda 1.0
  278. (
  279. customLayerData = {
  280. string creator = "Three.js USDZExporter"
  281. }
  282. defaultPrim = "Root"
  283. metersPerUnit = 1
  284. upAxis = "Y"
  285. )
  286. `;
  287. }
  288. // Xform
  289. function buildHierarchy( object, parentNode, materials, usedNames, files, options ) {
  290. for ( let i = 0, l = object.children.length; i < l; i ++ ) {
  291. const child = object.children[ i ];
  292. if ( child.visible === false && options.onlyVisible === true ) continue;
  293. let childNode;
  294. if ( child.isMesh ) {
  295. const geometry = child.geometry;
  296. const material = child.material;
  297. if ( material.isMeshStandardMaterial ) {
  298. const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usda';
  299. if ( ! ( geometryFileName in files ) ) {
  300. const meshObject = buildMeshObject( geometry );
  301. files[ geometryFileName ] = strToU8(
  302. buildHeader() + '\n' + meshObject.toString()
  303. );
  304. }
  305. if ( ! ( material.uuid in materials ) ) {
  306. materials[ material.uuid ] = material;
  307. }
  308. childNode = buildMesh(
  309. child,
  310. geometry,
  311. materials[ material.uuid ],
  312. usedNames
  313. );
  314. } else {
  315. console.warn(
  316. 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)',
  317. child
  318. );
  319. }
  320. } else if ( child.isCamera ) {
  321. childNode = buildCamera( child, usedNames );
  322. } else {
  323. childNode = buildXform( child, usedNames );
  324. }
  325. if ( childNode ) {
  326. parentNode.addChild( childNode );
  327. buildHierarchy( child, childNode, materials, usedNames, files, options );
  328. }
  329. }
  330. }
  331. function buildXform( object, usedNames ) {
  332. const name = getName( object, usedNames );
  333. if ( object.matrix.determinant() < 0 ) {
  334. console.warn(
  335. 'THREE.USDZExporter: USDZ does not support negative scales',
  336. object
  337. );
  338. }
  339. const node = new USDNode( name, 'Xform' );
  340. if ( object.pivot !== null ) {
  341. // Export with pivot using separate transform ops
  342. const p = object.position;
  343. const q = object.quaternion;
  344. const s = object.scale;
  345. const piv = object.pivot;
  346. node.addProperty( `float3 xformOp:translate = (${p.x.toPrecision( PRECISION )}, ${p.y.toPrecision( PRECISION )}, ${p.z.toPrecision( PRECISION )})` );
  347. node.addProperty( `float3 xformOp:translate:pivot = (${piv.x.toPrecision( PRECISION )}, ${piv.y.toPrecision( PRECISION )}, ${piv.z.toPrecision( PRECISION )})` );
  348. node.addProperty( `quatf xformOp:orient = (${q.w.toPrecision( PRECISION )}, ${q.x.toPrecision( PRECISION )}, ${q.y.toPrecision( PRECISION )}, ${q.z.toPrecision( PRECISION )})` );
  349. node.addProperty( `float3 xformOp:scale = (${s.x.toPrecision( PRECISION )}, ${s.y.toPrecision( PRECISION )}, ${s.z.toPrecision( PRECISION )})` );
  350. node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:translate:pivot", "xformOp:orient", "xformOp:scale", "!invert!xformOp:translate:pivot"]' );
  351. } else {
  352. // Export as single transform matrix
  353. const transform = buildMatrix( object.matrix );
  354. node.addProperty( `matrix4d xformOp:transform = ${transform}` );
  355. node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:transform"]' );
  356. }
  357. return node;
  358. }
  359. function buildMesh( object, geometry, material, usedNames ) {
  360. const node = buildXform( object, usedNames );
  361. node.addMetadata(
  362. 'prepend references',
  363. `@./geometries/Geometry_${geometry.id}.usda@</Geometry>`
  364. );
  365. node.addMetadata( 'prepend apiSchemas', '["MaterialBindingAPI"]' );
  366. node.addProperty(
  367. `rel material:binding = </Materials/Material_${material.id}>`
  368. );
  369. return node;
  370. }
  371. function buildMatrix( matrix ) {
  372. const array = matrix.elements;
  373. return `( ${buildMatrixRow( array, 0 )}, ${buildMatrixRow(
  374. array,
  375. 4
  376. )}, ${buildMatrixRow( array, 8 )}, ${buildMatrixRow( array, 12 )} )`;
  377. }
  378. function buildMatrixRow( array, offset ) {
  379. return `(${array[ offset + 0 ]}, ${array[ offset + 1 ]}, ${array[ offset + 2 ]}, ${
  380. array[ offset + 3 ]
  381. })`;
  382. }
  383. // Mesh
  384. function buildMeshObject( geometry ) {
  385. const node = new USDNode( 'Geometry' );
  386. const meshNode = buildMeshNode( geometry );
  387. node.addChild( meshNode );
  388. return node;
  389. }
  390. function buildMeshNode( geometry ) {
  391. const name = 'Geometry';
  392. const attributes = geometry.attributes;
  393. const count = attributes.position.count;
  394. const node = new USDNode( name, 'Mesh' );
  395. node.addProperty(
  396. `int[] faceVertexCounts = [${buildMeshVertexCount( geometry )}]`
  397. );
  398. node.addProperty(
  399. `int[] faceVertexIndices = [${buildMeshVertexIndices( geometry )}]`
  400. );
  401. node.addProperty(
  402. `normal3f[] normals = [${buildVector3Array( attributes.normal, count )}]`,
  403. [ 'interpolation = "vertex"' ]
  404. );
  405. node.addProperty(
  406. `point3f[] points = [${buildVector3Array( attributes.position, count )}]`
  407. );
  408. for ( let i = 0; i < 4; i ++ ) {
  409. const id = i > 0 ? i : '';
  410. const attribute = attributes[ 'uv' + id ];
  411. if ( attribute !== undefined ) {
  412. node.addProperty(
  413. `texCoord2f[] primvars:st${id} = [${buildVector2Array( attribute )}]`,
  414. [ 'interpolation = "vertex"' ]
  415. );
  416. }
  417. }
  418. const colorAttribute = attributes.color;
  419. if ( colorAttribute !== undefined ) {
  420. node.addProperty(
  421. `color3f[] primvars:displayColor = [${buildVector3Array(
  422. colorAttribute,
  423. count
  424. )}]`,
  425. [ 'interpolation = "vertex"' ]
  426. );
  427. }
  428. node.addProperty( 'uniform token subdivisionScheme = "none"' );
  429. return node;
  430. }
  431. function buildMeshVertexCount( geometry ) {
  432. const count =
  433. geometry.index !== null
  434. ? geometry.index.count
  435. : geometry.attributes.position.count;
  436. return Array( count / 3 )
  437. .fill( 3 )
  438. .join( ', ' );
  439. }
  440. function buildMeshVertexIndices( geometry ) {
  441. const index = geometry.index;
  442. const array = [];
  443. if ( index !== null ) {
  444. for ( let i = 0; i < index.count; i ++ ) {
  445. array.push( index.getX( i ) );
  446. }
  447. } else {
  448. const length = geometry.attributes.position.count;
  449. for ( let i = 0; i < length; i ++ ) {
  450. array.push( i );
  451. }
  452. }
  453. return array.join( ', ' );
  454. }
  455. function buildVector3Array( attribute, count ) {
  456. if ( attribute === undefined ) {
  457. console.warn( 'USDZExporter: Normals missing.' );
  458. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  459. }
  460. const array = [];
  461. for ( let i = 0; i < attribute.count; i ++ ) {
  462. const x = attribute.getX( i );
  463. const y = attribute.getY( i );
  464. const z = attribute.getZ( i );
  465. array.push(
  466. `(${x.toPrecision( PRECISION )}, ${y.toPrecision(
  467. PRECISION
  468. )}, ${z.toPrecision( PRECISION )})`
  469. );
  470. }
  471. return array.join( ', ' );
  472. }
  473. function buildVector2Array( attribute ) {
  474. const array = [];
  475. for ( let i = 0; i < attribute.count; i ++ ) {
  476. const x = attribute.getX( i );
  477. const y = attribute.getY( i );
  478. array.push(
  479. `(${x.toPrecision( PRECISION )}, ${1 - y.toPrecision( PRECISION )})`
  480. );
  481. }
  482. return array.join( ', ' );
  483. }
  484. // Materials
  485. function buildMaterials( materials, textures, quickLookCompatible = false ) {
  486. const materialsNode = new USDNode( 'Materials' );
  487. for ( const uuid in materials ) {
  488. const material = materials[ uuid ];
  489. materialsNode.addChild(
  490. buildMaterial( material, textures, quickLookCompatible )
  491. );
  492. }
  493. return materialsNode;
  494. }
  495. function buildMaterial( material, textures, quickLookCompatible = false ) {
  496. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  497. const materialNode = new USDNode( `Material_${material.id}`, 'Material' );
  498. function buildTextureNodes( texture, mapType, color ) {
  499. const id = texture.source.id + '_' + texture.flipY;
  500. textures[ id ] = texture;
  501. const uv = texture.channel > 0 ? 'st' + texture.channel : 'st';
  502. const WRAPPINGS = {
  503. 1000: 'repeat', // RepeatWrapping
  504. 1001: 'clamp', // ClampToEdgeWrapping
  505. 1002: 'mirror', // MirroredRepeatWrapping
  506. };
  507. const repeat = texture.repeat.clone();
  508. const offset = texture.offset.clone();
  509. const rotation = texture.rotation;
  510. // rotation is around the wrong point. after rotation we need to shift offset again so that we're rotating around the right spot
  511. const xRotationOffset = Math.sin( rotation );
  512. const yRotationOffset = Math.cos( rotation );
  513. // texture coordinates start in the opposite corner, need to correct
  514. offset.y = 1 - offset.y - repeat.y;
  515. // turns out QuickLook is buggy and interprets texture repeat inverted/applies operations in a different order.
  516. // Apple Feedback: FB10036297 and FB11442287
  517. if ( quickLookCompatible ) {
  518. // This is NOT correct yet in QuickLook, but comes close for a range of models.
  519. // It becomes more incorrect the bigger the offset is
  520. offset.x = offset.x / repeat.x;
  521. offset.y = offset.y / repeat.y;
  522. offset.x += xRotationOffset / repeat.x;
  523. offset.y += yRotationOffset - 1;
  524. } else {
  525. // results match glTF results exactly. verified correct in usdview.
  526. offset.x += xRotationOffset * repeat.x;
  527. offset.y += ( 1 - yRotationOffset ) * repeat.y;
  528. }
  529. const primvarReaderNode = new USDNode( `PrimvarReader_${mapType}`, 'Shader' );
  530. primvarReaderNode.addProperty(
  531. 'uniform token info:id = "UsdPrimvarReader_float2"'
  532. );
  533. primvarReaderNode.addProperty( 'float2 inputs:fallback = (0.0, 0.0)' );
  534. primvarReaderNode.addProperty( `string inputs:varname = "${uv}"` );
  535. primvarReaderNode.addProperty( 'float2 outputs:result' );
  536. const transform2dNode = new USDNode( `Transform2d_${mapType}`, 'Shader' );
  537. transform2dNode.addProperty( 'uniform token info:id = "UsdTransform2d"' );
  538. transform2dNode.addProperty(
  539. `float2 inputs:in.connect = </Materials/Material_${material.id}/PrimvarReader_${mapType}.outputs:result>`
  540. );
  541. transform2dNode.addProperty(
  542. `float inputs:rotation = ${( rotation * ( 180 / Math.PI ) ).toFixed(
  543. PRECISION
  544. )}`
  545. );
  546. transform2dNode.addProperty(
  547. `float2 inputs:scale = ${buildVector2( repeat )}`
  548. );
  549. transform2dNode.addProperty(
  550. `float2 inputs:translation = ${buildVector2( offset )}`
  551. );
  552. transform2dNode.addProperty( 'float2 outputs:result' );
  553. const textureNode = new USDNode(
  554. `Texture_${texture.id}_${mapType}`,
  555. 'Shader'
  556. );
  557. textureNode.addProperty( 'uniform token info:id = "UsdUVTexture"' );
  558. textureNode.addProperty( `asset inputs:file = @textures/Texture_${id}.png@` );
  559. textureNode.addProperty(
  560. `float2 inputs:st.connect = </Materials/Material_${material.id}/Transform2d_${mapType}.outputs:result>`
  561. );
  562. if ( color !== undefined ) {
  563. textureNode.addProperty( `float4 inputs:scale = ${buildColor4( color )}` );
  564. }
  565. if ( mapType === 'normal' ) {
  566. textureNode.addProperty( 'float4 inputs:scale = (2, 2, 2, 1)' );
  567. textureNode.addProperty( 'float4 inputs:bias = (-1, -1, -1, 0)' );
  568. }
  569. textureNode.addProperty(
  570. `token inputs:sourceColorSpace = "${
  571. texture.colorSpace === NoColorSpace ? 'raw' : 'sRGB'
  572. }"`
  573. );
  574. textureNode.addProperty(
  575. `token inputs:wrapS = "${WRAPPINGS[ texture.wrapS ]}"`
  576. );
  577. textureNode.addProperty(
  578. `token inputs:wrapT = "${WRAPPINGS[ texture.wrapT ]}"`
  579. );
  580. textureNode.addProperty( 'float outputs:r' );
  581. textureNode.addProperty( 'float outputs:g' );
  582. textureNode.addProperty( 'float outputs:b' );
  583. textureNode.addProperty( 'float3 outputs:rgb' );
  584. if ( material.transparent || material.alphaTest > 0.0 ) {
  585. textureNode.addProperty( 'float outputs:a' );
  586. }
  587. return [ primvarReaderNode, transform2dNode, textureNode ];
  588. }
  589. if ( material.side === DoubleSide ) {
  590. console.warn(
  591. 'THREE.USDZExporter: USDZ does not support double sided materials',
  592. material
  593. );
  594. }
  595. const previewSurfaceNode = new USDNode( 'PreviewSurface', 'Shader' );
  596. previewSurfaceNode.addProperty( 'uniform token info:id = "UsdPreviewSurface"' );
  597. if ( material.map !== null ) {
  598. previewSurfaceNode.addProperty(
  599. `color3f inputs:diffuseColor.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:rgb>`
  600. );
  601. if ( material.transparent ) {
  602. previewSurfaceNode.addProperty(
  603. `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`
  604. );
  605. } else if ( material.alphaTest > 0.0 ) {
  606. previewSurfaceNode.addProperty(
  607. `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`
  608. );
  609. previewSurfaceNode.addProperty(
  610. `float inputs:opacityThreshold = ${material.alphaTest}`
  611. );
  612. }
  613. const textureNodes = buildTextureNodes(
  614. material.map,
  615. 'diffuse',
  616. material.color
  617. );
  618. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  619. } else {
  620. previewSurfaceNode.addProperty(
  621. `color3f inputs:diffuseColor = ${buildColor( material.color )}`
  622. );
  623. }
  624. if ( material.emissiveMap !== null ) {
  625. previewSurfaceNode.addProperty(
  626. `color3f inputs:emissiveColor.connect = </Materials/Material_${material.id}/Texture_${material.emissiveMap.id}_emissive.outputs:rgb>`
  627. );
  628. const emissiveColor = new Color(
  629. material.emissive.r * material.emissiveIntensity,
  630. material.emissive.g * material.emissiveIntensity,
  631. material.emissive.b * material.emissiveIntensity
  632. );
  633. const textureNodes = buildTextureNodes(
  634. material.emissiveMap,
  635. 'emissive',
  636. emissiveColor
  637. );
  638. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  639. } else if ( material.emissive.getHex() > 0 ) {
  640. previewSurfaceNode.addProperty(
  641. `color3f inputs:emissiveColor = ${buildColor( material.emissive )}`
  642. );
  643. }
  644. if ( material.normalMap !== null ) {
  645. previewSurfaceNode.addProperty(
  646. `normal3f inputs:normal.connect = </Materials/Material_${material.id}/Texture_${material.normalMap.id}_normal.outputs:rgb>`
  647. );
  648. const textureNodes = buildTextureNodes( material.normalMap, 'normal' );
  649. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  650. }
  651. if ( material.aoMap !== null ) {
  652. previewSurfaceNode.addProperty(
  653. `float inputs:occlusion.connect = </Materials/Material_${material.id}/Texture_${material.aoMap.id}_occlusion.outputs:r>`
  654. );
  655. const aoColor = new Color(
  656. material.aoMapIntensity,
  657. material.aoMapIntensity,
  658. material.aoMapIntensity
  659. );
  660. const textureNodes = buildTextureNodes(
  661. material.aoMap,
  662. 'occlusion',
  663. aoColor
  664. );
  665. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  666. }
  667. if ( material.roughnessMap !== null ) {
  668. previewSurfaceNode.addProperty(
  669. `float inputs:roughness.connect = </Materials/Material_${material.id}/Texture_${material.roughnessMap.id}_roughness.outputs:g>`
  670. );
  671. const roughnessColor = new Color(
  672. material.roughness,
  673. material.roughness,
  674. material.roughness
  675. );
  676. const textureNodes = buildTextureNodes(
  677. material.roughnessMap,
  678. 'roughness',
  679. roughnessColor
  680. );
  681. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  682. } else {
  683. previewSurfaceNode.addProperty(
  684. `float inputs:roughness = ${material.roughness}`
  685. );
  686. }
  687. if ( material.metalnessMap !== null ) {
  688. previewSurfaceNode.addProperty(
  689. `float inputs:metallic.connect = </Materials/Material_${material.id}/Texture_${material.metalnessMap.id}_metallic.outputs:b>`
  690. );
  691. const metalnessColor = new Color(
  692. material.metalness,
  693. material.metalness,
  694. material.metalness
  695. );
  696. const textureNodes = buildTextureNodes(
  697. material.metalnessMap,
  698. 'metallic',
  699. metalnessColor
  700. );
  701. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  702. } else {
  703. previewSurfaceNode.addProperty(
  704. `float inputs:metallic = ${material.metalness}`
  705. );
  706. }
  707. if ( material.alphaMap !== null ) {
  708. previewSurfaceNode.addProperty(
  709. `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>`
  710. );
  711. previewSurfaceNode.addProperty( 'float inputs:opacityThreshold = 0.0001' );
  712. const textureNodes = buildTextureNodes( material.alphaMap, 'opacity' );
  713. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  714. } else {
  715. previewSurfaceNode.addProperty(
  716. `float inputs:opacity = ${material.opacity}`
  717. );
  718. }
  719. if ( material.isMeshPhysicalMaterial ) {
  720. if ( material.clearcoatMap !== null ) {
  721. previewSurfaceNode.addProperty(
  722. `float inputs:clearcoat.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatMap.id}_clearcoat.outputs:r>`
  723. );
  724. const clearcoatColor = new Color(
  725. material.clearcoat,
  726. material.clearcoat,
  727. material.clearcoat
  728. );
  729. const textureNodes = buildTextureNodes(
  730. material.clearcoatMap,
  731. 'clearcoat',
  732. clearcoatColor
  733. );
  734. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  735. } else {
  736. previewSurfaceNode.addProperty(
  737. `float inputs:clearcoat = ${material.clearcoat}`
  738. );
  739. }
  740. if ( material.clearcoatRoughnessMap !== null ) {
  741. previewSurfaceNode.addProperty(
  742. `float inputs:clearcoatRoughness.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatRoughnessMap.id}_clearcoatRoughness.outputs:g>`
  743. );
  744. const clearcoatRoughnessColor = new Color(
  745. material.clearcoatRoughness,
  746. material.clearcoatRoughness,
  747. material.clearcoatRoughness
  748. );
  749. const textureNodes = buildTextureNodes(
  750. material.clearcoatRoughnessMap,
  751. 'clearcoatRoughness',
  752. clearcoatRoughnessColor
  753. );
  754. textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
  755. } else {
  756. previewSurfaceNode.addProperty(
  757. `float inputs:clearcoatRoughness = ${material.clearcoatRoughness}`
  758. );
  759. }
  760. previewSurfaceNode.addProperty( `float inputs:ior = ${material.ior}` );
  761. }
  762. previewSurfaceNode.addProperty( 'int inputs:useSpecularWorkflow = 0' );
  763. previewSurfaceNode.addProperty( 'token outputs:surface' );
  764. materialNode.addChild( previewSurfaceNode );
  765. materialNode.addProperty(
  766. `token outputs:surface.connect = </Materials/Material_${material.id}/PreviewSurface.outputs:surface>`
  767. );
  768. return materialNode;
  769. }
  770. function buildColor( color ) {
  771. return `(${color.r}, ${color.g}, ${color.b})`;
  772. }
  773. function buildColor4( color ) {
  774. return `(${color.r}, ${color.g}, ${color.b}, 1.0)`;
  775. }
  776. function buildVector2( vector ) {
  777. return `(${vector.x}, ${vector.y})`;
  778. }
  779. function buildCamera( camera, usedNames ) {
  780. const name = getName( camera, usedNames );
  781. const transform = buildMatrix( camera.matrix );
  782. if ( camera.matrix.determinant() < 0 ) {
  783. console.warn(
  784. 'THREE.USDZExporter: USDZ does not support negative scales',
  785. camera
  786. );
  787. }
  788. const node = new USDNode( name, 'Camera' );
  789. node.addProperty( `matrix4d xformOp:transform = ${transform}` );
  790. node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:transform"]' );
  791. const projection = camera.isOrthographicCamera
  792. ? 'orthographic'
  793. : 'perspective';
  794. node.addProperty( `token projection = "${projection}"` );
  795. const clippingRange = `(${camera.near.toPrecision(
  796. PRECISION
  797. )}, ${camera.far.toPrecision( PRECISION )})`;
  798. node.addProperty( `float2 clippingRange = ${clippingRange}` );
  799. let horizontalAperture;
  800. if ( camera.isOrthographicCamera ) {
  801. horizontalAperture = (
  802. ( Math.abs( camera.left ) + Math.abs( camera.right ) ) *
  803. 10
  804. ).toPrecision( PRECISION );
  805. } else {
  806. horizontalAperture = camera.getFilmWidth().toPrecision( PRECISION );
  807. }
  808. node.addProperty( `float horizontalAperture = ${horizontalAperture}` );
  809. let verticalAperture;
  810. if ( camera.isOrthographicCamera ) {
  811. verticalAperture = (
  812. ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) *
  813. 10
  814. ).toPrecision( PRECISION );
  815. } else {
  816. verticalAperture = camera.getFilmHeight().toPrecision( PRECISION );
  817. }
  818. node.addProperty( `float verticalAperture = ${verticalAperture}` );
  819. if ( camera.isPerspectiveCamera ) {
  820. const focalLength = camera.getFocalLength().toPrecision( PRECISION );
  821. node.addProperty( `float focalLength = ${focalLength}` );
  822. const focusDistance = camera.focus.toPrecision( PRECISION );
  823. node.addProperty( `float focusDistance = ${focusDistance}` );
  824. }
  825. return node;
  826. }
  827. /**
  828. * Export options of `USDZExporter`.
  829. *
  830. * @typedef {Object} USDZExporter~Options
  831. * @property {number} [maxTextureSize=1024] - The maximum texture size that is going to be exported.
  832. * @property {boolean} [includeAnchoringProperties=true] - Whether to include anchoring properties or not.
  833. * @property {boolean} [onlyVisible=true] - Export only visible 3D objects.
  834. * @property {Object} [ar] - If `includeAnchoringProperties` is set to `true`, the anchoring type and alignment
  835. * can be configured via `ar.anchoring.type` and `ar.planeAnchoring.alignment`.
  836. * @property {boolean} [quickLookCompatible=false] - Whether to make the exported USDZ compatible to QuickLook
  837. * which means the asset is modified to accommodate the bugs FB10036297 and FB11442287 (Apple Feedback).
  838. **/
  839. /**
  840. * onDone callback of `USDZExporter`.
  841. *
  842. * @callback USDZExporter~OnDone
  843. * @param {ArrayBuffer} result - The generated USDZ.
  844. */
  845. /**
  846. * onError callback of `USDZExporter`.
  847. *
  848. * @callback USDZExporter~OnError
  849. * @param {Error} error - The error object.
  850. */
  851. export { USDZExporter };
粤ICP备19079148号