WebGPURenderer.js 13 KB

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