WebGPURenderer.js 27 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166
  1. import { GPUIndexFormat, GPUTextureFormat, GPUFeatureName, GPULoadOp } from './constants.js';
  2. import WebGPUAnimation from './WebGPUAnimation.js';
  3. import WebGPURenderObjects from './WebGPURenderObjects.js';
  4. import WebGPUAttributes from './WebGPUAttributes.js';
  5. import WebGPUGeometries from './WebGPUGeometries.js';
  6. import WebGPUInfo from './WebGPUInfo.js';
  7. import WebGPUProperties from './WebGPUProperties.js';
  8. import WebGPURenderPipelines from './WebGPURenderPipelines.js';
  9. import WebGPUComputePipelines from './WebGPUComputePipelines.js';
  10. import WebGPUBindings from './WebGPUBindings.js';
  11. import WebGPURenderLists from './WebGPURenderLists.js';
  12. import WebGPURenderStates from './WebGPURenderStates.js';
  13. import WebGPUTextures from './WebGPUTextures.js';
  14. import WebGPUBackground from './WebGPUBackground.js';
  15. import WebGPUNodes from './nodes/WebGPUNodes.js';
  16. import WebGPUUtils from './WebGPUUtils.js';
  17. import { Frustum, Matrix4, Vector3, Color, SRGBColorSpace, NoToneMapping, DepthFormat } from 'three';
  18. console.info( 'THREE.WebGPURenderer: Modified Matrix4.makePerspective() and Matrix4.makeOrtographic() to work with WebGPU, see https://github.com/mrdoob/three.js/issues/20276.' );
  19. Matrix4.prototype.makePerspective = function ( left, right, top, bottom, near, far ) {
  20. const te = this.elements;
  21. const x = 2 * near / ( right - left );
  22. const y = 2 * near / ( top - bottom );
  23. const a = ( right + left ) / ( right - left );
  24. const b = ( top + bottom ) / ( top - bottom );
  25. const c = - far / ( far - near );
  26. const d = - far * near / ( far - near );
  27. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  28. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  29. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  30. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  31. return this;
  32. };
  33. Matrix4.prototype.makeOrthographic = function ( left, right, top, bottom, near, far ) {
  34. const te = this.elements;
  35. const w = 1.0 / ( right - left );
  36. const h = 1.0 / ( top - bottom );
  37. const p = 1.0 / ( far - near );
  38. const x = ( right + left ) * w;
  39. const y = ( top + bottom ) * h;
  40. const z = near * p;
  41. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  42. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  43. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 1 * p; te[ 14 ] = - z;
  44. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  45. return this;
  46. };
  47. Frustum.prototype.setFromProjectionMatrix = function ( m ) {
  48. const planes = this.planes;
  49. const me = m.elements;
  50. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  51. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  52. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  53. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  54. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  55. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  56. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  57. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  58. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  59. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  60. return this;
  61. };
  62. const _frustum = new Frustum();
  63. const _projScreenMatrix = new Matrix4();
  64. const _vector3 = new Vector3();
  65. class WebGPURenderer {
  66. constructor( parameters = {} ) {
  67. this.isWebGPURenderer = true;
  68. // public
  69. this.domElement = ( parameters.canvas !== undefined ) ? parameters.canvas : this._createCanvasElement();
  70. this.autoClear = true;
  71. this.autoClearColor = true;
  72. this.autoClearDepth = true;
  73. this.autoClearStencil = true;
  74. this.outputColorSpace = SRGBColorSpace;
  75. this.toneMapping = NoToneMapping;
  76. this.toneMappingExposure = 1.0;
  77. this.sortObjects = true;
  78. // internals
  79. this._parameters = Object.assign( {}, parameters );
  80. this._pixelRatio = 1;
  81. this._width = this.domElement.width;
  82. this._height = this.domElement.height;
  83. this._viewport = null;
  84. this._scissor = null;
  85. this._adapter = null;
  86. this._device = null;
  87. this._context = null;
  88. this._colorBuffer = null;
  89. this._depthBuffer = null;
  90. this._info = null;
  91. this._properties = null;
  92. this._attributes = null;
  93. this._geometries = null;
  94. this._nodes = null;
  95. this._bindings = null;
  96. this._objects = null;
  97. this._renderPipelines = null;
  98. this._computePipelines = null;
  99. this._renderLists = null;
  100. this._renderStates = null;
  101. this._textures = null;
  102. this._background = null;
  103. this._animation = new WebGPUAnimation();
  104. this._currentRenderState = null;
  105. this._opaqueSort = null;
  106. this._transparentSort = null;
  107. this._clearAlpha = 1;
  108. this._clearColor = new Color( 0x000000 );
  109. this._clearDepth = 1;
  110. this._clearStencil = 0;
  111. this._renderTarget = null;
  112. this._initialized = false;
  113. this._initPromise = null;
  114. // some parameters require default values other than "undefined"
  115. this._parameters.antialias = ( parameters.antialias === true );
  116. if ( this._parameters.antialias === true ) {
  117. this._parameters.sampleCount = ( parameters.sampleCount === undefined ) ? 4 : parameters.sampleCount;
  118. } else {
  119. this._parameters.sampleCount = 1;
  120. }
  121. this._parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  122. // backwards compatibility
  123. this.shadow = {
  124. shadowMap: {}
  125. };
  126. }
  127. async init() {
  128. if ( this._initialized === true ) {
  129. throw new Error( 'WebGPURenderer: Device has already been initialized.' );
  130. }
  131. if ( this._initPromise !== null ) {
  132. return this._initPromise;
  133. }
  134. this._initPromise = new Promise( async ( resolve, reject ) => {
  135. const parameters = this._parameters;
  136. const adapterOptions = {
  137. powerPreference: parameters.powerPreference
  138. };
  139. const adapter = await navigator.gpu.requestAdapter( adapterOptions );
  140. if ( adapter === null ) {
  141. reject( new Error( 'WebGPURenderer: Unable to create WebGPU adapter.' ) );
  142. return;
  143. }
  144. // feature support
  145. const features = Object.values( GPUFeatureName );
  146. const supportedFeatures = [];
  147. for ( const name of features ) {
  148. if ( adapter.features.has( name ) ) {
  149. supportedFeatures.push( name );
  150. }
  151. }
  152. const deviceDescriptor = {
  153. requiredFeatures: supportedFeatures,
  154. requiredLimits: parameters.requiredLimits
  155. };
  156. const device = await adapter.requestDevice( deviceDescriptor );
  157. const context = ( parameters.context !== undefined ) ? parameters.context : this.domElement.getContext( 'webgpu' );
  158. this._adapter = adapter;
  159. this._device = device;
  160. this._context = context;
  161. this._configureContext();
  162. this._info = new WebGPUInfo();
  163. this._properties = new WebGPUProperties();
  164. this._attributes = new WebGPUAttributes( device );
  165. this._geometries = new WebGPUGeometries( this._attributes, this._properties, this._info );
  166. this._textures = new WebGPUTextures( device, this._properties, this._info );
  167. this._utils = new WebGPUUtils( this );
  168. this._nodes = new WebGPUNodes( this, this._properties );
  169. this._objects = new WebGPURenderObjects( this, this._nodes, this._geometries, this._info );
  170. this._computePipelines = new WebGPUComputePipelines( device, this._nodes );
  171. this._renderPipelines = new WebGPURenderPipelines( device, this._nodes, this._utils );
  172. this._bindings = this._renderPipelines.bindings = new WebGPUBindings( device, this._info, this._properties, this._textures, this._renderPipelines, this._computePipelines, this._attributes, this._nodes );
  173. this._renderLists = new WebGPURenderLists();
  174. this._renderStates = new WebGPURenderStates();
  175. this._background = new WebGPUBackground( this, this._properties );
  176. //
  177. this._setupColorBuffer();
  178. this._setupDepthBuffer();
  179. this._animation.setNodes( this._nodes );
  180. this._animation.start();
  181. this._initialized = true;
  182. resolve();
  183. } );
  184. return this._initPromise;
  185. }
  186. async render( scene, camera ) {
  187. if ( this._initialized === false ) await this.init();
  188. // preserve render tree
  189. const nodeFrame = this._nodes.nodeFrame;
  190. const previousRenderId = nodeFrame.renderId;
  191. const previousRenderState = this._currentRenderState;
  192. //
  193. const renderState = this._renderStates.get( scene, camera );
  194. const renderTarget = this._renderTarget;
  195. this._currentRenderState = renderState;
  196. nodeFrame.renderId ++;
  197. //
  198. if ( this._animation.isAnimating === false ) nodeFrame.update();
  199. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  200. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  201. if ( this._info.autoReset === true ) this._info.reset();
  202. this._info.render.frame ++;
  203. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  204. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  205. const renderList = this._renderLists.get( scene, camera );
  206. renderList.init();
  207. this._projectObject( scene, camera, 0, renderList );
  208. renderList.finish();
  209. if ( this.sortObjects === true ) {
  210. renderList.sort( this._opaqueSort, this._transparentSort );
  211. }
  212. // prepare render pass descriptor
  213. renderState.descriptorGPU = {
  214. colorAttachments: [ {
  215. view: null
  216. } ],
  217. depthStencilAttachment: {
  218. view: null
  219. }
  220. };
  221. const colorAttachment = renderState.descriptorGPU.colorAttachments[ 0 ];
  222. const depthStencilAttachment = renderState.descriptorGPU.depthStencilAttachment;
  223. if ( renderTarget !== null ) {
  224. this._textures.initRenderTarget( renderTarget );
  225. // @TODO: Support RenderTarget with antialiasing.
  226. const renderTargetProperties = this._properties.get( renderTarget );
  227. colorAttachment.view = renderTargetProperties.colorTextureGPU.createView();
  228. depthStencilAttachment.view = renderTargetProperties.depthTextureGPU.createView();
  229. renderState.stencil = renderTarget.depthTexture ? renderTarget.depthTexture.format !== DepthFormat : true;
  230. } else {
  231. if ( this._parameters.antialias === true ) {
  232. colorAttachment.view = this._colorBuffer.createView();
  233. colorAttachment.resolveTarget = this._context.getCurrentTexture().createView();
  234. } else {
  235. colorAttachment.view = this._context.getCurrentTexture().createView();
  236. colorAttachment.resolveTarget = undefined;
  237. }
  238. depthStencilAttachment.view = this._depthBuffer.createView();
  239. }
  240. //
  241. this._nodes.updateEnvironment( scene );
  242. this._nodes.updateFog( scene );
  243. this._nodes.updateBackground( scene );
  244. this._nodes.updateToneMapping();
  245. //
  246. this._background.update( scene, renderList, renderState );
  247. // start render pass
  248. const device = this._device;
  249. renderState.encoderGPU = device.createCommandEncoder( {} );
  250. renderState.currentPassGPU = renderState.encoderGPU.beginRenderPass( renderState.descriptorGPU );
  251. // global rasterization settings for all renderable objects
  252. const vp = this._viewport;
  253. if ( vp !== null ) {
  254. const width = Math.floor( vp.width * this._pixelRatio );
  255. const height = Math.floor( vp.height * this._pixelRatio );
  256. renderState.currentPassGPU.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  257. }
  258. const sc = this._scissor;
  259. if ( sc !== null ) {
  260. const width = Math.floor( sc.width * this._pixelRatio );
  261. const height = Math.floor( sc.height * this._pixelRatio );
  262. renderState.currentPassGPU.setScissorRect( sc.x, sc.y, width, height );
  263. }
  264. // process render lists
  265. const opaqueObjects = renderList.opaque;
  266. const transparentObjects = renderList.transparent;
  267. const lightsNode = renderList.lightsNode;
  268. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, scene, lightsNode, renderState );
  269. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, scene, lightsNode, renderState );
  270. // finish render pass
  271. renderState.currentPassGPU.end();
  272. device.queue.submit( [ renderState.encoderGPU.finish() ] );
  273. // restore render tree
  274. nodeFrame.renderId = previousRenderId;
  275. this._currentRenderState = previousRenderState;
  276. }
  277. setAnimationLoop( callback ) {
  278. if ( this._initialized === false ) this.init();
  279. const animation = this._animation;
  280. animation.setAnimationLoop( callback );
  281. ( callback === null ) ? animation.stop() : animation.start();
  282. }
  283. async getArrayBuffer( attribute ) {
  284. return await this._attributes.getArrayBuffer( attribute );
  285. }
  286. getContext() {
  287. return this._context;
  288. }
  289. getPixelRatio() {
  290. return this._pixelRatio;
  291. }
  292. getDrawingBufferSize( target ) {
  293. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  294. }
  295. getSize( target ) {
  296. return target.set( this._width, this._height );
  297. }
  298. setPixelRatio( value = 1 ) {
  299. this._pixelRatio = value;
  300. this.setSize( this._width, this._height, false );
  301. }
  302. setDrawingBufferSize( width, height, pixelRatio ) {
  303. this._width = width;
  304. this._height = height;
  305. this._pixelRatio = pixelRatio;
  306. this.domElement.width = Math.floor( width * pixelRatio );
  307. this.domElement.height = Math.floor( height * pixelRatio );
  308. this._configureContext();
  309. this._setupColorBuffer();
  310. this._setupDepthBuffer();
  311. }
  312. setSize( width, height, updateStyle = true ) {
  313. this._width = width;
  314. this._height = height;
  315. this.domElement.width = Math.floor( width * this._pixelRatio );
  316. this.domElement.height = Math.floor( height * this._pixelRatio );
  317. if ( updateStyle === true ) {
  318. this.domElement.style.width = width + 'px';
  319. this.domElement.style.height = height + 'px';
  320. }
  321. this._configureContext();
  322. this._setupColorBuffer();
  323. this._setupDepthBuffer();
  324. }
  325. setOpaqueSort( method ) {
  326. this._opaqueSort = method;
  327. }
  328. setTransparentSort( method ) {
  329. this._transparentSort = method;
  330. }
  331. getScissor( target ) {
  332. const scissor = this._scissor;
  333. target.x = scissor.x;
  334. target.y = scissor.y;
  335. target.width = scissor.width;
  336. target.height = scissor.height;
  337. return target;
  338. }
  339. setScissor( x, y, width, height ) {
  340. if ( x === null ) {
  341. this._scissor = null;
  342. } else {
  343. this._scissor = {
  344. x: x,
  345. y: y,
  346. width: width,
  347. height: height
  348. };
  349. }
  350. }
  351. copyFramebufferToRenderTarget( renderTarget ) {
  352. const renderState = this._currentRenderState;
  353. const { encoderGPU, descriptorGPU } = renderState;
  354. const texture = renderTarget.texture;
  355. texture.internalFormat = GPUTextureFormat.BGRA8Unorm;
  356. this._textures.initRenderTarget( renderTarget );
  357. const sourceGPU = this._context.getCurrentTexture();
  358. const destinationGPU = this._textures.getTextureGPU( texture );
  359. renderState.currentPassGPU.end();
  360. encoderGPU.copyTextureToTexture(
  361. {
  362. texture: sourceGPU
  363. },
  364. {
  365. texture: destinationGPU
  366. },
  367. [
  368. texture.image.width,
  369. texture.image.height
  370. ]
  371. );
  372. descriptorGPU.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  373. if ( renderState.depth ) descriptorGPU.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  374. if ( renderState.stencil ) descriptorGPU.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  375. renderState.currentPassGPU = encoderGPU.beginRenderPass( descriptorGPU );
  376. }
  377. getViewport( target ) {
  378. const viewport = this._viewport;
  379. target.x = viewport.x;
  380. target.y = viewport.y;
  381. target.width = viewport.width;
  382. target.height = viewport.height;
  383. target.minDepth = viewport.minDepth;
  384. target.maxDepth = viewport.maxDepth;
  385. return target;
  386. }
  387. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  388. if ( x === null ) {
  389. this._viewport = null;
  390. } else {
  391. this._viewport = {
  392. x: x,
  393. y: y,
  394. width: width,
  395. height: height,
  396. minDepth: minDepth,
  397. maxDepth: maxDepth
  398. };
  399. }
  400. }
  401. getClearColor( target ) {
  402. return target.copy( this._clearColor );
  403. }
  404. setClearColor( color, alpha = 1 ) {
  405. this._clearColor.set( color );
  406. this._clearAlpha = alpha;
  407. }
  408. getClearAlpha() {
  409. return this._clearAlpha;
  410. }
  411. setClearAlpha( alpha ) {
  412. this._clearAlpha = alpha;
  413. }
  414. getClearDepth() {
  415. return this._clearDepth;
  416. }
  417. setClearDepth( depth ) {
  418. this._clearDepth = depth;
  419. }
  420. getClearStencil() {
  421. return this._clearStencil;
  422. }
  423. setClearStencil( stencil ) {
  424. this._clearStencil = stencil;
  425. }
  426. clear() {
  427. if ( this._background ) this._background.clear();
  428. }
  429. dispose() {
  430. this._objects.dispose();
  431. this._properties.dispose();
  432. this._renderPipelines.dispose();
  433. this._computePipelines.dispose();
  434. this._nodes.dispose();
  435. this._bindings.dispose();
  436. this._info.dispose();
  437. this._renderLists.dispose();
  438. this._renderStates.dispose();
  439. this._textures.dispose();
  440. this.setRenderTarget( null );
  441. this.setAnimationLoop( null );
  442. }
  443. setRenderTarget( renderTarget ) {
  444. this._renderTarget = renderTarget;
  445. }
  446. async compute( ...computeNodes ) {
  447. if ( this._initialized === false ) await this.init();
  448. const device = this._device;
  449. const computePipelines = this._computePipelines;
  450. const cmdEncoder = device.createCommandEncoder( {} );
  451. const passEncoder = cmdEncoder.beginComputePass();
  452. for ( const computeNode of computeNodes ) {
  453. // onInit
  454. if ( computePipelines.has( computeNode ) === false ) {
  455. computeNode.onInit( { renderer: this } );
  456. }
  457. // pipeline
  458. const pipeline = computePipelines.get( computeNode );
  459. passEncoder.setPipeline( pipeline );
  460. // node
  461. //this._nodes.update( computeNode );
  462. // bind group
  463. const bindGroup = this._bindings.getForCompute( computeNode ).group;
  464. this._bindings.update( computeNode );
  465. passEncoder.setBindGroup( 0, bindGroup );
  466. passEncoder.dispatchWorkgroups( computeNode.dispatchCount );
  467. }
  468. passEncoder.end();
  469. device.queue.submit( [ cmdEncoder.finish() ] );
  470. }
  471. getRenderTarget() {
  472. return this._renderTarget;
  473. }
  474. hasFeature( name ) {
  475. if ( this._initialized === false ) {
  476. throw new Error( 'THREE.WebGPURenderer: Renderer must be initialized before testing features.' );
  477. }
  478. //
  479. const features = Object.values( GPUFeatureName );
  480. if ( features.includes( name ) === false ) {
  481. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  482. }
  483. //
  484. return this._adapter.features.has( name );
  485. }
  486. _projectObject( object, camera, groupOrder, renderList ) {
  487. if ( object.visible === false ) return;
  488. const visible = object.layers.test( camera.layers );
  489. if ( visible ) {
  490. if ( object.isGroup ) {
  491. groupOrder = object.renderOrder;
  492. } else if ( object.isLOD ) {
  493. if ( object.autoUpdate === true ) object.update( camera );
  494. } else if ( object.isLight ) {
  495. renderList.pushLight( object );
  496. } else if ( object.isSprite ) {
  497. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  498. if ( this.sortObjects === true ) {
  499. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  500. }
  501. const geometry = object.geometry;
  502. const material = object.material;
  503. if ( material.visible ) {
  504. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  505. }
  506. }
  507. } else if ( object.isLineLoop ) {
  508. console.error( 'THREE.WebGPURenderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  509. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  510. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  511. const geometry = object.geometry;
  512. const material = object.material;
  513. if ( this.sortObjects === true ) {
  514. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  515. _vector3
  516. .copy( geometry.boundingSphere.center )
  517. .applyMatrix4( object.matrixWorld )
  518. .applyMatrix4( _projScreenMatrix );
  519. }
  520. if ( Array.isArray( material ) ) {
  521. const groups = geometry.groups;
  522. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  523. const group = groups[ i ];
  524. const groupMaterial = material[ group.materialIndex ];
  525. if ( groupMaterial && groupMaterial.visible ) {
  526. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  527. }
  528. }
  529. } else if ( material.visible ) {
  530. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  531. }
  532. }
  533. }
  534. }
  535. const children = object.children;
  536. for ( let i = 0, l = children.length; i < l; i ++ ) {
  537. this._projectObject( children[ i ], camera, groupOrder, renderList );
  538. }
  539. }
  540. _renderObjects( renderList, camera, scene, lightsNode ) {
  541. // process renderable objects
  542. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  543. const renderItem = renderList[ i ];
  544. // @TODO: Add support for multiple materials per object. This will require to extract
  545. // the material from the renderItem object and pass it with its group data to _renderObject().
  546. const { object, geometry, material, group } = renderItem;
  547. if ( camera.isArrayCamera ) {
  548. const cameras = camera.cameras;
  549. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  550. const camera2 = cameras[ j ];
  551. if ( object.layers.test( camera2.layers ) ) {
  552. const vp = camera2.viewport;
  553. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  554. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  555. this._currentRenderState.currentPassGPU.setViewport( vp.x, vp.y, vp.width, vp.height, minDepth, maxDepth );
  556. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  557. }
  558. }
  559. } else {
  560. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  561. }
  562. }
  563. }
  564. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  565. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  566. //
  567. object.onBeforeRender( this, scene, camera, geometry, material, group );
  568. //
  569. const renderObject = this._getRenderObject( object, material, scene, camera, lightsNode );
  570. //
  571. this._nodes.updateBefore( renderObject );
  572. //
  573. const passEncoder = this._currentRenderState.currentPassGPU;
  574. const info = this._info;
  575. //
  576. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  577. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  578. // updates
  579. this._nodes.update( renderObject );
  580. this._geometries.update( renderObject );
  581. this._bindings.update( renderObject );
  582. // pipeline
  583. const renderPipeline = this._renderPipelines.get( renderObject );
  584. passEncoder.setPipeline( renderPipeline.pipeline );
  585. // bind group
  586. const bindGroup = this._bindings.get( renderObject ).group;
  587. passEncoder.setBindGroup( 0, bindGroup );
  588. // index
  589. const index = this._geometries.getIndex( renderObject );
  590. const hasIndex = ( index !== null );
  591. if ( hasIndex === true ) {
  592. this._setupIndexBuffer( index, passEncoder );
  593. }
  594. // vertex buffers
  595. this._setupVertexBuffers( geometry.attributes, passEncoder, renderPipeline );
  596. // draw
  597. const drawRange = geometry.drawRange;
  598. const firstVertex = drawRange.start;
  599. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.isInstancedMesh ? object.count : 1 );
  600. if ( hasIndex === true ) {
  601. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  602. passEncoder.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  603. info.update( object, indexCount, instanceCount );
  604. } else {
  605. const positionAttribute = geometry.attributes.position;
  606. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  607. passEncoder.draw( vertexCount, instanceCount, firstVertex, 0 );
  608. info.update( object, vertexCount, instanceCount );
  609. }
  610. }
  611. _getRenderObject( object, material, scene, camera, lightsNode ) {
  612. const renderObject = this._objects.get( object, material, scene, camera, lightsNode );
  613. const renderObjectProperties = this._properties.get( renderObject );
  614. if ( renderObjectProperties.initialized !== true ) {
  615. renderObjectProperties.initialized = true;
  616. const dispose = () => {
  617. this._renderPipelines.remove( renderObject );
  618. this._nodes.remove( renderObject );
  619. this._properties.remove( renderObject );
  620. this._objects.remove( object, material, scene, camera, lightsNode );
  621. renderObject.material.removeEventListener( 'dispose', dispose );
  622. };
  623. renderObject.material.addEventListener( 'dispose', dispose );
  624. }
  625. const cacheKey = renderObject.getCacheKey();
  626. if ( renderObjectProperties.cacheKey !== cacheKey ) {
  627. renderObjectProperties.cacheKey = cacheKey;
  628. this._renderPipelines.remove( renderObject );
  629. this._nodes.remove( renderObject );
  630. }
  631. return renderObject;
  632. }
  633. _setupIndexBuffer( index, encoder ) {
  634. const buffer = this._attributes.get( index ).buffer;
  635. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  636. encoder.setIndexBuffer( buffer, indexFormat );
  637. }
  638. _setupVertexBuffers( geometryAttributes, encoder, renderPipeline ) {
  639. const shaderAttributes = renderPipeline.shaderAttributes;
  640. for ( const shaderAttribute of shaderAttributes ) {
  641. const name = shaderAttribute.name;
  642. const slot = shaderAttribute.slot;
  643. const attribute = geometryAttributes[ name ];
  644. if ( attribute !== undefined ) {
  645. const buffer = this._attributes.get( attribute ).buffer;
  646. encoder.setVertexBuffer( slot, buffer );
  647. }
  648. }
  649. }
  650. _setupColorBuffer() {
  651. const device = this._device;
  652. if ( device ) {
  653. if ( this._colorBuffer ) this._colorBuffer.destroy();
  654. this._colorBuffer = this._device.createTexture( {
  655. label: 'colorBuffer',
  656. size: {
  657. width: Math.floor( this._width * this._pixelRatio ),
  658. height: Math.floor( this._height * this._pixelRatio ),
  659. depthOrArrayLayers: 1
  660. },
  661. sampleCount: this._parameters.sampleCount,
  662. format: GPUTextureFormat.BGRA8Unorm,
  663. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  664. } );
  665. }
  666. }
  667. _setupDepthBuffer() {
  668. const device = this._device;
  669. if ( device ) {
  670. if ( this._depthBuffer ) this._depthBuffer.destroy();
  671. this._depthBuffer = this._device.createTexture( {
  672. label: 'depthBuffer',
  673. size: {
  674. width: Math.floor( this._width * this._pixelRatio ),
  675. height: Math.floor( this._height * this._pixelRatio ),
  676. depthOrArrayLayers: 1
  677. },
  678. sampleCount: this._parameters.sampleCount,
  679. format: GPUTextureFormat.Depth24PlusStencil8,
  680. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  681. } );
  682. }
  683. }
  684. _configureContext() {
  685. const device = this._device;
  686. if ( device ) {
  687. this._context.configure( {
  688. device: device,
  689. format: GPUTextureFormat.BGRA8Unorm,
  690. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  691. alphaMode: 'premultiplied'
  692. } );
  693. }
  694. }
  695. _createCanvasElement() {
  696. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  697. canvas.style.display = 'block';
  698. return canvas;
  699. }
  700. }
  701. export default WebGPURenderer;