WebGPUTextures.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. import { GPUTextureFormat, GPUAddressMode, GPUFilterMode } from './constants.js';
  2. import { CubeTexture, Texture, NearestFilter, NearestMipmapNearestFilter, NearestMipmapLinearFilter, LinearFilter, RepeatWrapping, MirroredRepeatWrapping,
  3. RGBFormat, RGBAFormat, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, UnsignedByteType, FloatType, HalfFloatType, sRGBEncoding
  4. } from '../../../../build/three.module.js';
  5. import WebGPUTextureUtils from './WebGPUTextureUtils.js';
  6. class WebGPUTextures {
  7. constructor( device, properties, info, glslang ) {
  8. this.device = device;
  9. this.properties = properties;
  10. this.info = info;
  11. this.glslang = glslang;
  12. this.defaultTexture = null;
  13. this.defaultCubeTexture = null;
  14. this.defaultSampler = null;
  15. this.samplerCache = new Map();
  16. this.utils = null;
  17. }
  18. getDefaultSampler() {
  19. if ( this.defaultSampler === null ) {
  20. this.defaultSampler = this.device.createSampler( {} );
  21. }
  22. return this.defaultSampler;
  23. }
  24. getDefaultTexture() {
  25. if ( this.defaultTexture === null ) {
  26. const texture = new Texture();
  27. texture.minFilter = NearestFilter;
  28. texture.magFilter = NearestFilter;
  29. this.defaultTexture = this._createTexture( texture );
  30. }
  31. return this.defaultTexture;
  32. }
  33. getDefaultCubeTexture() {
  34. if ( this.defaultCubeTexture === null ) {
  35. const texture = new CubeTexture();
  36. texture.minFilter = NearestFilter;
  37. texture.magFilter = NearestFilter;
  38. this.defaultCubeTexture = this._createTexture( texture );
  39. }
  40. return this.defaultCubeTexture;
  41. }
  42. getTextureGPU( texture ) {
  43. const textureProperties = this.properties.get( texture );
  44. return textureProperties.textureGPU;
  45. }
  46. getSampler( texture ) {
  47. const textureProperties = this.properties.get( texture );
  48. return textureProperties.samplerGPU;
  49. }
  50. updateTexture( texture ) {
  51. let forceUpdate = false;
  52. const textureProperties = this.properties.get( texture );
  53. if ( texture.version > 0 && textureProperties.version !== texture.version ) {
  54. const image = texture.image;
  55. if ( image === undefined ) {
  56. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is undefined.' );
  57. } else if ( image.complete === false ) {
  58. console.warn( 'THREE.WebGPURenderer: Texture marked for update but image is incomplete.' );
  59. } else {
  60. // texture init
  61. if ( textureProperties.initialized === undefined ) {
  62. textureProperties.initialized = true;
  63. const disposeCallback = onTextureDispose.bind( this );
  64. textureProperties.disposeCallback = disposeCallback;
  65. texture.addEventListener( 'dispose', disposeCallback );
  66. this.info.memory.textures ++;
  67. }
  68. // texture creation
  69. if ( textureProperties.textureGPU !== undefined ) {
  70. // @TODO: Avoid calling of destroy() in certain scenarios. When only the contents of a texture
  71. // are updated, a buffer upload should be sufficient. However, if the user changes
  72. // the dimensions of the texture, format or usage, a new instance of GPUTexture is required.
  73. textureProperties.textureGPU.destroy();
  74. }
  75. textureProperties.textureGPU = this._createTexture( texture );
  76. textureProperties.version = texture.version;
  77. forceUpdate = true;
  78. }
  79. }
  80. // if the texture is used for RTT, it's necessary to init it once so the binding
  81. // group's resource definition points to the respective GPUTexture
  82. if ( textureProperties.initializedRTT === false ) {
  83. textureProperties.initializedRTT = true;
  84. forceUpdate = true;
  85. }
  86. return forceUpdate;
  87. }
  88. updateSampler( texture ) {
  89. const array = [];
  90. array.push( texture.wrapS );
  91. array.push( texture.wrapT );
  92. array.push( texture.wrapR );
  93. array.push( texture.magFilter );
  94. array.push( texture.minFilter );
  95. array.push( texture.anisotropy );
  96. const key = array.join();
  97. let samplerGPU = this.samplerCache.get( key );
  98. if ( samplerGPU === undefined ) {
  99. samplerGPU = this.device.createSampler( {
  100. addressModeU: this._convertAddressMode( texture.wrapS ),
  101. addressModeV: this._convertAddressMode( texture.wrapT ),
  102. addressModeW: this._convertAddressMode( texture.wrapR ),
  103. magFilter: this._convertFilterMode( texture.magFilter ),
  104. minFilter: this._convertFilterMode( texture.minFilter ),
  105. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  106. maxAnisotropy: texture.anisotropy
  107. } );
  108. this.samplerCache.set( key, samplerGPU );
  109. }
  110. const textureProperties = this.properties.get( texture );
  111. textureProperties.samplerGPU = samplerGPU;
  112. }
  113. initRenderTarget( renderTarget ) {
  114. const properties = this.properties;
  115. const renderTargetProperties = properties.get( renderTarget );
  116. if ( renderTargetProperties.initialized === undefined ) {
  117. const device = this.device;
  118. const width = renderTarget.width;
  119. const height = renderTarget.height;
  120. const colorTextureGPU = device.createTexture( {
  121. size: {
  122. width: width,
  123. height: height,
  124. depth: 1
  125. },
  126. format: GPUTextureFormat.BRGA8Unorm, // @TODO: Make configurable
  127. usage: GPUTextureUsage.OUTPUT_ATTACHMENT | GPUTextureUsage.SAMPLED
  128. } );
  129. renderTargetProperties.colorTextureGPU = colorTextureGPU;
  130. // When the ".texture" or ".depthTexture" property of a render target is used as a map,
  131. // the renderer has to find the respective GPUTexture objects to setup the bind groups.
  132. // Since it's not possible to see just from a texture object whether it belongs to a render
  133. // target or not, we need the initializedRTT flag.
  134. const textureProperties = properties.get( renderTarget.texture );
  135. textureProperties.textureGPU = colorTextureGPU;
  136. textureProperties.initializedRTT = false;
  137. if ( renderTarget.depthBuffer === true ) {
  138. const depthTextureGPU = device.createTexture( {
  139. size: {
  140. width: width,
  141. height: height,
  142. depth: 1
  143. },
  144. format: GPUTextureFormat.Depth24PlusStencil8, // @TODO: Make configurable
  145. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  146. } );
  147. renderTargetProperties.depthTextureGPU = depthTextureGPU;
  148. if ( renderTarget.depthTexture !== null ) {
  149. const depthTextureProperties = properties.get( renderTarget.depthTexture );
  150. depthTextureProperties.textureGPU = depthTextureGPU;
  151. depthTextureProperties.initializedRTT = false;
  152. }
  153. }
  154. //
  155. const disposeCallback = onRenderTargetDispose.bind( this );
  156. renderTargetProperties.disposeCallback = disposeCallback;
  157. renderTarget.addEventListener( 'dispose', disposeCallback );
  158. //
  159. renderTargetProperties.initialized = true;
  160. }
  161. }
  162. dispose() {
  163. this.samplerCache.clear();
  164. }
  165. _convertAddressMode( value ) {
  166. let addressMode = GPUAddressMode.ClampToEdge;
  167. if ( value === RepeatWrapping ) {
  168. addressMode = GPUAddressMode.Repeat;
  169. } else if ( value === MirroredRepeatWrapping ) {
  170. addressMode = GPUAddressMode.MirrorRepeat;
  171. }
  172. return addressMode;
  173. }
  174. _convertFilterMode( value ) {
  175. let filterMode = GPUFilterMode.Linear;
  176. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  177. filterMode = GPUFilterMode.Nearest;
  178. }
  179. return filterMode;
  180. }
  181. _createTexture( texture ) {
  182. const device = this.device;
  183. const image = texture.image;
  184. const { width, height, depth } = this._getSize( texture );
  185. const needsMipmaps = this._needsMipmaps( texture );
  186. const mipLevelCount = this._getMipLevelCount( texture, width, height, needsMipmaps );
  187. const format = this._getFormat( texture );
  188. let usage = GPUTextureUsage.SAMPLED | GPUTextureUsage.COPY_DST;
  189. if ( needsMipmaps === true ) {
  190. // current mipmap generation requires OUTPUT_ATTACHMENT
  191. usage |= GPUTextureUsage.OUTPUT_ATTACHMENT;
  192. }
  193. // texture creation
  194. const textureGPUDescriptor = {
  195. size: {
  196. width: width,
  197. height: height,
  198. depth: depth,
  199. },
  200. mipLevelCount: mipLevelCount,
  201. sampleCount: 1,
  202. format: format,
  203. usage: usage
  204. };
  205. const textureGPU = device.createTexture( textureGPUDescriptor );
  206. // transfer texture data
  207. if ( texture.isDataTexture ) {
  208. this._copyBufferToTexture( image, format, textureGPU );
  209. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  210. } else if ( texture.isCompressedTexture ) {
  211. this._copyCompressedBufferToTexture( texture.mipmaps, format, textureGPU );
  212. } else if ( texture.isCubeTexture ) {
  213. this._copyCubeMapToTexture( image, texture, textureGPU );
  214. } else {
  215. if ( image !== undefined ) {
  216. // assume HTMLImageElement, HTMLCanvasElement or ImageBitmap
  217. this._getImageBitmap( image, texture ).then( imageBitmap => {
  218. this._copyImageBitmapToTexture( imageBitmap, textureGPU );
  219. if ( needsMipmaps === true ) this._generateMipmaps( textureGPU, textureGPUDescriptor );
  220. } );
  221. }
  222. }
  223. return textureGPU;
  224. }
  225. _copyBufferToTexture( image, format, textureGPU ) {
  226. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  227. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  228. const data = image.data;
  229. const bytesPerTexel = this._getBytesPerTexel( format );
  230. const bytesPerRow = Math.ceil( image.width * bytesPerTexel / 256 ) * 256;
  231. this.device.defaultQueue.writeTexture(
  232. {
  233. texture: textureGPU,
  234. mipLevel: 0
  235. },
  236. data,
  237. {
  238. offset: 0,
  239. bytesPerRow
  240. },
  241. {
  242. width: image.width,
  243. height: image.height,
  244. depth: 1
  245. } );
  246. }
  247. _copyCubeMapToTexture( images, texture, textureGPU ) {
  248. for ( let i = 0; i < images.length; i ++ ) {
  249. const image = images[ i ];
  250. this._getImageBitmap( image, texture ).then( imageBitmap => {
  251. this._copyImageBitmapToTexture( imageBitmap, textureGPU, { x: 0, y: 0, z: i } );
  252. } );
  253. }
  254. }
  255. _copyImageBitmapToTexture( image, textureGPU, origin = { x: 0, y: 0, z: 0 } ) {
  256. this.device.defaultQueue.copyImageBitmapToTexture(
  257. {
  258. imageBitmap: image
  259. }, {
  260. texture: textureGPU,
  261. mipLevel: 0,
  262. origin: origin
  263. }, {
  264. width: image.width,
  265. height: image.height,
  266. depth: 1
  267. }
  268. );
  269. }
  270. _copyCompressedBufferToTexture( mipmaps, format, textureGPU ) {
  271. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  272. const blockData = this._getBlockData( format );
  273. for ( let i = 0; i < mipmaps.length; i ++ ) {
  274. const mipmap = mipmaps[ i ];
  275. const width = mipmap.width;
  276. const height = mipmap.height;
  277. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  278. this.device.defaultQueue.writeTexture(
  279. {
  280. texture: textureGPU,
  281. mipLevel: i
  282. },
  283. mipmap.data,
  284. {
  285. offset: 0,
  286. bytesPerRow
  287. },
  288. {
  289. width: Math.ceil( width / blockData.width ) * blockData.width,
  290. height: Math.ceil( height / blockData.width ) * blockData.width,
  291. depth: 1,
  292. } );
  293. }
  294. }
  295. _generateMipmaps( textureGPU, textureGPUDescriptor ) {
  296. if ( this.utils === null ) {
  297. this.utils = new WebGPUTextureUtils( this.device, this.glslang ); // only create this helper if necessary
  298. }
  299. this.utils.generateMipmaps( textureGPU, textureGPUDescriptor );
  300. }
  301. _getBlockData( format ) {
  302. // this method is only relevant for compressed texture formats
  303. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  304. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  305. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  306. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  307. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  308. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  309. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  310. }
  311. _getBytesPerTexel( format ) {
  312. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return 4;
  313. if ( format === GPUTextureFormat.RGBA16Float ) return 8;
  314. if ( format === GPUTextureFormat.RGBA32Float ) return 16;
  315. }
  316. _getFormat( texture ) {
  317. const format = texture.format;
  318. const type = texture.type;
  319. const encoding = texture.encoding;
  320. let formatGPU;
  321. switch ( format ) {
  322. case RGBA_S3TC_DXT1_Format:
  323. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  324. break;
  325. case RGBA_S3TC_DXT3_Format:
  326. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  327. break;
  328. case RGBA_S3TC_DXT5_Format:
  329. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  330. break;
  331. case RGBFormat:
  332. case RGBAFormat:
  333. switch ( type ) {
  334. case UnsignedByteType:
  335. formatGPU = ( encoding === sRGBEncoding ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  336. break;
  337. case FloatType:
  338. formatGPU = GPUTextureFormat.RGBA32Float;
  339. break;
  340. case HalfFloatType:
  341. formatGPU = GPUTextureFormat.RGBA16Float;
  342. break;
  343. default:
  344. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  345. }
  346. break;
  347. default:
  348. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  349. }
  350. return formatGPU;
  351. }
  352. _getImageBitmap( image, texture ) {
  353. const width = image.width;
  354. const height = image.height;
  355. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  356. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ) {
  357. const options = {};
  358. options.imageOrientation = ( texture.flipY === true ) ? 'flipY' : 'none';
  359. options.premultiplyAlpha = ( texture.premultiplyAlpha === true ) ? 'premultiply' : 'default';
  360. return createImageBitmap( image, 0, 0, width, height, options );
  361. } else {
  362. // assume ImageBitmap
  363. return Promise.resolve( image );
  364. }
  365. }
  366. _getMipLevelCount( texture, width, height, needsMipmaps ) {
  367. let mipLevelCount;
  368. if ( texture.isCompressedTexture ) {
  369. mipLevelCount = texture.mipmaps.length;
  370. } else if ( needsMipmaps === true ) {
  371. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  372. } else {
  373. mipLevelCount = 1; // a texture without mipmaps has a base mip (mipLevel 0)
  374. }
  375. return mipLevelCount;
  376. }
  377. _getSize( texture ) {
  378. const image = texture.image;
  379. let width, height, depth;
  380. if ( texture.isCubeTexture ) {
  381. width = ( image.length > 0 ) ? image[ 0 ].width : 1;
  382. height = ( image.length > 0 ) ? image[ 0 ].height : 1;
  383. depth = 6; // one image for each side of the cube map
  384. } else {
  385. width = ( image !== undefined ) ? image.width : 1;
  386. height = ( image !== undefined ) ? image.height : 1;
  387. depth = 1;
  388. }
  389. return { width, height, depth };
  390. }
  391. _needsMipmaps( texture ) {
  392. return ( texture.isCompressedTexture !== true ) && ( texture.generateMipmaps === true ) && ( texture.minFilter !== NearestFilter ) && ( texture.minFilter !== LinearFilter );
  393. }
  394. }
  395. function onRenderTargetDispose( event ) {
  396. const renderTarget = event.target;
  397. const properties = this.properties;
  398. const renderTargetProperties = properties.get( renderTarget );
  399. renderTarget.removeEventListener( 'dispose', renderTargetProperties.disposeCallback );
  400. renderTargetProperties.colorTextureGPU.destroy();
  401. properties.remove( renderTarget.texture );
  402. if ( renderTarget.depthBuffer === true ) {
  403. renderTargetProperties.depthTextureGPU.destroy();
  404. if ( renderTarget.depthTexture !== null ) {
  405. properties.remove( renderTarget.depthTexture );
  406. }
  407. }
  408. properties.remove( renderTarget );
  409. }
  410. function onTextureDispose( event ) {
  411. const texture = event.target;
  412. const textureProperties = this.properties.get( texture );
  413. textureProperties.textureGPU.destroy();
  414. texture.removeEventListener( 'dispose', textureProperties.disposeCallback );
  415. this.properties.remove( texture );
  416. this.info.memory.textures --;
  417. }
  418. export default WebGPUTextures;