WebGPURenderer.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. import { GPUIndexFormat, GPUTextureFormat, GPUStoreOp } from './constants.js';
  2. import WebGPUObjects from './WebGPUObjects.js';
  3. import WebGPUAttributes from './WebGPUAttributes.js';
  4. import WebGPUGeometries from './WebGPUGeometries.js';
  5. import WebGPUInfo from './WebGPUInfo.js';
  6. import WebGPUProperties from './WebGPUProperties.js';
  7. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  8. import WebGPUBindings from './WebGPUBindings.js';
  9. import WebGPURenderLists from './WebGPURenderLists.js';
  10. import WebGPUTextures from './WebGPUTextures.js';
  11. import WebGPUBackground from './WebGPUBackground.js';
  12. import { Frustum, Matrix4, Vector3, Color } from '../../../../build/three.module.js';
  13. console.warn( 'THREE.WebGPURenderer: Modified Matrix4.makePerspective() and Matrix4.makeOrtographic() to work with WebGPU, see https://github.com/mrdoob/three.js/issues/20276.' );
  14. Matrix4.prototype.makePerspective = function ( left, right, top, bottom, near, far ) {
  15. const te = this.elements;
  16. const x = 2 * near / ( right - left );
  17. const y = 2 * near / ( top - bottom );
  18. const a = ( right + left ) / ( right - left );
  19. const b = ( top + bottom ) / ( top - bottom );
  20. const c = - far / ( far - near );
  21. const d = - far * near / ( far - near );
  22. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  23. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  24. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  25. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  26. return this;
  27. };
  28. Matrix4.prototype.makeOrthographic = function ( left, right, top, bottom, near, far ) {
  29. const te = this.elements;
  30. const w = 1.0 / ( right - left );
  31. const h = 1.0 / ( top - bottom );
  32. const p = 1.0 / ( far - near );
  33. const x = ( right + left ) * w;
  34. const y = ( top + bottom ) * h;
  35. const z = near * p;
  36. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  37. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  38. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 1 * p; te[ 14 ] = - z;
  39. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  40. return this;
  41. };
  42. const _frustum = new Frustum();
  43. const _projScreenMatrix = new Matrix4();
  44. const _vector3 = new Vector3();
  45. class WebGPURenderer {
  46. constructor( parameters = {} ) {
  47. // public
  48. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  49. this.parameters = Object.assign( {}, parameters );
  50. this.autoClear = true;
  51. this.autoClearColor = true;
  52. this.autoClearDepth = true;
  53. this.autoClearStencil = true;
  54. this.sortObjects = true;
  55. // internals
  56. this._pixelRatio = 1;
  57. this._width = this.domElement.width;
  58. this._height = this.domElement.height;
  59. this._viewport = null;
  60. this._scissor = null;
  61. this._adapter = null;
  62. this._device = null;
  63. this._context = null;
  64. this._swapChain = null;
  65. this._colorBuffer = null;
  66. this._depthBuffer = null;
  67. this._info = null;
  68. this._properties = null;
  69. this._attributes = null;
  70. this._geometries = null;
  71. this._bindings = null;
  72. this._objects = null;
  73. this._renderPipelines = null;
  74. this._renderLists = null;
  75. this._textures = null;
  76. this._background = null;
  77. this._renderPassDescriptor = null;
  78. this._currentRenderList = null;
  79. this._opaqueSort = null;
  80. this._transparentSort = null;
  81. this._clearAlpha = 1;
  82. this._clearColor = new Color( 0x000000 );
  83. this._clearDepth = 1;
  84. this._clearStencil = 0;
  85. this._renderTarget = null;
  86. // ensure some parameters
  87. this.parameters.antialias = ( this.parameters.antialias === true );
  88. if ( this.parameters.antialias === true ) {
  89. this.parameters.sampleCount = this.parameters.sampleCount || 4;
  90. } else {
  91. this.parameters.sampleCount = 1;
  92. }
  93. }
  94. init() {
  95. return initWebGPU( this );
  96. }
  97. render( scene, camera ) {
  98. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  99. if ( camera.parent === null ) camera.updateMatrixWorld();
  100. if ( this._info.autoReset === true ) this._info.reset();
  101. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  102. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  103. this._currentRenderList = this._renderLists.get( scene, camera );
  104. this._currentRenderList.init();
  105. this._projectObject( scene, camera, 0 );
  106. this._currentRenderList.finish();
  107. if ( this.sortObjects === true ) {
  108. this._currentRenderList.sort( this._opaqueSort, this._transparentSort );
  109. }
  110. // prepare render pass descriptor
  111. const colorAttachment = this._renderPassDescriptor.colorAttachments[ 0 ];
  112. const depthStencilAttachment = this._renderPassDescriptor.depthStencilAttachment;
  113. const renderTarget = this._renderTarget;
  114. if ( renderTarget !== null ) {
  115. // @TODO: Support RenderTarget with antialiasing.
  116. const renderTargetProperties = this._properties.get( renderTarget );
  117. colorAttachment.attachment = renderTargetProperties.colorTextureGPU.createView();
  118. depthStencilAttachment.attachment = renderTargetProperties.depthTextureGPU.createView();
  119. } else {
  120. if ( this.parameters.antialias === true ) {
  121. colorAttachment.attachment = this._colorBuffer.createView();
  122. colorAttachment.resolveTarget = this._swapChain.getCurrentTexture().createView();
  123. } else {
  124. colorAttachment.attachment = this._swapChain.getCurrentTexture().createView();
  125. colorAttachment.resolveTarget = undefined;
  126. }
  127. depthStencilAttachment.attachment = this._depthBuffer.createView();
  128. }
  129. //
  130. this._background.update( scene );
  131. // start render pass
  132. const device = this._device;
  133. const cmdEncoder = device.createCommandEncoder( {} );
  134. const passEncoder = cmdEncoder.beginRenderPass( this._renderPassDescriptor );
  135. // global rasterization settings for all renderable objects
  136. const vp = this._viewport;
  137. if ( vp !== null ) {
  138. const width = Math.floor( vp.width * this._pixelRatio );
  139. const height = Math.floor( vp.height * this._pixelRatio );
  140. passEncoder.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  141. }
  142. const sc = this._scissor;
  143. if ( sc !== null ) {
  144. const width = Math.floor( sc.width * this._pixelRatio );
  145. const height = Math.floor( sc.height * this._pixelRatio );
  146. passEncoder.setScissorRect( sc.x, sc.y, width, height );
  147. }
  148. // process render lists
  149. const opaqueObjects = this._currentRenderList.opaque;
  150. const transparentObjects = this._currentRenderList.transparent;
  151. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, passEncoder );
  152. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, passEncoder );
  153. // finish render pass
  154. passEncoder.endPass();
  155. device.defaultQueue.submit( [ cmdEncoder.finish() ] );
  156. }
  157. getContext() {
  158. return this._context;
  159. }
  160. getPixelRatio() {
  161. return this._pixelRatio;
  162. }
  163. getDrawingBufferSize( target ) {
  164. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  165. }
  166. getSize( target ) {
  167. return target.set( this._width, this._height );
  168. }
  169. setPixelRatio( value = 1 ) {
  170. this._pixelRatio = value;
  171. this.setSize( this._width, this._height, false );
  172. }
  173. setDrawingBufferSize( width, height, pixelRatio ) {
  174. this._width = width;
  175. this._height = height;
  176. this._pixelRatio = pixelRatio;
  177. this.domElement.width = Math.floor( width * pixelRatio );
  178. this.domElement.height = Math.floor( height * pixelRatio );
  179. this._setupColorBuffer();
  180. this._setupDepthBuffer();
  181. }
  182. setSize( width, height, updateStyle = true ) {
  183. this._width = width;
  184. this._height = height;
  185. this.domElement.width = Math.floor( width * this._pixelRatio );
  186. this.domElement.height = Math.floor( height * this._pixelRatio );
  187. if ( updateStyle === true ) {
  188. this.domElement.style.width = width + 'px';
  189. this.domElement.style.height = height + 'px';
  190. }
  191. this._setupColorBuffer();
  192. this._setupDepthBuffer();
  193. }
  194. setOpaqueSort( method ) {
  195. this._opaqueSort = method;
  196. }
  197. setTransparentSort( method ) {
  198. this._transparentSort = method;
  199. }
  200. getScissor( target ) {
  201. const scissor = this._scissor;
  202. target.x = scissor.x;
  203. target.y = scissor.y;
  204. target.width = scissor.width;
  205. target.height = scissor.height;
  206. return target;
  207. }
  208. setScissor( x, y, width, height ) {
  209. if ( x === null ) {
  210. this._scissor = null;
  211. } else {
  212. this._scissor = {
  213. x: x,
  214. y: y,
  215. width: width,
  216. height: height
  217. };
  218. }
  219. }
  220. getViewport( target ) {
  221. const viewport = this._viewport;
  222. target.x = viewport.x;
  223. target.y = viewport.y;
  224. target.width = viewport.width;
  225. target.height = viewport.height;
  226. target.minDepth = viewport.minDepth;
  227. target.maxDepth = viewport.maxDepth;
  228. return target;
  229. }
  230. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  231. if ( x === null ) {
  232. this._viewport = null;
  233. } else {
  234. this._viewport = {
  235. x: x,
  236. y: y,
  237. width: width,
  238. height: height,
  239. minDepth: minDepth,
  240. maxDepth: maxDepth
  241. };
  242. }
  243. }
  244. getClearColor() {
  245. return this._clearColor;
  246. }
  247. setClearColor( color, alpha = 1 ) {
  248. this._clearColor.set( color );
  249. this._clearAlpha = alpha;
  250. }
  251. getClearAlpha() {
  252. return this._clearAlpha;
  253. }
  254. setClearAlpha( alpha ) {
  255. this._clearAlpha = alpha;
  256. }
  257. getClearDepth() {
  258. return this._clearDepth;
  259. }
  260. setClearDepth( depth ) {
  261. this._clearDepth = depth;
  262. }
  263. getClearStencil() {
  264. return this._clearStencil;
  265. }
  266. setClearStencil( stencil ) {
  267. this._clearStencil = stencil;
  268. }
  269. clear() {
  270. this._background.clear();
  271. }
  272. dispose() {
  273. this._objects.dispose();
  274. this._properties.dispose();
  275. this._renderPipelines.dispose();
  276. this._bindings.dispose();
  277. this._info.dispose();
  278. this._renderLists.dispose();
  279. this._textures.dispose();
  280. }
  281. setRenderTarget( renderTarget ) {
  282. this._renderTarget = renderTarget;
  283. if ( renderTarget !== null ) {
  284. this._textures.initRenderTarget( renderTarget );
  285. }
  286. }
  287. _projectObject( object, camera, groupOrder ) {
  288. const info = this._info;
  289. const currentRenderList = this._currentRenderList;
  290. if ( object.visible === false ) return;
  291. const visible = object.layers.test( camera.layers );
  292. if ( visible ) {
  293. if ( object.isGroup ) {
  294. groupOrder = object.renderOrder;
  295. } else if ( object.isLOD ) {
  296. if ( object.autoUpdate === true ) object.update( camera );
  297. } else if ( object.isLight ) {
  298. //currentRenderState.pushLight( object );
  299. if ( object.castShadow ) {
  300. //currentRenderState.pushShadow( object );
  301. }
  302. } else if ( object.isSprite ) {
  303. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  304. if ( this.sortObjects === true ) {
  305. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  306. }
  307. const geometry = object.geometry;
  308. const material = object.material;
  309. if ( material.visible ) {
  310. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  311. }
  312. }
  313. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  314. if ( object.isSkinnedMesh ) {
  315. // update skeleton only once in a frame
  316. if ( object.skeleton.frame !== info.render.frame ) {
  317. object.skeleton.update();
  318. object.skeleton.frame = info.render.frame;
  319. }
  320. }
  321. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  322. if ( this.sortObjects === true ) {
  323. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  324. }
  325. const geometry = object.geometry;
  326. const material = object.material;
  327. if ( Array.isArray( material ) ) {
  328. const groups = geometry.groups;
  329. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  330. const group = groups[ i ];
  331. const groupMaterial = material[ group.materialIndex ];
  332. if ( groupMaterial && groupMaterial.visible ) {
  333. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  334. }
  335. }
  336. } else if ( material.visible ) {
  337. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  338. }
  339. }
  340. }
  341. }
  342. const children = object.children;
  343. for ( let i = 0, l = children.length; i < l; i ++ ) {
  344. this._projectObject( children[ i ], camera, groupOrder );
  345. }
  346. }
  347. _renderObjects( renderList, camera, passEncoder ) {
  348. // process renderable objects
  349. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  350. const renderItem = renderList[ i ];
  351. const object = renderItem.object;
  352. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  353. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  354. this._objects.update( object );
  355. this._bindings.update( object, camera );
  356. this._renderObject( object, passEncoder );
  357. }
  358. }
  359. _renderObject( object, passEncoder ) {
  360. const info = this._info;
  361. // pipeline
  362. const pipeline = this._renderPipelines.get( object );
  363. passEncoder.setPipeline( pipeline );
  364. // bind group
  365. const bindGroup = this._bindings.get( object ).group;
  366. passEncoder.setBindGroup( 0, bindGroup );
  367. // index
  368. const geometry = object.geometry;
  369. const index = geometry.index;
  370. const hasIndex = ( index !== null );
  371. if ( hasIndex === true ) {
  372. this._setupIndexBuffer( index, passEncoder );
  373. }
  374. // vertex buffers
  375. this._setupVertexBuffers( geometry.attributes, passEncoder, pipeline );
  376. // draw
  377. const drawRange = geometry.drawRange;
  378. const firstVertex = drawRange.start;
  379. if ( hasIndex === true ) {
  380. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  381. passEncoder.drawIndexed( indexCount, 1, firstVertex, 0, 0 );
  382. info.update( object, indexCount );
  383. } else {
  384. const positionAttribute = geometry.attributes.position;
  385. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  386. passEncoder.draw( vertexCount, 1, firstVertex, 0 );
  387. info.update( object, vertexCount );
  388. }
  389. }
  390. _setupIndexBuffer( index, encoder ) {
  391. const buffer = this._attributes.get( index ).buffer;
  392. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  393. encoder.setIndexBuffer( buffer, indexFormat );
  394. }
  395. _setupVertexBuffers( geometryAttributes, encoder, pipeline ) {
  396. const shaderAttributes = this._renderPipelines.getShaderAttributes( pipeline );
  397. for ( const shaderAttribute of shaderAttributes ) {
  398. const name = shaderAttribute.name;
  399. const slot = shaderAttribute.slot;
  400. const attribute = geometryAttributes[ name ];
  401. if ( attribute !== undefined ) {
  402. const buffer = this._attributes.get( attribute ).buffer;
  403. encoder.setVertexBuffer( slot, buffer );
  404. }
  405. }
  406. }
  407. _setupColorBuffer() {
  408. const device = this._device;
  409. if ( device ) {
  410. if ( this._colorBuffer ) this._colorBuffer.destroy();
  411. this._colorBuffer = this._device.createTexture( {
  412. size: {
  413. width: this._width * this._pixelRatio,
  414. height: this._height * this._pixelRatio,
  415. depth: 1
  416. },
  417. sampleCount: this.parameters.sampleCount,
  418. format: GPUTextureFormat.BRGA8Unorm,
  419. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  420. } );
  421. }
  422. }
  423. _setupDepthBuffer() {
  424. const device = this._device;
  425. if ( device ) {
  426. if ( this._depthBuffer ) this._depthBuffer.destroy();
  427. this._depthBuffer = this._device.createTexture( {
  428. size: {
  429. width: this._width * this._pixelRatio,
  430. height: this._height * this._pixelRatio,
  431. depth: 1
  432. },
  433. sampleCount: this.parameters.sampleCount,
  434. format: GPUTextureFormat.Depth24PlusStencil8,
  435. usage: GPUTextureUsage.OUTPUT_ATTACHMENT
  436. } );
  437. }
  438. }
  439. }
  440. async function initWebGPU( scope ) {
  441. const parameters = scope.parameters;
  442. const adapterOptions = {
  443. powerPreference: ( parameters.powerPreference !== undefined ) ? parameters.powerPreference : undefined
  444. };
  445. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  446. const deviceDescriptor = {
  447. enabledExtensions: ( parameters.enabledExtensions !== undefined ) ? parameters.enabledExtensions : [],
  448. limits: ( parameters.limits !== undefined ) ? parameters.limits : {}
  449. };
  450. const device = await adapter.requestDevice( deviceDescriptor );
  451. const glslang = await import( 'https://cdn.jsdelivr.net/npm/@webgpu/[email protected]/dist/web-devel/glslang.js' );
  452. const compiler = await glslang.default();
  453. const context = ( parameters.context !== undefined ) ? parameters.context : scope.domElement.getContext( 'gpupresent' );
  454. const swapChain = context.configureSwapChain( {
  455. device: device,
  456. format: GPUTextureFormat.BRGA8Unorm
  457. } );
  458. scope._adapter = adapter;
  459. scope._device = device;
  460. scope._context = context;
  461. scope._swapChain = swapChain;
  462. scope._info = new WebGPUInfo();
  463. scope._properties = new WebGPUProperties();
  464. scope._attributes = new WebGPUAttributes( device );
  465. scope._geometries = new WebGPUGeometries( scope._attributes, scope._info );
  466. scope._textures = new WebGPUTextures( device, scope._properties, scope._info, compiler );
  467. scope._bindings = new WebGPUBindings( device, scope._info, scope._properties, scope._textures );
  468. scope._objects = new WebGPUObjects( scope._geometries, scope._info );
  469. scope._renderPipelines = new WebGPURenderPipelines( device, compiler, scope._bindings, scope.parameters.sampleCount );
  470. scope._renderLists = new WebGPURenderLists();
  471. scope._background = new WebGPUBackground( scope );
  472. //
  473. scope._renderPassDescriptor = {
  474. colorAttachments: [ {
  475. attachment: null
  476. } ],
  477. depthStencilAttachment: {
  478. attachment: null,
  479. depthStoreOp: GPUStoreOp.Store,
  480. stencilStoreOp: GPUStoreOp.Store
  481. }
  482. };
  483. scope._setupColorBuffer();
  484. scope._setupDepthBuffer();
  485. }
  486. export default WebGPURenderer;