WebGPURenderer.js 16 KB

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