WebGPURenderer.js 16 KB

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