WebGPURenderer.js 18 KB

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