WebGPURenderer.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  203. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  204. const renderList = this._renderLists.get( scene, camera );
  205. renderList.init();
  206. this._projectObject( scene, camera, 0, renderList );
  207. renderList.finish();
  208. if ( this.sortObjects === true ) {
  209. renderList.sort( this._opaqueSort, this._transparentSort );
  210. }
  211. // prepare render pass descriptor
  212. renderState.descriptorGPU = {
  213. colorAttachments: [ {
  214. view: null
  215. } ],
  216. depthStencilAttachment: {
  217. view: null
  218. }
  219. };
  220. const colorAttachment = renderState.descriptorGPU.colorAttachments[ 0 ];
  221. const depthStencilAttachment = renderState.descriptorGPU.depthStencilAttachment;
  222. if ( renderTarget !== null ) {
  223. this._textures.initRenderTarget( renderTarget );
  224. // @TODO: Support RenderTarget with antialiasing.
  225. const renderTargetProperties = this._properties.get( renderTarget );
  226. colorAttachment.view = renderTargetProperties.colorTextureGPU.createView();
  227. depthStencilAttachment.view = renderTargetProperties.depthTextureGPU.createView();
  228. renderState.stencil = renderTarget.depthTexture ? renderTarget.depthTexture.format !== DepthFormat : true;
  229. } else {
  230. if ( this._parameters.antialias === true ) {
  231. colorAttachment.view = this._colorBuffer.createView();
  232. colorAttachment.resolveTarget = this._context.getCurrentTexture().createView();
  233. } else {
  234. colorAttachment.view = this._context.getCurrentTexture().createView();
  235. colorAttachment.resolveTarget = undefined;
  236. }
  237. depthStencilAttachment.view = this._depthBuffer.createView();
  238. }
  239. //
  240. this._nodes.updateEnvironment( scene );
  241. this._nodes.updateFog( scene );
  242. this._nodes.updateBackground( scene );
  243. this._nodes.updateToneMapping();
  244. //
  245. this._background.update( scene, renderList, renderState );
  246. // start render pass
  247. const device = this._device;
  248. renderState.encoderGPU = device.createCommandEncoder( {} );
  249. renderState.currentPassGPU = renderState.encoderGPU.beginRenderPass( renderState.descriptorGPU );
  250. // global rasterization settings for all renderable objects
  251. const vp = this._viewport;
  252. if ( vp !== null ) {
  253. const width = Math.floor( vp.width * this._pixelRatio );
  254. const height = Math.floor( vp.height * this._pixelRatio );
  255. renderState.currentPassGPU.setViewport( vp.x, vp.y, width, height, vp.minDepth, vp.maxDepth );
  256. }
  257. const sc = this._scissor;
  258. if ( sc !== null ) {
  259. const width = Math.floor( sc.width * this._pixelRatio );
  260. const height = Math.floor( sc.height * this._pixelRatio );
  261. renderState.currentPassGPU.setScissorRect( sc.x, sc.y, width, height );
  262. }
  263. // process render lists
  264. const opaqueObjects = renderList.opaque;
  265. const transparentObjects = renderList.transparent;
  266. const lightsNode = renderList.lightsNode;
  267. if ( opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, scene, lightsNode, renderState );
  268. if ( transparentObjects.length > 0 ) this._renderObjects( transparentObjects, camera, scene, lightsNode, renderState );
  269. // finish render pass
  270. renderState.currentPassGPU.end();
  271. device.queue.submit( [ renderState.encoderGPU.finish() ] );
  272. // restore render tree
  273. nodeFrame.renderId = previousRenderId;
  274. this._currentRenderState = previousRenderState;
  275. }
  276. setAnimationLoop( callback ) {
  277. if ( this._initialized === false ) this.init();
  278. const animation = this._animation;
  279. animation.setAnimationLoop( callback );
  280. ( callback === null ) ? animation.stop() : animation.start();
  281. }
  282. async getArrayBuffer( attribute ) {
  283. return await this._attributes.getArrayBuffer( attribute );
  284. }
  285. getContext() {
  286. return this._context;
  287. }
  288. getPixelRatio() {
  289. return this._pixelRatio;
  290. }
  291. getDrawingBufferSize( target ) {
  292. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  293. }
  294. getSize( target ) {
  295. return target.set( this._width, this._height );
  296. }
  297. setPixelRatio( value = 1 ) {
  298. this._pixelRatio = value;
  299. this.setSize( this._width, this._height, false );
  300. }
  301. setDrawingBufferSize( width, height, pixelRatio ) {
  302. this._width = width;
  303. this._height = height;
  304. this._pixelRatio = pixelRatio;
  305. this.domElement.width = Math.floor( width * pixelRatio );
  306. this.domElement.height = Math.floor( height * pixelRatio );
  307. this._configureContext();
  308. this._setupColorBuffer();
  309. this._setupDepthBuffer();
  310. }
  311. setSize( width, height, updateStyle = true ) {
  312. this._width = width;
  313. this._height = height;
  314. this.domElement.width = Math.floor( width * this._pixelRatio );
  315. this.domElement.height = Math.floor( height * this._pixelRatio );
  316. if ( updateStyle === true ) {
  317. this.domElement.style.width = width + 'px';
  318. this.domElement.style.height = height + 'px';
  319. }
  320. this._configureContext();
  321. this._setupColorBuffer();
  322. this._setupDepthBuffer();
  323. }
  324. setOpaqueSort( method ) {
  325. this._opaqueSort = method;
  326. }
  327. setTransparentSort( method ) {
  328. this._transparentSort = method;
  329. }
  330. getScissor( target ) {
  331. const scissor = this._scissor;
  332. target.x = scissor.x;
  333. target.y = scissor.y;
  334. target.width = scissor.width;
  335. target.height = scissor.height;
  336. return target;
  337. }
  338. setScissor( x, y, width, height ) {
  339. if ( x === null ) {
  340. this._scissor = null;
  341. } else {
  342. this._scissor = {
  343. x: x,
  344. y: y,
  345. width: width,
  346. height: height
  347. };
  348. }
  349. }
  350. copyFramebufferToRenderTarget( renderTarget ) {
  351. const renderState = this._currentRenderState;
  352. const { encoderGPU, descriptorGPU } = renderState;
  353. const texture = renderTarget.texture;
  354. texture.internalFormat = GPUTextureFormat.BGRA8Unorm;
  355. this._textures.initRenderTarget( renderTarget );
  356. const sourceGPU = this._context.getCurrentTexture();
  357. const destinationGPU = this._textures.getTextureGPU( texture );
  358. renderState.currentPassGPU.end();
  359. encoderGPU.copyTextureToTexture(
  360. {
  361. texture: sourceGPU
  362. },
  363. {
  364. texture: destinationGPU
  365. },
  366. [
  367. texture.image.width,
  368. texture.image.height
  369. ]
  370. );
  371. descriptorGPU.colorAttachments[ 0 ].loadOp = GPULoadOp.Load;
  372. if ( renderState.depth ) descriptorGPU.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  373. if ( renderState.stencil ) descriptorGPU.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  374. renderState.currentPassGPU = encoderGPU.beginRenderPass( descriptorGPU );
  375. }
  376. getViewport( target ) {
  377. const viewport = this._viewport;
  378. target.x = viewport.x;
  379. target.y = viewport.y;
  380. target.width = viewport.width;
  381. target.height = viewport.height;
  382. target.minDepth = viewport.minDepth;
  383. target.maxDepth = viewport.maxDepth;
  384. return target;
  385. }
  386. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  387. if ( x === null ) {
  388. this._viewport = null;
  389. } else {
  390. this._viewport = {
  391. x: x,
  392. y: y,
  393. width: width,
  394. height: height,
  395. minDepth: minDepth,
  396. maxDepth: maxDepth
  397. };
  398. }
  399. }
  400. getClearColor( target ) {
  401. return target.copy( this._clearColor );
  402. }
  403. setClearColor( color, alpha = 1 ) {
  404. this._clearColor.set( color );
  405. this._clearAlpha = alpha;
  406. }
  407. getClearAlpha() {
  408. return this._clearAlpha;
  409. }
  410. setClearAlpha( alpha ) {
  411. this._clearAlpha = alpha;
  412. }
  413. getClearDepth() {
  414. return this._clearDepth;
  415. }
  416. setClearDepth( depth ) {
  417. this._clearDepth = depth;
  418. }
  419. getClearStencil() {
  420. return this._clearStencil;
  421. }
  422. setClearStencil( stencil ) {
  423. this._clearStencil = stencil;
  424. }
  425. clear() {
  426. if ( this._background ) this._background.clear();
  427. }
  428. dispose() {
  429. this._objects.dispose();
  430. this._properties.dispose();
  431. this._renderPipelines.dispose();
  432. this._computePipelines.dispose();
  433. this._nodes.dispose();
  434. this._bindings.dispose();
  435. this._info.dispose();
  436. this._renderLists.dispose();
  437. this._renderStates.dispose();
  438. this._textures.dispose();
  439. this.setRenderTarget( null );
  440. this.setAnimationLoop( null );
  441. }
  442. setRenderTarget( renderTarget ) {
  443. this._renderTarget = renderTarget;
  444. }
  445. async compute( ...computeNodes ) {
  446. if ( this._initialized === false ) await this.init();
  447. const device = this._device;
  448. const computePipelines = this._computePipelines;
  449. const cmdEncoder = device.createCommandEncoder( {} );
  450. const passEncoder = cmdEncoder.beginComputePass();
  451. for ( const computeNode of computeNodes ) {
  452. // onInit
  453. if ( computePipelines.has( computeNode ) === false ) {
  454. computeNode.onInit( { renderer: this } );
  455. }
  456. // pipeline
  457. const pipeline = computePipelines.get( computeNode );
  458. passEncoder.setPipeline( pipeline );
  459. // node
  460. //this._nodes.update( computeNode );
  461. // bind group
  462. const bindGroup = this._bindings.getForCompute( computeNode ).group;
  463. this._bindings.update( computeNode );
  464. passEncoder.setBindGroup( 0, bindGroup );
  465. passEncoder.dispatchWorkgroups( computeNode.dispatchCount );
  466. }
  467. passEncoder.end();
  468. device.queue.submit( [ cmdEncoder.finish() ] );
  469. }
  470. getRenderTarget() {
  471. return this._renderTarget;
  472. }
  473. hasFeature( name ) {
  474. if ( this._initialized === false ) {
  475. throw new Error( 'THREE.WebGPURenderer: Renderer must be initialized before testing features.' );
  476. }
  477. //
  478. const features = Object.values( GPUFeatureName );
  479. if ( features.includes( name ) === false ) {
  480. throw new Error( 'THREE.WebGPURenderer: Unknown WebGPU GPU feature: ' + name );
  481. }
  482. //
  483. return this._adapter.features.has( name );
  484. }
  485. _projectObject( object, camera, groupOrder, renderList ) {
  486. if ( object.visible === false ) return;
  487. const visible = object.layers.test( camera.layers );
  488. if ( visible ) {
  489. if ( object.isGroup ) {
  490. groupOrder = object.renderOrder;
  491. } else if ( object.isLOD ) {
  492. if ( object.autoUpdate === true ) object.update( camera );
  493. } else if ( object.isLight ) {
  494. renderList.pushLight( object );
  495. } else if ( object.isSprite ) {
  496. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  497. if ( this.sortObjects === true ) {
  498. _vector3.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  499. }
  500. const geometry = object.geometry;
  501. const material = object.material;
  502. if ( material.visible ) {
  503. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  504. }
  505. }
  506. } else if ( object.isLineLoop ) {
  507. console.error( 'THREE.WebGPURenderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  508. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  509. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  510. const geometry = object.geometry;
  511. const material = object.material;
  512. if ( this.sortObjects === true ) {
  513. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  514. _vector3
  515. .copy( geometry.boundingSphere.center )
  516. .applyMatrix4( object.matrixWorld )
  517. .applyMatrix4( _projScreenMatrix );
  518. }
  519. if ( Array.isArray( material ) ) {
  520. const groups = geometry.groups;
  521. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  522. const group = groups[ i ];
  523. const groupMaterial = material[ group.materialIndex ];
  524. if ( groupMaterial && groupMaterial.visible ) {
  525. renderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  526. }
  527. }
  528. } else if ( material.visible ) {
  529. renderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  530. }
  531. }
  532. }
  533. }
  534. const children = object.children;
  535. for ( let i = 0, l = children.length; i < l; i ++ ) {
  536. this._projectObject( children[ i ], camera, groupOrder, renderList );
  537. }
  538. }
  539. _renderObjects( renderList, camera, scene, lightsNode ) {
  540. // process renderable objects
  541. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  542. const renderItem = renderList[ i ];
  543. // @TODO: Add support for multiple materials per object. This will require to extract
  544. // the material from the renderItem object and pass it with its group data to _renderObject().
  545. const { object, geometry, material, group } = renderItem;
  546. if ( camera.isArrayCamera ) {
  547. const cameras = camera.cameras;
  548. for ( let j = 0, jl = cameras.length; j < jl; j ++ ) {
  549. const camera2 = cameras[ j ];
  550. if ( object.layers.test( camera2.layers ) ) {
  551. const vp = camera2.viewport;
  552. const minDepth = ( vp.minDepth === undefined ) ? 0 : vp.minDepth;
  553. const maxDepth = ( vp.maxDepth === undefined ) ? 1 : vp.maxDepth;
  554. this._currentRenderState.currentPassGPU.setViewport( vp.x, vp.y, vp.width, vp.height, minDepth, maxDepth );
  555. this._renderObject( object, scene, camera2, geometry, material, group, lightsNode );
  556. }
  557. }
  558. } else {
  559. this._renderObject( object, scene, camera, geometry, material, group, lightsNode );
  560. }
  561. }
  562. }
  563. _renderObject( object, scene, camera, geometry, material, group, lightsNode ) {
  564. material = scene.overrideMaterial !== null ? scene.overrideMaterial : material;
  565. //
  566. object.onBeforeRender( this, scene, camera, geometry, material, group );
  567. //
  568. const renderObject = this._getRenderObject( object, material, scene, camera, lightsNode );
  569. //
  570. this._nodes.updateBefore( renderObject );
  571. //
  572. const passEncoder = this._currentRenderState.currentPassGPU;
  573. const info = this._info;
  574. //
  575. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  576. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  577. // updates
  578. this._nodes.update( renderObject );
  579. this._geometries.update( renderObject );
  580. this._bindings.update( renderObject );
  581. // pipeline
  582. const renderPipeline = this._renderPipelines.get( renderObject );
  583. passEncoder.setPipeline( renderPipeline.pipeline );
  584. // bind group
  585. const bindGroup = this._bindings.get( renderObject ).group;
  586. passEncoder.setBindGroup( 0, bindGroup );
  587. // index
  588. const index = this._geometries.getIndex( renderObject );
  589. const hasIndex = ( index !== null );
  590. if ( hasIndex === true ) {
  591. this._setupIndexBuffer( index, passEncoder );
  592. }
  593. // vertex buffers
  594. this._setupVertexBuffers( geometry.attributes, passEncoder, renderPipeline );
  595. // draw
  596. const drawRange = geometry.drawRange;
  597. const firstVertex = drawRange.start;
  598. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.isInstancedMesh ? object.count : 1 );
  599. if ( hasIndex === true ) {
  600. const indexCount = ( drawRange.count !== Infinity ) ? drawRange.count : index.count;
  601. passEncoder.drawIndexed( indexCount, instanceCount, firstVertex, 0, 0 );
  602. info.update( object, indexCount, instanceCount );
  603. } else {
  604. const positionAttribute = geometry.attributes.position;
  605. const vertexCount = ( drawRange.count !== Infinity ) ? drawRange.count : positionAttribute.count;
  606. passEncoder.draw( vertexCount, instanceCount, firstVertex, 0 );
  607. info.update( object, vertexCount, instanceCount );
  608. }
  609. }
  610. _getRenderObject( object, material, scene, camera, lightsNode ) {
  611. const renderObject = this._objects.get( object, material, scene, camera, lightsNode );
  612. const renderObjectProperties = this._properties.get( renderObject );
  613. if ( renderObjectProperties.initialized !== true ) {
  614. renderObjectProperties.initialized = true;
  615. const dispose = () => {
  616. this._renderPipelines.remove( renderObject );
  617. this._nodes.remove( renderObject );
  618. this._properties.remove( renderObject );
  619. this._objects.remove( object, material, scene, camera, lightsNode );
  620. renderObject.material.removeEventListener( 'dispose', dispose );
  621. };
  622. renderObject.material.addEventListener( 'dispose', dispose );
  623. }
  624. const cacheKey = renderObject.getCacheKey();
  625. if ( renderObjectProperties.cacheKey !== cacheKey ) {
  626. renderObjectProperties.cacheKey = cacheKey;
  627. this._renderPipelines.remove( renderObject );
  628. this._nodes.remove( renderObject );
  629. }
  630. return renderObject;
  631. }
  632. _setupIndexBuffer( index, encoder ) {
  633. const buffer = this._attributes.get( index ).buffer;
  634. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  635. encoder.setIndexBuffer( buffer, indexFormat );
  636. }
  637. _setupVertexBuffers( geometryAttributes, encoder, renderPipeline ) {
  638. const shaderAttributes = renderPipeline.shaderAttributes;
  639. for ( const shaderAttribute of shaderAttributes ) {
  640. const name = shaderAttribute.name;
  641. const slot = shaderAttribute.slot;
  642. const attribute = geometryAttributes[ name ];
  643. if ( attribute !== undefined ) {
  644. const buffer = this._attributes.get( attribute ).buffer;
  645. encoder.setVertexBuffer( slot, buffer );
  646. }
  647. }
  648. }
  649. _setupColorBuffer() {
  650. const device = this._device;
  651. if ( device ) {
  652. if ( this._colorBuffer ) this._colorBuffer.destroy();
  653. this._colorBuffer = this._device.createTexture( {
  654. label: 'colorBuffer',
  655. size: {
  656. width: Math.floor( this._width * this._pixelRatio ),
  657. height: Math.floor( this._height * this._pixelRatio ),
  658. depthOrArrayLayers: 1
  659. },
  660. sampleCount: this._parameters.sampleCount,
  661. format: GPUTextureFormat.BGRA8Unorm,
  662. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  663. } );
  664. }
  665. }
  666. _setupDepthBuffer() {
  667. const device = this._device;
  668. if ( device ) {
  669. if ( this._depthBuffer ) this._depthBuffer.destroy();
  670. this._depthBuffer = this._device.createTexture( {
  671. label: 'depthBuffer',
  672. size: {
  673. width: Math.floor( this._width * this._pixelRatio ),
  674. height: Math.floor( this._height * this._pixelRatio ),
  675. depthOrArrayLayers: 1
  676. },
  677. sampleCount: this._parameters.sampleCount,
  678. format: GPUTextureFormat.Depth24PlusStencil8,
  679. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  680. } );
  681. }
  682. }
  683. _configureContext() {
  684. const device = this._device;
  685. if ( device ) {
  686. this._context.configure( {
  687. device: device,
  688. format: GPUTextureFormat.BGRA8Unorm,
  689. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  690. alphaMode: 'premultiplied'
  691. } );
  692. }
  693. }
  694. _createCanvasElement() {
  695. const canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  696. canvas.style.display = 'block';
  697. return canvas;
  698. }
  699. }
  700. export default WebGPURenderer;