webgpu_compute_rasterizer.html 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <title>three.js webgpu - compute rasterizer</title>
  5. <meta charset="utf-8">
  6. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  7. <meta property="og:title" content="three.js webgpu - compute rasterizer">
  8. <meta property="og:type" content="website">
  9. <meta property="og:url" content="https://threejs.org/examples/webgpu_compute_rasterizer.html">
  10. <meta property="og:image" content="https://threejs.org/examples/screenshots/webgpu_compute_rasterizer.jpg">
  11. <link type="text/css" rel="stylesheet" href="example.css">
  12. </head>
  13. <body>
  14. <div id="info">
  15. <a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>
  16. <div class="title-wrapper">
  17. <a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>GPU-Driven Compute Rasterizer</span>
  18. </div>
  19. <small>Rendering <span id="triangleCount"></span> triangles.</small>
  20. </div>
  21. <script type="importmap">
  22. {
  23. "imports": {
  24. "three": "../build/three.webgpu.js",
  25. "three/webgpu": "../build/three.webgpu.js",
  26. "three/tsl": "../build/three.tsl.js",
  27. "three/addons/": "./jsm/"
  28. }
  29. }
  30. </script>
  31. <script type="module">
  32. import * as THREE from 'three/webgpu';
  33. import { Fn, If, Loop, vec4, vec2, uvec4, mat4, uint, float, int, min, max, atomicMax, atomicAdd, atomicStore, atomicLoad, floor, cos, sin, dot, bool, storage, uniform, uniformArray, uv, instanceIndex, vertexIndex, distance, screenSize, time, texture, varyingProperty, sqrt } from 'three/tsl';
  34. import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  35. import { TeapotGeometry } from 'three/addons/geometries/TeapotGeometry.js';
  36. import { Inspector } from 'three/addons/inspector/Inspector.js';
  37. import WebGPU from 'three/addons/capabilities/WebGPU.js';
  38. if ( WebGPU.isAvailable() === false ) {
  39. document.body.appendChild( WebGPU.getErrorMessage() );
  40. throw new Error( 'No WebGPU support' );
  41. }
  42. let camera, renderer, controls;
  43. let computeRasterize, computeClear, computeFrustum, computeDispatch, computeHWArgs;
  44. let quadMesh, hwScene, hwMesh;
  45. let cameraPos, projScreenMatrixUniform, frustumPlanesUniform, cotHalfFovUniform;
  46. let screenTriAttr, screenTriAtomic, screenTriRead;
  47. let screenInstAttr, screenInstAtomic, screenInstRead;
  48. let maxPixels;
  49. const rows = 400;
  50. const cols = 400;
  51. const instanceCount = rows * cols;
  52. const MAX_RASTER_SIZE = 16;
  53. const options = { Mode: 'Meshlet Debug', Rasterizer: 'Both' };
  54. // Buffer visibility packaging configuration
  55. const TRIANGLE_INDEX_BITS = 14; // Bits allocated for triangle index (2^14 = 16384 max triangles)
  56. const TRIANGLE_INDEX_MASK = 0x3FFF; // Bitmask to extract triangle index (14 bits)
  57. const INSTANCE_INDEX_BITS = 18; // Bits allocated for instance id (2^18 = 262144 max instances)
  58. const INSTANCE_INDEX_MASK = 0x3FFFF; // Bitmask to extract instance id (18 bits)
  59. const DEPTH_TRI_MAX = 262143.0; // Maximum 18-bit depth packed above the triangle index
  60. const DEPTH_INST_MAX = 16383.0; // Maximum 14-bit depth packed above the instance id
  61. const background = new THREE.Color( .1, .1, .1 );
  62. init();
  63. async function init() {
  64. renderer = new THREE.WebGPURenderer();
  65. renderer.setPixelRatio( window.devicePixelRatio );
  66. renderer.setSize( window.innerWidth, window.innerHeight );
  67. renderer.setAnimationLoop( animate );
  68. renderer.inspector = new Inspector();
  69. document.body.appendChild( renderer.domElement );
  70. await renderer.init();
  71. camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, .25, 1000000 );
  72. camera.position.set( 0, 15, 50 );
  73. controls = new OrbitControls( camera, renderer.domElement );
  74. controls.target.y = - 1.5;
  75. controls.enableDamping = true;
  76. controls.zoomSpeed = .5;
  77. controls.maxDistance = 1000;
  78. controls.maxPolarAngle = Math.PI / 2;
  79. // Generate LOD Geometries
  80. const lods = [
  81. { geometry: new TeapotGeometry( 1, 10 ), error: 0.0 },
  82. { geometry: new TeapotGeometry( 1, 8 ), error: 0.005 },
  83. { geometry: new TeapotGeometry( 1, 6 ), error: 0.015 },
  84. { geometry: new TeapotGeometry( 1, 5 ), error: 0.03 },
  85. { geometry: new TeapotGeometry( 1, 4 ), error: 0.06 },
  86. { geometry: new TeapotGeometry( 1, 3 ), error: 0.1 },
  87. { geometry: new TeapotGeometry( 1, 2 ), error: 0.2 }
  88. ];
  89. let totalVertices = 0;
  90. let totalIndices = 0;
  91. for ( const lod of lods ) {
  92. const geom = lod.geometry;
  93. const pos = geom.attributes.position;
  94. const uvs = geom.attributes.uv;
  95. const idx = geom.index ? Array.from( geom.index.array ) : Array.from( { length: pos.count }, ( _, i ) => i );
  96. lod.numVertices = pos.count;
  97. lod.numTriangles = idx.length / 3;
  98. lod.vertexOffset = totalVertices;
  99. lod.indexOffset = totalIndices;
  100. lod.positions = pos;
  101. lod.uvs = uvs;
  102. lod.indices = idx;
  103. totalVertices += pos.count;
  104. totalIndices += idx.length;
  105. }
  106. const maxTrianglesPerInstance = lods[ 0 ].numTriangles;
  107. const totalTriangles = rows * cols * maxTrianglesPerInstance;
  108. document.getElementById( 'triangleCount' ).innerText = new Intl.NumberFormat().format( totalTriangles );
  109. const vertexArray = new Float32Array( totalVertices * 4 ); // vec4 padded
  110. const uvArray = new Float32Array( totalVertices * 2 );
  111. const indexArray = new Uint32Array( totalIndices );
  112. const meshletTriangleArray = new Uint32Array( totalIndices / 3 ); // 1 meshlet ID per triangle
  113. let currentMeshletId = 1;
  114. for ( const lod of lods ) {
  115. for ( let i = 0; i < lod.numVertices; i ++ ) {
  116. const vIdx = lod.vertexOffset + i;
  117. vertexArray[ vIdx * 4 + 0 ] = lod.positions.getX( i );
  118. vertexArray[ vIdx * 4 + 1 ] = lod.positions.getY( i );
  119. vertexArray[ vIdx * 4 + 2 ] = lod.positions.getZ( i );
  120. vertexArray[ vIdx * 4 + 3 ] = 1.0;
  121. if ( lod.uvs ) {
  122. uvArray[ vIdx * 2 + 0 ] = lod.uvs.getX( i );
  123. uvArray[ vIdx * 2 + 1 ] = lod.uvs.getY( i );
  124. }
  125. }
  126. let currentTriCount = 0;
  127. for ( let i = 0; i < lod.numTriangles; i ++ ) {
  128. const triIdx = ( lod.indexOffset / 3 ) + i;
  129. indexArray[ triIdx * 3 + 0 ] = lod.vertexOffset + lod.indices[ i * 3 + 0 ];
  130. indexArray[ triIdx * 3 + 1 ] = lod.vertexOffset + lod.indices[ i * 3 + 1 ];
  131. indexArray[ triIdx * 3 + 2 ] = lod.vertexOffset + lod.indices[ i * 3 + 2 ];
  132. if ( currentTriCount >= 126 ) {
  133. currentMeshletId ++;
  134. currentTriCount = 0;
  135. }
  136. meshletTriangleArray[ triIdx ] = currentMeshletId;
  137. currentTriCount ++;
  138. }
  139. currentMeshletId ++;
  140. }
  141. // Precompute Bounding Spheres for each 64-triangle Chunk (Cluster)
  142. let totalChunks = 0;
  143. for ( const lod of lods ) {
  144. lod.numChunks = Math.ceil( lod.numTriangles / 64 );
  145. lod.chunkStart = totalChunks;
  146. totalChunks += lod.numChunks;
  147. }
  148. const chunkBoundsData = new Float32Array( totalChunks * 4 ); // vec4: cx, cy, cz, radius
  149. let currentChunkId = 0;
  150. for ( const lod of lods ) {
  151. const positions = lod.positions;
  152. const indices = lod.indices;
  153. for ( let c = 0; c < lod.numChunks; c ++ ) {
  154. const startTri = c * 64;
  155. const endTri = Math.min( startTri + 64, lod.numTriangles );
  156. // 1. Calculate Center
  157. let cx = 0, cy = 0, cz = 0;
  158. const vertCount = ( endTri - startTri ) * 3;
  159. for ( let t = startTri; t < endTri; t ++ ) {
  160. for ( let v = 0; v < 3; v ++ ) {
  161. const idx = indices[ t * 3 + v ];
  162. cx += positions.getX( idx );
  163. cy += positions.getY( idx );
  164. cz += positions.getZ( idx );
  165. }
  166. }
  167. cx /= vertCount;
  168. cy /= vertCount;
  169. cz /= vertCount;
  170. // 2. Calculate Radius
  171. let maxDistSq = 0;
  172. for ( let t = startTri; t < endTri; t ++ ) {
  173. for ( let v = 0; v < 3; v ++ ) {
  174. const idx = indices[ t * 3 + v ];
  175. const dx = positions.getX( idx ) - cx;
  176. const dy = positions.getY( idx ) - cy;
  177. const dz = positions.getZ( idx ) - cz;
  178. const distSq = dx * dx + dy * dy + dz * dz;
  179. if ( distSq > maxDistSq ) maxDistSq = distSq;
  180. }
  181. }
  182. const radius = Math.sqrt( maxDistSq );
  183. chunkBoundsData[ currentChunkId * 4 + 0 ] = cx;
  184. chunkBoundsData[ currentChunkId * 4 + 1 ] = cy;
  185. chunkBoundsData[ currentChunkId * 4 + 2 ] = cz;
  186. chunkBoundsData[ currentChunkId * 4 + 3 ] = radius;
  187. currentChunkId ++;
  188. }
  189. }
  190. // Upload LOD offsets to GPU (uvec4: triangleStart, numTriangles, chunkStart, 0)
  191. const lodOffsetsData = new Uint32Array( lods.length * 4 );
  192. for ( let i = 0; i < lods.length; i ++ ) {
  193. lodOffsetsData[ i * 4 + 0 ] = lods[ i ].indexOffset / 3;
  194. lodOffsetsData[ i * 4 + 1 ] = lods[ i ].numTriangles;
  195. lodOffsetsData[ i * 4 + 2 ] = lods[ i ].chunkStart;
  196. }
  197. const lodOffsetsBuffer = storage( new THREE.StorageBufferAttribute( lodOffsetsData, 4 ), 'uvec4', lods.length ).toReadOnly();
  198. const chunkBoundsBuffer = storage( new THREE.StorageBufferAttribute( chunkBoundsData, 4 ), 'vec4', totalChunks ).toReadOnly();
  199. // Storage Buffers
  200. const vertexBuffer = storage( new THREE.StorageBufferAttribute( vertexArray, 4 ), 'vec4', totalVertices ).toReadOnly();
  201. const uvBuffer = storage( new THREE.StorageBufferAttribute( uvArray, 2 ), 'vec2', totalVertices ).toReadOnly();
  202. const indexBuffer = storage( new THREE.StorageBufferAttribute( indexArray, 1 ), 'uint', totalIndices ).toReadOnly();
  203. const meshletIdBuffer = storage( new THREE.StorageBufferAttribute( meshletTriangleArray, 1 ), 'uint', totalIndices / 3 ).toReadOnly();
  204. const materialModeUniform = uniform( 0, 'uint' );
  205. const textureMap = new THREE.TextureLoader().load( 'textures/uv_grid_directx.jpg' );
  206. textureMap.colorSpace = THREE.SRGBColorSpace;
  207. textureMap.wrapS = THREE.RepeatWrapping;
  208. textureMap.wrapT = THREE.RepeatWrapping;
  209. const timeScale = uniform( 1.0 );
  210. const parameterGroup = renderer.inspector.createParameters( 'Parameters' );
  211. parameterGroup.add( options, 'Mode', { 'Meshlet Debug': 'Meshlet Debug', 'Texture': 'Texture' } ).addEventListener( 'change', ( e ) => {
  212. materialModeUniform.value = e.value === 'Texture' ? 1 : 0;
  213. } );
  214. parameterGroup.add( options, 'Rasterizer', { 'SW Only': 'SW Only', 'HW Only': 'HW Only', 'Both': 'Both' } );
  215. parameterGroup.add( timeScale, 'value', 0.0, 1.0 ).name( 'Animation Speed' );
  216. // Packed visibility buffers — depth in the high bits, payload in the low bits,
  217. // so a single atomicMax resolves the depth test and the payload write together
  218. // and the winner is order-independent (no frame-to-frame flicker).
  219. // screenTri: depth(18) | megaTriangleIndex(14)
  220. // screenInst: depth(14) | instId(18)
  221. createScreenBuffers();
  222. const staticInstanceData = new Float32Array( instanceCount * 4 );
  223. let dataIndex = 0;
  224. for ( let i = 0; i < rows; i ++ ) {
  225. for ( let j = 0; j < cols; j ++ ) {
  226. staticInstanceData[ dataIndex ++ ] = ( i - rows / 2 ) * 4.0;
  227. staticInstanceData[ dataIndex ++ ] = - 1;
  228. staticInstanceData[ dataIndex ++ ] = ( j - cols / 2 ) * 4.0;
  229. staticInstanceData[ dataIndex ++ ] = 1.0; // scale
  230. }
  231. }
  232. const instanceDataBuffer = storage( new THREE.StorageBufferAttribute( staticInstanceData, 4 ), 'vec4', instanceCount );
  233. const instanceWorldData = new Float32Array( instanceCount * 16 );
  234. const instanceMvpData = new Float32Array( instanceCount * 16 );
  235. const instanceWorldAttr = new THREE.StorageBufferAttribute( instanceWorldData, 16 );
  236. const instanceMvpAttr = new THREE.StorageBufferAttribute( instanceMvpData, 16 );
  237. const instanceWorldBuffer = storage( instanceWorldAttr, 'mat4', instanceCount );
  238. const instanceMvpBuffer = storage( instanceMvpAttr, 'mat4', instanceCount );
  239. const instanceWorldRead = storage( instanceWorldAttr, 'mat4', instanceCount ).toReadOnly();
  240. const workQueueCountData = new Uint32Array( 1 );
  241. const workQueueCountAttr = new THREE.StorageBufferAttribute( workQueueCountData, 1 );
  242. const workQueueCountAtomic = storage( workQueueCountAttr, 'uint', 1 ).toAtomic();
  243. const workQueueCountRead = storage( workQueueCountAttr, 'uint', 1 ).toReadOnly();
  244. const dispatchData = new Uint32Array( 3 );
  245. const dispatchAttr = new THREE.IndirectStorageBufferAttribute( dispatchData, 3 );
  246. const dispatchBuffer = storage( dispatchAttr, 'uint', 3 );
  247. // Work queue budget — one item is a 64-triangle chunk of one visible instance
  248. const MAX_WORK_ITEMS = 2820000;
  249. const workQueueData = new Uint32Array( MAX_WORK_ITEMS * 4 );
  250. const workQueueBuffer = storage( new THREE.StorageBufferAttribute( workQueueData, 4 ), 'uvec4', MAX_WORK_ITEMS );
  251. // HW Rasterizer Buffers (for large triangles that exceed SW raster budget)
  252. const MAX_HW_TRIANGLES = 100000;
  253. // HW queue: index 0 is atomic counter, indices 1..MAX store payload32
  254. const hwQueueData = new Uint32Array( MAX_HW_TRIANGLES + 1 );
  255. const hwQueueAttr = new THREE.StorageBufferAttribute( hwQueueData, 1 );
  256. const hwQueueAtomic = storage( hwQueueAttr, 'uint', MAX_HW_TRIANGLES + 1 ).toAtomic();
  257. const hwQueueRead = storage( hwQueueAttr, 'uint', MAX_HW_TRIANGLES + 1 ).toReadOnly();
  258. // Draw indirect buffer: vertexCount, instanceCount, firstVertex, firstInstance
  259. const hwDrawData = new Uint32Array( 4 );
  260. const hwDrawAttr = new THREE.IndirectStorageBufferAttribute( hwDrawData, 4 );
  261. const hwDrawBuffer = storage( hwDrawAttr, 'uint', 4 );
  262. projScreenMatrixUniform = uniform( new THREE.Matrix4() );
  263. frustumPlanesUniform = uniformArray( [
  264. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  265. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  266. ], 'vec4' );
  267. cameraPos = uniform( new THREE.Vector3() );
  268. cotHalfFovUniform = uniform( 1.0 );
  269. const pixelErrorThresholdUniform = uniform( 4.0 );
  270. const maxRasterSizeUniform = uniform( MAX_RASTER_SIZE, 'int' ); // Max bounding box size in pixels for SW rasterizer
  271. // Compute Clear
  272. computeClear = Fn( () => {
  273. atomicStore( screenTriAtomic.element( instanceIndex ), uint( 0 ) );
  274. atomicStore( screenInstAtomic.element( instanceIndex ), uint( 0 ) );
  275. If( instanceIndex.equal( 0 ), () => {
  276. atomicStore( workQueueCountAtomic.element( 0 ), uint( 0 ) );
  277. atomicStore( hwQueueAtomic.element( 0 ), uint( 0 ) );
  278. } );
  279. } )().compute( maxPixels, [ 256 ] ).setName( 'Compute Clear' );
  280. // Compute Frustum (GPU Culling, LOD & Work Allocation)
  281. computeFrustum = Fn( () => {
  282. const data = instanceDataBuffer.element( instanceIndex );
  283. const pos = data.xyz;
  284. const scale = data.w;
  285. const i = float( instanceIndex );
  286. // Rotation
  287. const rotY = time.mul( timeScale ).add( i );
  288. const c = cos( rotY );
  289. const s = sin( rotY );
  290. // Compose MatrixWorld
  291. const matrixWorld = mat4(
  292. vec4( c.mul( scale ), 0.0, s.mul( scale ), 0.0 ),
  293. vec4( 0.0, scale, 0.0, 0.0 ),
  294. vec4( s.negate().mul( scale ), 0.0, c.mul( scale ), 0.0 ),
  295. vec4( pos, 1.0 )
  296. );
  297. const visible = bool( true ).toVar();
  298. const radius = scale.mul( 2.0 ); // bounding sphere radius
  299. // Frustum culling using the 6 extracted world-space planes
  300. Loop( { start: 0, end: 6 }, ( { i: planeIndex } ) => {
  301. const plane = frustumPlanesUniform.element( planeIndex );
  302. const dist = dot( plane.xyz, pos ).add( plane.w );
  303. If( dist.lessThan( radius.negate() ), () => {
  304. visible.assign( false );
  305. } );
  306. } );
  307. If( visible, () => {
  308. const distToCamera = distance( cameraPos, pos );
  309. // Precompute projection factor once (Screen-Space Projected Error)
  310. // pixelError = cotHalfFov * errorWorld / dist * screenH / 2
  311. const pixelFactor = cotHalfFovUniform.div( max( 0.01, distToCamera ) ).mul( float( screenSize.y ) ).div( 2.0 );
  312. const lodLevel = uint( 0 ).toVar();
  313. let lodSelection = null;
  314. for ( let i = lods.length - 1; i > 0; i -- ) {
  315. const checkLod = float( lods[ i ].error ).mul( scale ).mul( pixelFactor ).lessThanEqual( pixelErrorThresholdUniform );
  316. if ( lodSelection === null ) {
  317. lodSelection = If( checkLod, () => {
  318. lodLevel.assign( i );
  319. } );
  320. } else {
  321. lodSelection = lodSelection.ElseIf( checkLod, () => {
  322. lodLevel.assign( i );
  323. } );
  324. }
  325. }
  326. const lodData = lodOffsetsBuffer.element( lodLevel );
  327. const lodTriStart = lodData.x;
  328. const lodNumTriangles = lodData.y;
  329. const lodChunkStart = lodData.z;
  330. // Calculate Work Items (64 triangles per item)
  331. const workItems = lodNumTriangles.add( 63 ).div( 64 );
  332. // Evaluate each Chunk (Cluster)
  333. Loop( { name: 'cIdx', type: 'uint', start: uint( 0 ), end: workItems, condition: '<' }, ( { cIdx: chunkIndex } ) => {
  334. const globalChunkId = lodChunkStart.add( uint( chunkIndex ) );
  335. const chunkBounds = chunkBoundsBuffer.element( globalChunkId );
  336. const chunkCenterLocal = chunkBounds.xyz;
  337. const chunkRadiusLocal = chunkBounds.w;
  338. // Transform chunk bounding sphere to world space and store as var to prevent inlining
  339. const chunkCenterWorld = matrixWorld.mul( vec4( chunkCenterLocal, 1.0 ) ).xyz.toVar();
  340. const chunkRadiusWorld = chunkRadiusLocal.mul( scale ).toVar();
  341. const chunkVisible = bool( true ).toVar();
  342. // Frustum cull the chunk
  343. Loop( { name: 'pIdx', start: 0, end: 6 }, ( { pIdx: planeIndex } ) => {
  344. const plane = frustumPlanesUniform.element( planeIndex );
  345. const chunkDist = dot( plane.xyz, chunkCenterWorld ).add( plane.w );
  346. If( chunkDist.lessThan( chunkRadiusWorld.negate() ), () => {
  347. chunkVisible.assign( false );
  348. } );
  349. } );
  350. If( chunkVisible, () => {
  351. const itemIndex = atomicAdd( workQueueCountAtomic.element( 0 ), 1 );
  352. // uvec4( instanceIndex, triangleStart, lodNumTriangles, chunkIndex )
  353. workQueueBuffer.element( itemIndex ).assign(
  354. uvec4( instanceIndex, lodTriStart, lodNumTriangles, uint( chunkIndex ) )
  355. );
  356. } );
  357. } );
  358. // Store transform for this instance
  359. instanceWorldBuffer.element( instanceIndex ).assign( matrixWorld );
  360. instanceMvpBuffer.element( instanceIndex ).assign( projScreenMatrixUniform.mul( matrixWorld ) );
  361. } );
  362. } )().compute( instanceCount ).setName( 'Compute Frustum' );
  363. // Compute Dispatch (Indirect arguments)
  364. computeDispatch = Fn( () => {
  365. const totalWorkgroups = workQueueCountRead.element( 0 );
  366. const maxDim = uint( 65535 );
  367. // Split totalWorkgroups into 2D dispatch if it exceeds 65535
  368. const dispatchX = min( totalWorkgroups, maxDim );
  369. const dispatchY = totalWorkgroups.add( maxDim ).sub( 1 ).div( maxDim );
  370. dispatchBuffer.element( 0 ).assign( dispatchX );
  371. dispatchBuffer.element( 1 ).assign( dispatchY );
  372. dispatchBuffer.element( 2 ).assign( 1 );
  373. } )().compute( 1 ).setName( 'Compute Dispatch' );
  374. // Edge function for barycentric coordinates
  375. const edgeFunction = Fn( ( [ a, b, c ] ) => {
  376. // (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)
  377. return c.y.sub( a.y ).mul( b.x.sub( a.x ) ).sub( c.x.sub( a.x ).mul( b.y.sub( a.y ) ) );
  378. } );
  379. // Compute Rasterizer
  380. computeRasterize = Fn( () => {
  381. const totalWorkgroups = workQueueCountRead.element( 0 );
  382. const totalThreads = totalWorkgroups.mul( 64 );
  383. If( instanceIndex.lessThan( totalThreads ), () => {
  384. const workItemId = instanceIndex.div( 64 );
  385. const localTriangleIndex = instanceIndex.mod( 64 );
  386. const workItem = workQueueBuffer.element( workItemId );
  387. const instId = workItem.x;
  388. const lodTriStart = workItem.y;
  389. const lodNumTriangles = workItem.z;
  390. const chunkIndex = workItem.w;
  391. const globalTriangleIndex = chunkIndex.mul( 64 ).add( localTriangleIndex );
  392. If( globalTriangleIndex.lessThan( lodNumTriangles ), () => {
  393. const megaTriangleIndex = lodTriStart.add( globalTriangleIndex );
  394. const indexOffset = megaTriangleIndex.mul( 3 );
  395. const i0 = indexBuffer.element( indexOffset );
  396. const i1 = indexBuffer.element( indexOffset.add( 1 ) );
  397. const i2 = indexBuffer.element( indexOffset.add( 2 ) );
  398. const v0 = vertexBuffer.element( i0 );
  399. const v1 = vertexBuffer.element( i1 );
  400. const v2 = vertexBuffer.element( i2 );
  401. const instMvpMatrix = instanceMvpBuffer.element( instId );
  402. // MVP
  403. const p0 = instMvpMatrix.mul( v0 );
  404. const p1 = instMvpMatrix.mul( v1 );
  405. const p2 = instMvpMatrix.mul( v2 );
  406. // Near plane clipping
  407. If( p0.w.greaterThan( 0.0 ).and( p1.w.greaterThan( 0.0 ) ).and( p2.w.greaterThan( 0.0 ) ), () => {
  408. const ndc0 = p0.xyz.div( p0.w );
  409. const ndc1 = p1.xyz.div( p1.w );
  410. const ndc2 = p2.xyz.div( p2.w );
  411. // Early Backface Culling in NDC
  412. const areaNdc = edgeFunction( ndc0, ndc1, ndc2 );
  413. If( areaNdc.greaterThan( 0.0 ), () => {
  414. // NDC guard: skip triangles entirely outside clip volume
  415. const ndcMinX = min( ndc0.x, min( ndc1.x, ndc2.x ) );
  416. const ndcMaxX = max( ndc0.x, max( ndc1.x, ndc2.x ) );
  417. const ndcMinY = min( ndc0.y, min( ndc1.y, ndc2.y ) );
  418. const ndcMaxY = max( ndc0.y, max( ndc1.y, ndc2.y ) );
  419. If( ndcMaxX.greaterThan( - 1.0 ).and( ndcMinX.lessThan( 1.0 ) ).and( ndcMaxY.greaterThan( - 1.0 ) ).and( ndcMinY.lessThan( 1.0 ) ), () => {
  420. // Map to screen coordinates
  421. const w = screenSize.x;
  422. const h = screenSize.y;
  423. const s0 = ndc0.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  424. const s1 = ndc1.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  425. const s2 = ndc2.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  426. // Bounding Box
  427. const minX = max( 0.0, min( s0.x, min( s1.x, s2.x ) ) );
  428. const maxX = min( w.sub( 1.0 ), max( s0.x, max( s1.x, s2.x ) ) );
  429. const minY = max( 0.0, min( s0.y, min( s1.y, s2.y ) ) );
  430. const maxY = min( h.sub( 1.0 ), max( s0.y, max( s1.y, s2.y ) ) );
  431. const startX = int( floor( minX ) );
  432. const endX = int( floor( maxX ) );
  433. const startY = int( floor( minY ) );
  434. const endY = int( floor( maxY ) );
  435. // Big triangle guard: skip triangles larger than maxRasterSize
  436. // This is the key performance safeguard — software rasterizers
  437. // should only handle small triangles. Large triangles cause O(n²)
  438. // pixel iteration per thread, which kills performance when close.
  439. const bbWidth = endX.sub( startX );
  440. const bbHeight = endY.sub( startY );
  441. // Compute payload32 for HW path (full precision)
  442. // payload32: instId (18 bits) | megaTriangleIndex (14 bits)
  443. const payload32 = instId.shiftLeft( TRIANGLE_INDEX_BITS ).bitOr( megaTriangleIndex.bitAnd( TRIANGLE_INDEX_MASK ) );
  444. // Sub-pixel / Valid bounds rejection + big triangle guard
  445. If( startX.lessThanEqual( endX ).and( startY.lessThanEqual( endY ) ).and( bbWidth.lessThanEqual( maxRasterSizeUniform ) ).and( bbHeight.lessThanEqual( maxRasterSizeUniform ) ), () => {
  446. const area = edgeFunction( s0, s1, s2 );
  447. const stepX_w0 = s1.y.sub( s2.y );
  448. const stepY_w0 = s2.x.sub( s1.x );
  449. const stepX_w1 = s2.y.sub( s0.y );
  450. const stepY_w1 = s0.x.sub( s2.x );
  451. const stepX_w2 = s0.y.sub( s1.y );
  452. const stepY_w2 = s1.x.sub( s0.x );
  453. // Top-Left rule check for each edge to guarantee watertightness
  454. const isTopLeft0 = stepX_w0.lessThan( 0.0 ).or( stepX_w0.equal( 0.0 ).and( stepY_w0.greaterThan( 0.0 ) ) );
  455. const isTopLeft1 = stepX_w1.lessThan( 0.0 ).or( stepX_w1.equal( 0.0 ).and( stepY_w1.greaterThan( 0.0 ) ) );
  456. const isTopLeft2 = stepX_w2.lessThan( 0.0 ).or( stepX_w2.equal( 0.0 ).and( stepY_w2.greaterThan( 0.0 ) ) );
  457. const bias0 = isTopLeft0.select( 0.0, - 1e-5 );
  458. const bias1 = isTopLeft1.select( 0.0, - 1e-5 );
  459. const bias2 = isTopLeft2.select( 0.0, - 1e-5 );
  460. const pStart = vec2( float( startX ).add( 0.5 ), float( startY ).add( 0.5 ) );
  461. const row_w0 = edgeFunction( s1, s2, pStart ).toVar();
  462. const row_w1 = edgeFunction( s2, s0, pStart ).toVar();
  463. const row_w2 = edgeFunction( s0, s1, pStart ).toVar();
  464. row_w0.addAssign( bias0 );
  465. row_w1.addAssign( bias1 );
  466. row_w2.addAssign( bias2 );
  467. // Incremental Z Math (ALU Optimization)
  468. const b0_start = row_w0.div( area );
  469. const b1_start = row_w1.div( area );
  470. const b2_start = row_w2.div( area );
  471. const row_z = b0_start.mul( ndc0.z ).add( b1_start.mul( ndc1.z ) ).add( b2_start.mul( ndc2.z ) ).toVar();
  472. const stepX_z = stepX_w0.div( area ).mul( ndc0.z ).add( stepX_w1.div( area ).mul( ndc1.z ) ).add( stepX_w2.div( area ).mul( ndc2.z ) );
  473. const stepY_z = stepY_w0.div( area ).mul( ndc0.z ).add( stepY_w1.div( area ).mul( ndc1.z ) ).add( stepY_w2.div( area ).mul( ndc2.z ) );
  474. Loop( { name: 'y', type: 'int', start: startY, end: endY, condition: '<=' }, ( { y } ) => {
  475. const w0 = row_w0.toVar();
  476. const w1 = row_w1.toVar();
  477. const w2 = row_w2.toVar();
  478. const z = row_z.toVar();
  479. Loop( { name: 'x', type: 'int', start: startX, end: endX, condition: '<=' }, ( { x } ) => {
  480. If( w0.greaterThanEqual( 0.0 ).and( w1.greaterThanEqual( 0.0 ) ).and( w2.greaterThanEqual( 0.0 ) ), () => {
  481. If( z.greaterThanEqual( 0.0 ).and( z.lessThanEqual( 1.0 ) ), () => {
  482. // Depth (fourth-root distribution) packed above each payload's bits
  483. const zEncoded = sqrt( sqrt( float( 1.0 ).sub( z ) ) );
  484. const depthTri = uint( zEncoded.mul( DEPTH_TRI_MAX ) );
  485. const depthInst = uint( zEncoded.mul( DEPTH_INST_MAX ) );
  486. const packedTri = depthTri.shiftLeft( TRIANGLE_INDEX_BITS ).bitOr( megaTriangleIndex.bitAnd( TRIANGLE_INDEX_MASK ) );
  487. const packedInst = depthInst.shiftLeft( INSTANCE_INDEX_BITS ).bitOr( instId );
  488. const pixelIndex = uint( y ).mul( uint( screenSize.x ) ).add( uint( x ) );
  489. // Early depth pre-check: skip the atomics if the pixel already has a closer fragment
  490. const currentDepth = atomicLoad( screenTriAtomic.element( pixelIndex ) ).shiftRight( TRIANGLE_INDEX_BITS );
  491. If( depthTri.greaterThanEqual( currentDepth ), () => {
  492. // Depth occupies the high bits, so atomicMax resolves the depth
  493. // test and the payload write in one order-independent step
  494. atomicMax( screenTriAtomic.element( pixelIndex ), packedTri );
  495. atomicMax( screenInstAtomic.element( pixelIndex ), packedInst );
  496. } );
  497. } );
  498. } );
  499. w0.addAssign( stepX_w0 );
  500. w1.addAssign( stepX_w1 );
  501. w2.addAssign( stepX_w2 );
  502. z.addAssign( stepX_z );
  503. } );
  504. row_w0.addAssign( stepY_w0 );
  505. row_w1.addAssign( stepY_w1 );
  506. row_w2.addAssign( stepY_w2 );
  507. row_z.addAssign( stepY_z );
  508. } );
  509. } ).Else( () => {
  510. // Big triangle → enqueue for HW rasterization
  511. If( startX.lessThanEqual( endX ).and( startY.lessThanEqual( endY ) ), () => {
  512. const hwCount = atomicAdd( hwQueueAtomic.element( 0 ), 1 );
  513. const hwSlot = hwCount.add( 1 );
  514. atomicStore( hwQueueAtomic.element( hwSlot ), payload32 );
  515. } );
  516. } );
  517. } );
  518. } ); // End Early Backface Culling
  519. } ); // End Near Plane Clipping
  520. } ); // End globalTriangleIndex bounds check
  521. } ); // End instanceIndex bounds check
  522. } )().compute( dispatchAttr ).setName( 'Compute Rasterize' );
  523. // Compute HW Draw Indirect Args
  524. computeHWArgs = Fn( () => {
  525. const hwCount = atomicLoad( hwQueueAtomic.element( 0 ) );
  526. // Non-indexed draw: vertexCount = hwCount * 3 (3 verts per triangle)
  527. hwDrawBuffer.element( 0 ).assign( hwCount.mul( 3 ) ); // vertexCount
  528. hwDrawBuffer.element( 1 ).assign( uint( 1 ) ); // instanceCount
  529. hwDrawBuffer.element( 2 ).assign( uint( 0 ) ); // firstVertex
  530. hwDrawBuffer.element( 3 ).assign( uint( 0 ) ); // firstInstance
  531. } )().compute( 1 ).setName( 'Compute HW Args' );
  532. // Hash function for meshlet colors (shared between HW mesh and fullscreen quad)
  533. const hashColor = Fn( ( [ id_in ] ) => {
  534. let id = uint( id_in ).toVar();
  535. id = id.mul( uint( 747796405 ) ).add( uint( 289559509 ) );
  536. id = id.shiftRight( 16 ).bitXor( id ).mul( uint( 277803737 ) );
  537. id = id.shiftRight( 16 ).bitXor( id );
  538. const r = float( id.bitAnd( uint( 255 ) ) ).div( 255.0 );
  539. const g = float( id.shiftRight( 8 ).bitAnd( uint( 255 ) ) ).div( 255.0 );
  540. const b = float( id.shiftRight( 16 ).bitAnd( uint( 255 ) ) ).div( 255.0 );
  541. return vec4( r.mul( 0.8 ).add( 0.2 ), g.mul( 0.8 ).add( 0.2 ), b.mul( 0.8 ).add( 0.2 ), 1.0 );
  542. } );
  543. // HW Rasterizer Mesh (renders big triangles via GPU hardware pipeline)
  544. // Unlike the SW rasterizer which writes to an atomic screen buffer,
  545. // the HW mesh renders directly with real colors and hardware depth testing.
  546. // It renders AFTER the fullscreen quad, overlaying HW-rasterized triangles.
  547. {
  548. // Geometry: dummy positions, vertex count driven by indirect draw
  549. const hwGeometry = new THREE.BufferGeometry();
  550. hwGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( new Float32Array( MAX_HW_TRIANGLES * 3 * 3 ), 3 ) );
  551. hwGeometry.setIndirect( hwDrawAttr );
  552. hwGeometry.boundingSphere = new THREE.Sphere().set( new THREE.Vector3(), Infinity );
  553. // Varying to pass payload and UVs from vertex to fragment
  554. const vPayload = varyingProperty( 'uint', 'vPayload' );
  555. const vUv = varyingProperty( 'vec2', 'vUv' );
  556. const hwMaterial = new THREE.NodeMaterial();
  557. hwMaterial.depthWrite = true;
  558. hwMaterial.depthTest = true;
  559. // Vertex shader: vertex pulling from HW queue
  560. hwMaterial.positionNode = Fn( () => {
  561. // vertexIndex: 0,1,2, 3,4,5, 6,7,8, ...
  562. const triIndex = vertexIndex.div( 3 ); // which triangle in HW queue
  563. const localVert = vertexIndex.mod( 3 ); // which vertex (0, 1, 2)
  564. const payload32 = hwQueueRead.element( triIndex.add( 1 ) );
  565. const instId = payload32.shiftRight( TRIANGLE_INDEX_BITS );
  566. const megaTriIdx = payload32.bitAnd( TRIANGLE_INDEX_MASK );
  567. // Fetch actual vertex index from the mega index buffer
  568. const vertGlobalIdx = indexBuffer.element( megaTriIdx.mul( 3 ).add( localVert ) );
  569. const v = vertexBuffer.element( vertGlobalIdx );
  570. // Transform to world space
  571. const worldPos = instanceWorldRead.element( instId ).mul( v );
  572. const uvVal = uvBuffer.element( vertGlobalIdx );
  573. vUv.assign( uvVal );
  574. vPayload.assign( payload32 );
  575. return worldPos.xyz;
  576. } )();
  577. // Fragment shader: directly output final color (no storage buffer writes)
  578. hwMaterial.fragmentNode = Fn( () => {
  579. const payload32 = vPayload;
  580. const instId = payload32.shiftRight( TRIANGLE_INDEX_BITS );
  581. const megaTriangleIndex = payload32.bitAnd( TRIANGLE_INDEX_MASK );
  582. const outColor = vec4( 0.0 ).toVar();
  583. If( materialModeUniform.equal( 0 ), () => {
  584. const meshletId = meshletIdBuffer.element( megaTriangleIndex ).add( instId.mul( 1000 ) );
  585. outColor.assign( hashColor( meshletId ) );
  586. } ).Else( () => {
  587. // Hardware interpolated UV!
  588. outColor.assign( texture( textureMap, vUv ) );
  589. } );
  590. return outColor;
  591. } )();
  592. hwMesh = new THREE.Mesh( hwGeometry, hwMaterial );
  593. hwMesh.frustumCulled = false;
  594. hwScene = new THREE.Scene();
  595. hwScene.add( hwMesh );
  596. }
  597. // Fullscreen Presentation Pass
  598. const material = new THREE.NodeMaterial();
  599. material.depthWrite = true;
  600. // Shared screen-coordinate helper
  601. const getPixelIndex = () => {
  602. const screenX = uint( floor( uv().x.mul( screenSize.x ) ) );
  603. const screenY = uint( floor( uv().y.oneMinus().mul( screenSize.y ) ) );
  604. return screenY.mul( uint( screenSize.x ) ).add( screenX );
  605. };
  606. // Output depth from the SW rasterizer so HW mesh can depth test against it
  607. material.depthNode = Fn( () => {
  608. const pixelIndex = getPixelIndex();
  609. // Depth lives in the high 18 bits of the packed value
  610. const depthTri = screenTriRead.element( pixelIndex ).shiftRight( TRIANGLE_INDEX_BITS );
  611. // Reconstruct NDC Z from non-linear depth (fourth-root distribution)
  612. const y = float( depthTri ).div( DEPTH_TRI_MAX );
  613. const y2 = y.mul( y );
  614. const v = y2.mul( y2 ); // raise to the fourth power (y^4) to get original v
  615. return float( 1.0 ).sub( v );
  616. } )();
  617. material.colorNode = Fn( () => {
  618. const pixelIndex = getPixelIndex();
  619. // Check for background immediately (depth in the high bits)
  620. const packedTri = screenTriRead.element( pixelIndex );
  621. // Background color for pixels with no geometry
  622. const outColor = vec4( background, 1.0 ).toVar();
  623. If( packedTri.shiftRight( TRIANGLE_INDEX_BITS ).greaterThan( 0 ), () => {
  624. // Unpack the two payloads from their depth-packed buffers
  625. const megaTriangleIndex = packedTri.bitAnd( TRIANGLE_INDEX_MASK );
  626. const instId = screenInstRead.element( pixelIndex ).bitAnd( INSTANCE_INDEX_MASK );
  627. // Visibility Buffer: Fetch exact vertices and UVs
  628. const i0 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 0 ) );
  629. const i1 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 1 ) );
  630. const i2 = indexBuffer.element( megaTriangleIndex.mul( 3 ).add( 2 ) );
  631. const v0 = vertexBuffer.element( i0 );
  632. const v1 = vertexBuffer.element( i1 );
  633. const v2 = vertexBuffer.element( i2 );
  634. const t_uv0 = uvBuffer.element( i0 );
  635. const t_uv1 = uvBuffer.element( i1 );
  636. const t_uv2 = uvBuffer.element( i2 );
  637. // Project Vertices to Screen Space
  638. const mvpMatrix = instanceMvpBuffer.element( instId );
  639. const p0 = mvpMatrix.mul( v0 );
  640. const p1 = mvpMatrix.mul( v1 );
  641. const p2 = mvpMatrix.mul( v2 );
  642. const ndc0 = p0.xyz.div( p0.w );
  643. const ndc1 = p1.xyz.div( p1.w );
  644. const ndc2 = p2.xyz.div( p2.w );
  645. const w = screenSize.x;
  646. const h = screenSize.y;
  647. const s0 = ndc0.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  648. const s1 = ndc1.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  649. const s2 = ndc2.xy.add( 1.0 ).mul( 0.5 ).mul( vec2( w, h ) );
  650. const p = vec2( uv().x.mul( screenSize.x ), uv().y.oneMinus().mul( screenSize.y ) );
  651. // Compute Barycentrics
  652. const area = edgeFunction( s0, s1, s2 );
  653. const w0 = edgeFunction( s1, s2, p );
  654. const w1 = edgeFunction( s2, s0, p );
  655. const w2 = edgeFunction( s0, s1, p );
  656. // Guard against division by zero for safe execution
  657. const safeArea = area.equal( 0.0 ).select( 1.0, area );
  658. const b0 = w0.div( safeArea );
  659. const b1 = w1.div( safeArea );
  660. const b2 = w2.div( safeArea );
  661. // Perspective correct UV interpolation (32-bit floats!)
  662. const z_inv = b0.div( p0.w ).add( b1.div( p1.w ) ).add( b2.div( p2.w ) );
  663. const safeZInv = z_inv.equal( 0.0 ).select( 1.0, z_inv );
  664. const b0_p = b0.div( p0.w ).div( safeZInv );
  665. const b1_p = b1.div( p1.w ).div( safeZInv );
  666. const b2_p = b2.div( p2.w ).div( safeZInv );
  667. const uv_interp = t_uv0.mul( b0_p ).add( t_uv1.mul( b1_p ) ).add( t_uv2.mul( b2_p ) );
  668. // Compute screen-space derivatives analytically (extremely clean, no helper fragment issues)
  669. const dw0_dx = s2.y.sub( s1.y );
  670. const dw1_dx = s0.y.sub( s2.y );
  671. const dw2_dx = s1.y.sub( s0.y );
  672. const dw0_dy = s1.x.sub( s2.x );
  673. const dw1_dy = s2.x.sub( s0.x );
  674. const dw2_dy = s0.x.sub( s1.x );
  675. const q0 = float( 1.0 ).div( p0.w );
  676. const q1 = float( 1.0 ).div( p1.w );
  677. const q2 = float( 1.0 ).div( p2.w );
  678. const sum_w_q = w0.mul( q0 ).add( w1.mul( q1 ) ).add( w2.mul( q2 ) );
  679. const safe_sum_w_q = sum_w_q.equal( 0.0 ).select( 1.0, sum_w_q );
  680. const dUvDx = (
  681. dw0_dx.mul( q0 ).mul( t_uv0.sub( uv_interp ) )
  682. .add( dw1_dx.mul( q1 ).mul( t_uv1.sub( uv_interp ) ) )
  683. .add( dw2_dx.mul( q2 ).mul( t_uv2.sub( uv_interp ) ) )
  684. ).div( safe_sum_w_q );
  685. const dUvDy = (
  686. dw0_dy.mul( q0 ).mul( t_uv0.sub( uv_interp ) )
  687. .add( dw1_dy.mul( q1 ).mul( t_uv1.sub( uv_interp ) ) )
  688. .add( dw2_dy.mul( q2 ).mul( t_uv2.sub( uv_interp ) ) )
  689. ).div( safe_sum_w_q );
  690. If( materialModeUniform.equal( 0 ), () => {
  691. const meshletId = meshletIdBuffer.element( megaTriangleIndex ).add( instId.mul( 1000 ) );
  692. outColor.assign( hashColor( meshletId ) );
  693. } ).Else( () => {
  694. outColor.assign( texture( textureMap, uv_interp ).grad( dUvDx, dUvDy ) );
  695. } );
  696. } );
  697. return outColor;
  698. } )();
  699. quadMesh = new THREE.QuadMesh( material );
  700. window.addEventListener( 'resize', onWindowResize );
  701. }
  702. function createScreenBuffers() {
  703. const size = new THREE.Vector2();
  704. renderer.getDrawingBufferSize( size );
  705. const newMaxPixels = size.x * size.y;
  706. if ( newMaxPixels === maxPixels ) return;
  707. maxPixels = newMaxPixels;
  708. if ( screenTriAttr ) screenTriAttr.dispose();
  709. if ( screenInstAttr ) screenInstAttr.dispose();
  710. const screenTriData = new Uint32Array( maxPixels );
  711. screenTriAttr = new THREE.StorageBufferAttribute( screenTriData, 1 );
  712. const screenInstData = new Uint32Array( maxPixels );
  713. screenInstAttr = new THREE.StorageBufferAttribute( screenInstData, 1 );
  714. if ( screenTriAtomic === undefined ) {
  715. screenTriAtomic = storage( screenTriAttr, 'uint', maxPixels ).toAtomic();
  716. screenTriRead = storage( screenTriAttr, 'uint', maxPixels ).toReadOnly();
  717. screenInstAtomic = storage( screenInstAttr, 'uint', maxPixels ).toAtomic();
  718. screenInstRead = storage( screenInstAttr, 'uint', maxPixels ).toReadOnly();
  719. } else {
  720. screenTriAtomic.value = screenTriAttr;
  721. screenTriAtomic.bufferCount = maxPixels;
  722. screenTriRead.value = screenTriAttr;
  723. screenTriRead.bufferCount = maxPixels;
  724. screenInstAtomic.value = screenInstAttr;
  725. screenInstAtomic.bufferCount = maxPixels;
  726. screenInstRead.value = screenInstAttr;
  727. screenInstRead.bufferCount = maxPixels;
  728. computeClear.count = maxPixels;
  729. computeClear.dispose();
  730. computeRasterize.dispose();
  731. computeFrustum.dispose();
  732. computeDispatch.dispose();
  733. computeHWArgs.dispose();
  734. quadMesh.material.dispose();
  735. hwMesh.material.dispose();
  736. }
  737. }
  738. function onWindowResize() {
  739. camera.aspect = window.innerWidth / window.innerHeight;
  740. camera.updateProjectionMatrix();
  741. renderer.setSize( window.innerWidth, window.innerHeight );
  742. createScreenBuffers();
  743. }
  744. const frustum = new THREE.Frustum();
  745. const projScreenMatrix = new THREE.Matrix4();
  746. const cameraInverse = new THREE.Matrix4();
  747. function animate() {
  748. controls.update();
  749. camera.updateMatrixWorld();
  750. cameraInverse.copy( camera.matrixWorld ).invert();
  751. projScreenMatrix.multiplyMatrices( camera.projectionMatrix, cameraInverse );
  752. frustum.setFromProjectionMatrix( projScreenMatrix );
  753. // Update GPU uniforms
  754. projScreenMatrixUniform.value.copy( projScreenMatrix );
  755. cameraPos.value.copy( camera.position );
  756. cotHalfFovUniform.value = camera.projectionMatrix.elements[ 5 ];
  757. // Pack frustum planes into the uniform array
  758. const planes = frustum.planes;
  759. const planesArray = frustumPlanesUniform.array;
  760. for ( let i = 0; i < 6; i ++ ) {
  761. const p = planes[ i ];
  762. planesArray[ i ].set( p.normal.x, p.normal.y, p.normal.z, p.constant );
  763. }
  764. // Compute & Render
  765. renderer.compute( computeClear );
  766. renderer.compute( computeFrustum );
  767. renderer.compute( computeDispatch );
  768. renderer.compute( computeRasterize );
  769. renderer.compute( computeHWArgs );
  770. const rasterMode = options.Rasterizer;
  771. // SW presentation (fullscreen quad reads atomic buffer)
  772. if ( rasterMode === 'SW Only' || rasterMode === 'Both' ) {
  773. quadMesh.render( renderer );
  774. }
  775. // HW mesh renders with real depth testing + colors
  776. if ( rasterMode === 'HW Only' || rasterMode === 'Both' ) {
  777. hwScene.background = ( rasterMode === 'HW Only' ) ? background : null;
  778. renderer.autoClear = ( rasterMode === 'HW Only' );
  779. renderer.render( hwScene, camera );
  780. renderer.autoClear = true;
  781. }
  782. }
  783. </script>
  784. </body>
  785. </html>
粤ICP备19079148号