WebGPURenderer.js 17 KB

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