WebGPURenderer.js 14 KB

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