WebGPURenderer.js 26 KB

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