webgpu_compute_sort_bitonic.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. <html lang="en">
  2. <head>
  3. <title>three.js webgpu - storage pbo external element</title>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
  6. <link type="text/css" rel="stylesheet" href="main.css">
  7. </head>
  8. <body>
  9. <div id="info">
  10. <a href="https://threejs.org" target="_blank" rel="noopener">three.js</a>
  11. <br /> This example demonstrates a bitonic sort running step by step in a compute shader.
  12. <br /> The left canvas swaps values within workgroup local arrays. The right swaps values within storage buffers.
  13. <br /> Reference implementation by <a href="https://poniesandlight.co.uk/reflect/bitonic_merge_sort/">Tim Gfrerer</a>
  14. <br />
  15. <div id="local_swap" style="
  16. position: absolute;
  17. top: 150px;
  18. left: 0;
  19. padding: 10px;
  20. background: rgba( 0, 0, 0, 0.5 );
  21. color: #fff;
  22. font-family: monospace;
  23. font-size: 12px;
  24. line-height: 1.5;
  25. pointer-events: none;
  26. text-align: left;
  27. "></div>
  28. <div id="global_swap" style="
  29. position: absolute;
  30. top: 150px;
  31. right: 0;
  32. padding: 10px;
  33. background: rgba( 0, 0, 0, 0.5 );
  34. color: #fff;
  35. font-family: monospace;
  36. font-size: 12px;
  37. line-height: 1.5;
  38. pointer-events: none;
  39. text-align: left;
  40. "></div>
  41. </div>
  42. <script type="importmap">
  43. {
  44. "imports": {
  45. "three": "../build/three.webgpu.js",
  46. "three/tsl": "../build/three.webgpu.js",
  47. "three/addons/": "./jsm/"
  48. }
  49. }
  50. </script>
  51. <script type="module">
  52. import * as THREE from 'three';
  53. import { storageObject, If, vec3, not, uniform, uv, uint, float, Fn, vec2, abs, int, invocationLocalIndex, workgroupArray, uvec2, floor, instanceIndex, workgroupBarrier } from 'three/tsl';
  54. import { GUI } from 'three/addons/libs/lil-gui.module.min.js';
  55. const StepType = {
  56. NONE: 0,
  57. // Swap values within workgroup local buffer.
  58. FLIP_LOCAL: 1,
  59. DISPERSE_LOCAL: 2,
  60. // Swap values within global data buffer.
  61. FLIP_GLOBAL: 3,
  62. DISPERSE_GLOBAL: 4,
  63. };
  64. const timestamps = {
  65. local_swap: document.getElementById( 'local_swap' ),
  66. global_swap: document.getElementById( 'global_swap' )
  67. };
  68. const localColors = [ 'rgb(203, 64, 203)', 'rgb(0, 215, 215)' ];
  69. const globalColors = [ 'rgb(1, 150, 1)', 'red' ];
  70. // Total number of elements and the dimensions of the display grid.
  71. const size = 16384;
  72. const gridDim = Math.sqrt( size );
  73. const getNumSteps = () => {
  74. const n = Math.log2( size );
  75. return ( n * ( n + 1 ) ) / 2;
  76. };
  77. // Total number of steps in a bitonic sort with 'size' elements.
  78. const MAX_STEPS = getNumSteps();
  79. const WORKGROUP_SIZE = [ 64 ];
  80. const effectController = {
  81. // Sqr root of 16834
  82. gridWidth: uniform( gridDim ),
  83. gridHeight: uniform( gridDim ),
  84. highlight: uniform( 1 ),
  85. 'Display Mode': 'Swap Zone Highlight'
  86. };
  87. const gui = new GUI();
  88. gui.add( effectController, 'Display Mode', [ 'Elements', 'Swap Zone Highlight' ] ).onChange( () => {
  89. if ( effectController[ 'Display Mode' ] === 'Elements' ) {
  90. effectController.highlight.value = 0;
  91. } else {
  92. effectController.highlight.value = 1;
  93. }
  94. } );
  95. // Allow Workgroup Array Swaps
  96. init();
  97. // Global Swaps Only
  98. init( true );
  99. // When forceGlobalSwap is true, force all valid local swaps to be global swaps.
  100. async function init( forceGlobalSwap = false ) {
  101. let currentStep = 0;
  102. let nextStepGlobal = false;
  103. const aspect = ( window.innerWidth / 2 ) / window.innerHeight;
  104. const camera = new THREE.OrthographicCamera( - aspect, aspect, 1, - 1, 0, 2 );
  105. camera.position.z = 1;
  106. const scene = new THREE.Scene();
  107. const nextAlgoBuffer = new THREE.StorageInstancedBufferAttribute( new Uint32Array( 1 ).fill( forceGlobalSwap ? StepType.FLIP_GLOBAL : StepType.FLIP_LOCAL ), 1 );
  108. const nextAlgoStorage = storageObject( nextAlgoBuffer, 'uint', nextAlgoBuffer.count ).label( 'NextAlgo' );
  109. const nextBlockHeightBuffer = new THREE.StorageInstancedBufferAttribute( new Uint32Array( 1 ).fill( 2 ), 1 );
  110. const nextBlockHeightStorage = storageObject( nextBlockHeightBuffer, 'uint', nextBlockHeightBuffer.count ).label( 'NextBlockHeight' );
  111. const nextBlockHeightRead = storageObject( nextBlockHeightBuffer, 'uint', nextBlockHeightBuffer.count ).label( 'NextBlockHeight' ).toReadOnly();
  112. const highestBlockHeightBuffer = new THREE.StorageInstancedBufferAttribute( new Uint32Array( 1 ).fill( 2 ), 1 );
  113. const highestBlockHeightStorage = storageObject( highestBlockHeightBuffer, 'uint', highestBlockHeightBuffer.count ).label( 'HighestBlockHeight' );
  114. const array = new Uint32Array( Array.from( { length: size }, ( _, i ) => {
  115. return i;
  116. } ) );
  117. const randomizeDataArray = () => {
  118. let currentIndex = array.length;
  119. while ( currentIndex !== 0 ) {
  120. const randomIndex = Math.floor( Math.random() * currentIndex );
  121. currentIndex -= 1;
  122. [ array[ currentIndex ], array[ randomIndex ] ] = [
  123. array[ randomIndex ],
  124. array[ currentIndex ],
  125. ];
  126. }
  127. };
  128. randomizeDataArray();
  129. const currentElementsBuffer = new THREE.StorageInstancedBufferAttribute( array, 1 );
  130. const currentElementsStorage = storageObject( currentElementsBuffer, 'uint', size ).label( 'Elements' );
  131. const tempBuffer = new THREE.StorageInstancedBufferAttribute( array, 1 );
  132. const tempStorage = storageObject( tempBuffer, 'uint', size ).label( 'Temp' );
  133. const randomizedElementsBuffer = new THREE.StorageInstancedBufferAttribute( size, 1 );
  134. const randomizedElementsStorage = storageObject( randomizedElementsBuffer, 'uint', size ).label( 'RandomizedElements' );
  135. const getFlipIndices = ( index, blockHeight ) => {
  136. const blockOffset = ( index.mul( 2 ).div( blockHeight ) ).mul( blockHeight );
  137. const halfHeight = blockHeight.div( 2 );
  138. const idx = uvec2(
  139. index.modInt( halfHeight ),
  140. blockHeight.sub( index.modInt( halfHeight ) ).sub( 1 )
  141. );
  142. idx.x.addAssign( blockOffset );
  143. idx.y.addAssign( blockOffset );
  144. return idx;
  145. };
  146. const getDisperseIndices = ( index, blockHeight ) => {
  147. const blockOffset = ( ( index.mul( 2 ) ).div( blockHeight ) ).mul( blockHeight );
  148. const halfHeight = blockHeight.div( 2 );
  149. const idx = uvec2(
  150. index.modInt( halfHeight ),
  151. ( index.modInt( halfHeight ) ).add( halfHeight )
  152. );
  153. idx.x.addAssign( blockOffset );
  154. idx.y.addAssign( blockOffset );
  155. return idx;
  156. };
  157. const localStorage = workgroupArray( 'uint', 64 * 2 );
  158. // Swap the elements in local storage
  159. const localCompareAndSwap = ( idxBefore, idxAfter ) => {
  160. If( localStorage.element( idxAfter ).lessThan( localStorage.element( idxBefore ) ), () => {
  161. const temp = localStorage.element( idxBefore ).toVar();
  162. localStorage.element( idxBefore ).assign( localStorage.element( idxAfter ) );
  163. localStorage.element( idxAfter ).assign( temp );
  164. } );
  165. };
  166. const globalCompareAndSwap = ( idxBefore, idxAfter ) => {
  167. // If the later element is less than the current element
  168. If( currentElementsStorage.element( idxAfter ).lessThan( currentElementsStorage.element( idxBefore ) ), () => {
  169. // Apply the swapped values to temporary storage.
  170. tempStorage.element( idxBefore ).assign( currentElementsStorage.element( idxAfter ) );
  171. tempStorage.element( idxAfter ).assign( currentElementsStorage.element( idxBefore ) );
  172. } ).Else( () => {
  173. // Otherwise apply the existing values to temporary storage.
  174. tempStorage.element( idxBefore ).assign( currentElementsStorage.element( idxBefore ) );
  175. tempStorage.element( idxAfter ).assign( currentElementsStorage.element( idxAfter ) );
  176. } );
  177. };
  178. const computeInitFn = Fn( () => {
  179. randomizedElementsStorage.element( instanceIndex ).assign( currentElementsStorage.element( instanceIndex ) );
  180. } );
  181. const computeBitonicStepFn = Fn( () => {
  182. const nextBlockHeight = nextBlockHeightStorage.element( 0 ).toVar();
  183. const nextAlgo = nextAlgoStorage.element( 0 ).toVar();
  184. // Get ids of indices needed to populate workgroup local buffer.
  185. // Use .toVar() to prevent these values from being recalculated multiple times.
  186. const workgroupId = instanceIndex.div( WORKGROUP_SIZE[ 0 ] ).toVar();
  187. const localOffset = uint( WORKGROUP_SIZE[ 0 ] ).mul( 2 ).mul( workgroupId ).toVar();
  188. const localID1 = invocationLocalIndex.mul( 2 );
  189. const localID2 = invocationLocalIndex.mul( 2 ).add( 1 );
  190. // If we will perform a local swap, then populate the local data
  191. If( nextAlgo.lessThanEqual( uint( StepType.DISPERSE_LOCAL ) ), () => {
  192. localStorage.element( localID1 ).assign( currentElementsStorage.element( localOffset.add( localID1 ) ) );
  193. localStorage.element( localID2 ).assign( currentElementsStorage.element( localOffset.add( localID2 ) ) );
  194. } );
  195. workgroupBarrier();
  196. // TODO: Convert to switch block.
  197. If( nextAlgo.equal( uint( StepType.FLIP_LOCAL ) ), () => {
  198. const idx = getFlipIndices( invocationLocalIndex, nextBlockHeight );
  199. localCompareAndSwap( idx.x, idx.y );
  200. } ).ElseIf( nextAlgo.equal( uint( StepType.DISPERSE_LOCAL ) ), () => {
  201. const idx = getDisperseIndices( invocationLocalIndex, nextBlockHeight );
  202. localCompareAndSwap( idx.x, idx.y );
  203. } ).ElseIf( nextAlgo.equal( uint( StepType.FLIP_GLOBAL ) ), () => {
  204. const idx = getFlipIndices( instanceIndex, nextBlockHeight );
  205. globalCompareAndSwap( idx.x, idx.y );
  206. } ).ElseIf( nextAlgo.equal( uint( StepType.DISPERSE_GLOBAL ) ), () => {
  207. const idx = getDisperseIndices( instanceIndex, nextBlockHeight );
  208. globalCompareAndSwap( idx.x, idx.y );
  209. } );
  210. // Ensure that all invocations have swapped their own regions of data
  211. workgroupBarrier();
  212. // Populate output data with the results from our swaps
  213. If( nextAlgo.lessThanEqual( uint( StepType.DISPERSE_LOCAL ) ), () => {
  214. currentElementsStorage.element( localOffset.add( localID1 ) ).assign( localStorage.element( localID1 ) );
  215. currentElementsStorage.element( localOffset.add( localID2 ) ).assign( localStorage.element( localID2 ) );
  216. } );
  217. // If the previous algorithm was global, we execute an additional compute step to sync the current buffer with the output buffer.
  218. } );
  219. const computeSetAlgoFn = Fn( () => {
  220. const nextBlockHeight = nextBlockHeightStorage.element( 0 ).toVar();
  221. const nextAlgo = nextAlgoStorage.element( 0 );
  222. const highestBlockHeight = highestBlockHeightStorage.element( 0 ).toVar();
  223. nextBlockHeight.divAssign( 2 );
  224. If( nextBlockHeight.equal( 1 ), () => {
  225. highestBlockHeight.mulAssign( 2 );
  226. if ( forceGlobalSwap ) {
  227. If( highestBlockHeight.equal( size * 2 ), () => {
  228. nextAlgo.assign( StepType.NONE );
  229. nextBlockHeight.assign( 0 );
  230. } ).Else( () => {
  231. nextAlgo.assign( StepType.FLIP_GLOBAL );
  232. nextBlockHeight.assign( highestBlockHeight );
  233. } );
  234. } else {
  235. If( highestBlockHeight.equal( size * 2 ), () => {
  236. nextAlgo.assign( StepType.NONE );
  237. nextBlockHeight.assign( 0 );
  238. } ).ElseIf( highestBlockHeight.greaterThan( WORKGROUP_SIZE[ 0 ] * 2 ), () => {
  239. nextAlgo.assign( StepType.FLIP_GLOBAL );
  240. nextBlockHeight.assign( highestBlockHeight );
  241. } ).Else( () => {
  242. nextAlgo.assign( forceGlobalSwap ? StepType.FLIP_GLOBAL : StepType.FLIP_LOCAL );
  243. nextBlockHeight.assign( highestBlockHeight );
  244. } );
  245. }
  246. } ).Else( () => {
  247. if ( forceGlobalSwap ) {
  248. nextAlgo.assign( StepType.DISPERSE_GLOBAL );
  249. } else {
  250. nextAlgo.assign( nextBlockHeight.greaterThan( WORKGROUP_SIZE[ 0 ] * 2 ).select( StepType.DISPERSE_GLOBAL, StepType.DISPERSE_LOCAL ) );
  251. }
  252. } );
  253. nextBlockHeightStorage.element( 0 ).assign( nextBlockHeight );
  254. highestBlockHeightStorage.element( 0 ).assign( highestBlockHeight );
  255. } );
  256. const computeAlignCurrentFn = Fn( () => {
  257. currentElementsStorage.element( instanceIndex ).assign( tempStorage.element( instanceIndex ) );
  258. } );
  259. const computeResetBuffersFn = Fn( () => {
  260. currentElementsStorage.element( instanceIndex ).assign( randomizedElementsStorage.element( instanceIndex ) );
  261. } );
  262. const computeResetAlgoFn = Fn( () => {
  263. nextAlgoStorage.element( 0 ).assign( forceGlobalSwap ? StepType.FLIP_GLOBAL : StepType.FLIP_LOCAL );
  264. nextBlockHeightStorage.element( 0 ).assign( 2 );
  265. highestBlockHeightStorage.element( 0 ).assign( 2 );
  266. } );
  267. // Initialize each value in the elements buffer.
  268. const computeInit = computeInitFn().compute( size );
  269. // Swap a pair of elements in the elements buffer.
  270. const computeBitonicStep = computeBitonicStepFn().compute( size / 2 );
  271. // Set the conditions for the next swap.
  272. const computeSetAlgo = computeSetAlgoFn().compute( 1 );
  273. // Align the current buffer with the temp buffer if the previous sort was executed in a global scope.
  274. const computeAlignCurrent = computeAlignCurrentFn().compute( size );
  275. // Reset the buffers and algorithm information after a full bitonic sort has been completed.
  276. const computeResetBuffers = computeResetBuffersFn().compute( size );
  277. const computeResetAlgo = computeResetAlgoFn().compute( 1 );
  278. const material = new THREE.MeshBasicNodeMaterial( { color: 0x00ff00 } );
  279. const display = Fn( () => {
  280. const { gridWidth, gridHeight, highlight } = effectController;
  281. const newUV = uv().mul( vec2( gridWidth, gridHeight ) );
  282. const pixel = uvec2( uint( floor( newUV.x ) ), uint( floor( newUV.y ) ) );
  283. const elementIndex = uint( gridWidth ).mul( pixel.y ).add( pixel.x );
  284. const colorChanger = currentElementsStorage.element( elementIndex );
  285. const subtracter = float( colorChanger ).div( gridWidth.mul( gridHeight ) );
  286. const color = vec3( subtracter.oneMinus() ).toVar();
  287. If( highlight.equal( 1 ).and( not( nextAlgoStorage.element( 0 ).equal( StepType.NONE ) ) ), () => {
  288. const boolCheck = int( elementIndex.modInt( nextBlockHeightRead.element( 0 ) ).lessThan( nextBlockHeightRead.element( 0 ).div( 2 ) ) );
  289. color.z.assign( nextAlgoStorage.element( 0 ).lessThanEqual( StepType.DISPERSE_LOCAL ) );
  290. color.x.mulAssign( boolCheck );
  291. color.y.mulAssign( abs( boolCheck.sub( 1 ) ) );
  292. } );
  293. return color;
  294. } );
  295. material.colorNode = display();
  296. const plane = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), material );
  297. scene.add( plane );
  298. const renderer = new THREE.WebGPURenderer( { antialias: false, trackTimestamp: true } );
  299. renderer.setPixelRatio( window.devicePixelRatio );
  300. renderer.setSize( window.innerWidth / 2, window.innerHeight );
  301. const animate = () => {
  302. renderer.render( scene, camera );
  303. };
  304. renderer.setAnimationLoop( animate );
  305. document.body.appendChild( renderer.domElement );
  306. renderer.domElement.style.position = 'absolute';
  307. renderer.domElement.style.top = '0';
  308. renderer.domElement.style.left = '0';
  309. renderer.domElement.style.width = '50%';
  310. renderer.domElement.style.height = '100%';
  311. if ( forceGlobalSwap ) {
  312. renderer.domElement.style.left = '50%';
  313. scene.background = new THREE.Color( 0x212121 );
  314. } else {
  315. scene.background = new THREE.Color( 0x313131 );
  316. }
  317. await renderer.computeAsync( computeInit );
  318. renderer.info.autoReset = false;
  319. const stepAnimation = async function () {
  320. renderer.info.reset();
  321. if ( currentStep !== MAX_STEPS ) {
  322. renderer.compute( computeBitonicStep );
  323. if ( nextStepGlobal ) {
  324. renderer.compute( computeAlignCurrent );
  325. }
  326. renderer.compute( computeSetAlgo );
  327. currentStep ++;
  328. } else {
  329. renderer.compute( computeResetBuffers );
  330. renderer.compute( computeResetAlgo );
  331. currentStep = 0;
  332. }
  333. const algo = new Uint32Array( await renderer.getArrayBufferAsync( nextAlgoBuffer ) );
  334. algo > StepType.DISPERSE_LOCAL ? ( nextStepGlobal = true ) : ( nextStepGlobal = false );
  335. renderer.render( scene, camera );
  336. timestamps[ forceGlobalSwap ? 'global_swap' : 'local_swap' ].innerHTML = `
  337. Compute ${forceGlobalSwap ? 'Global' : 'Local'}: ${renderer.info.compute.frameCalls} pass in ${renderer.info.compute.timestamp.toFixed( 6 )}ms<br>
  338. <div style="display: flex; flex-direction:row; justify-content: center; align-items: center;">
  339. ${forceGlobalSwap ? 'Global Swaps' : 'Local Swaps'} Compare Region&nbsp;
  340. <div style="background-color: ${ forceGlobalSwap ? globalColors[ 0 ] : localColors[ 0 ]}; width:12.5px; height: 1em; border-radius: 20%;"></div>
  341. &nbsp;to Region&nbsp;
  342. <div style="background-color: ${ forceGlobalSwap ? globalColors[ 1 ] : localColors[ 1 ]}; width:12.5px; height: 1em; border-radius: 20%;"></div>
  343. </div>`;
  344. if ( currentStep === MAX_STEPS ) {
  345. setTimeout( stepAnimation, 1000 );
  346. } else {
  347. setTimeout( stepAnimation, 50 );
  348. }
  349. };
  350. stepAnimation();
  351. window.addEventListener( 'resize', onWindowResize );
  352. function onWindowResize() {
  353. renderer.setSize( window.innerWidth / 2, window.innerHeight );
  354. const aspect = ( window.innerWidth / 2 ) / window.innerHeight;
  355. const frustumHeight = camera.top - camera.bottom;
  356. camera.left = - frustumHeight * aspect / 2;
  357. camera.right = frustumHeight * aspect / 2;
  358. camera.updateProjectionMatrix();
  359. renderer.render( scene, camera );
  360. }
  361. }
  362. </script>
  363. </body>
  364. </html>