Repository: SuboptimalEng/slime-sim-webgpu Branch: main Commit: 99ca2b7444ec Files: 27 Total size: 78.2 KB Directory structure: gitextract_n2nuv297/ ├── .gitignore ├── LICENSE ├── README-VITE.md ├── README.md ├── eslint.config.js ├── index.html ├── package.json ├── postcss.config.js ├── src/ │ ├── App.tsx │ ├── index.css │ ├── main.tsx │ ├── slime-mold/ │ │ ├── create-pipeline-fns.ts │ │ ├── initialize-fns.ts │ │ ├── initialize-helpers.ts │ │ ├── main.ts │ │ ├── shaders/ │ │ │ ├── common-uniforms.wgsl │ │ │ ├── compute-01-update-agents.wgsl │ │ │ ├── compute-02-fade-agents-trail.wgsl │ │ │ ├── compute-03-blur-agents-trail.wgsl │ │ │ └── render-01-draw-agents.wgsl │ │ └── uniforms.ts │ └── vite-env.d.ts ├── tailwind.config.js ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* pnpm-debug.log* lerna-debug.log* node_modules dist dist-ssr *.local # Editor directories and files .vscode/* !.vscode/extensions.json .idea .DS_Store *.suo *.ntvs* *.njsproj *.sln *.sw? ================================================ FILE: LICENSE ================================================ Attribution-NonCommercial-ShareAlike 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and b. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. Additional offer from the Licensor -- Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter's License You apply. c. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. b. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 1. The Adapter's License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: README-VITE.md ================================================ # React + TypeScript + Vite This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. Currently, two official plugins are available: - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh ## Expanding the ESLint configuration If you are developing a production application, we recommend updating the configuration to enable type aware lint rules: - Configure the top-level `parserOptions` property like this: ```js export default tseslint.config({ languageOptions: { // other options... parserOptions: { project: ['./tsconfig.node.json', './tsconfig.app.json'], tsconfigRootDir: import.meta.dirname, }, }, }); ``` - Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` - Optionally add `...tseslint.configs.stylisticTypeChecked` - Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: ```js // eslint.config.js import react from 'eslint-plugin-react'; export default tseslint.config({ // Set the react version settings: { react: { version: '18.3' } }, plugins: { // Add the react plugin react, }, rules: { // other rules... // Enable its recommended rules ...react.configs.recommended.rules, ...react.configs['jsx-runtime'].rules, }, }); ``` ================================================ FILE: README.md ================================================ # 🦠 Slime Sim WebGPU I made this slime mold simulation to learn more about WebGPU and compute shaders. It's essentially a recreation of Sebastian Lague's coding adventure (albiet with fewer features). Here's a 45-second demo on [Twitter](https://x.com/SuboptimalEng/status/1873425520106582229), [Threads](https://www.threads.net/@suboptimaleng/post/DEK9UtZIX5n?hl=en), and [r/GraphicsProgramming](https://www.reddit.com/r/GraphicsProgramming/comments/1hp4kn2/webgpu_typescript_slime_mold_simulation/). You can also try the playable demo on my website (linked in the about section of this repo). Just know that WebGPU doesn't work on all devices so you might get an error screen. If you prefer a more in-depth video, you can checkout this [5-minute devlog on YouTube](https://www.youtube.com/watch?v=nBqZOz7AF34) where I showcase an extended demo and answer the following questions: - What is WebGPU? - What are compute shaders? - What is the graphics pipeline for this slime simulation? - What happens in each shader pass? ## Setup Guide ``` # Setup Guide (for everyone). git clone https://github.com/SuboptimalEng/slime-sim-webgpu.git cd slime-sim-webgpu npm install npm run dev # How to Deploy to GitHub Pages (mainly for me). # First, go to main.tsx file and enable StrictMode. npm run build npm run deploy # Disable StrictMode before running locally and pushing to GitHub. ``` ## Screenshots ## Resources #### WebGPU - [WebGPU Fundamentals](https://webgpufundamentals.org/) - [Google's Game of Life WebGPU Tutorial Series](https://codelabs.developers.google.com/your-first-webgpu-app#0) #### Slime Mold Simulation - [Jeff Jones' Physarum Research Paper](https://uwe-repository.worktribe.com/output/980579) - [Sebastian Lague's Slime Simulation Code](https://github.com/SebLague/Slime-Simulation) - [Sebastian Lague’s Slime Simulation Video](https://www.youtube.com/watch?v=X-iSQQgOd1A) - [Simulife Hub's Slime Mold Simulation Video](https://www.youtube.com/watch?v=qryINYcgO1s) - [Sage Jenson's Physarum Simulation Article](https://cargocollective.com/sagejenson/physarum) ## License Shield: [![CC BY-NC-SA 4.0][cc-by-nc-sa-shield]][cc-by-nc-sa] This work is licensed under a [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License][cc-by-nc-sa]. [![CC BY-NC-SA 4.0][cc-by-nc-sa-image]][cc-by-nc-sa] [cc-by-nc-sa]: http://creativecommons.org/licenses/by-nc-sa/4.0/ [cc-by-nc-sa-image]: https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png [cc-by-nc-sa-shield]: https://img.shields.io/badge/License-CC%20BY--NC--SA%204.0-lightgrey.svg ================================================ FILE: eslint.config.js ================================================ import js from '@eslint/js'; import globals from 'globals'; import reactHooks from 'eslint-plugin-react-hooks'; import reactRefresh from 'eslint-plugin-react-refresh'; import tseslint from 'typescript-eslint'; export default tseslint.config( { ignores: ['dist'] }, { extends: [js.configs.recommended, ...tseslint.configs.recommended], files: ['**/*.{ts,tsx}'], languageOptions: { ecmaVersion: 2020, globals: globals.browser, }, plugins: { 'react-hooks': reactHooks, 'react-refresh': reactRefresh, }, rules: { ...reactHooks.configs.recommended.rules, 'react-refresh/only-export-components': [ 'warn', { allowConstantExport: true }, ], }, }, ); ================================================ FILE: index.html ================================================ Slime Sim WebGPU
================================================ FILE: package.json ================================================ { "name": "slime-mold-webgpu-ts", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -b && vite build", "deploy": "gh-pages -d dist", "lint": "eslint .", "preview": "vite preview" }, "dependencies": { "react": "^18.3.1", "react-dom": "^18.3.1", "tweakpane": "^4.0.5" }, "devDependencies": { "@eslint/js": "^9.13.0", "@tweakpane/core": "^2.0.5", "@types/react": "^18.3.12", "@types/react-dom": "^18.3.1", "@vitejs/plugin-react": "^4.3.3", "@webgpu/types": "^0.1.51", "autoprefixer": "^10.4.20", "eslint": "^9.13.0", "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.14", "gh-pages": "^6.2.0", "globals": "^15.11.0", "postcss": "^8.4.49", "tailwindcss": "^3.4.15", "typescript": "~5.6.2", "typescript-eslint": "^8.11.0", "vite": "^5.4.10" } } ================================================ FILE: postcss.config.js ================================================ export default { plugins: { tailwindcss: {}, autoprefixer: {}, }, } ================================================ FILE: src/App.tsx ================================================ import { useEffect, useState } from 'react'; import { main, cleanUp } from './slime-mold/main'; function App() { const [errorMessage, setErrorMessage] = useState(''); useEffect(() => { const runMainAsync = async () => { try { await main(); } catch (e: any) { setErrorMessage(String(e)); cleanUp(); } }; runMainAsync(); return () => { // We need to cancel request animation frame in the old main fn // when refreshing the page to avoid getting WebGPU errors. cleanUp(); }; }, []); return (
{errorMessage.length > 0 && (
{errorMessage}
)}
); } export default App; ================================================ FILE: src/index.css ================================================ @tailwind base; @tailwind components; @tailwind utilities; ================================================ FILE: src/main.tsx ================================================ import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import './index.css'; import App from './App.tsx'; createRoot(document.getElementById('root')!).render( // todo: use strict mode // // // , , ); ================================================ FILE: src/slime-mold/create-pipeline-fns.ts ================================================ import commonUniformsWGSL from './shaders/common-uniforms.wgsl?raw'; import c1UpdateAgentsWGSL from './shaders/compute-01-update-agents.wgsl?raw'; import c2FadeAgentsTrailWGSL from './shaders/compute-02-fade-agents-trail.wgsl?raw'; import c3BlurAgentsTrailWGSL from './shaders/compute-03-blur-agents-trail.wgsl?raw'; import r1DrawAgentsWGSL from './shaders/render-01-draw-agents.wgsl?raw'; const createUpdateAgentsComputePipeline = ( device: GPUDevice, slimeSimUniformsBufferGPU: GPUBuffer, agentsBufferGPU: GPUBuffer, gpuTextureForReadView: GPUTextureView, gpuTextureForStorageView: GPUTextureView, ) => { const updateAgentsWGSL = [commonUniformsWGSL, c1UpdateAgentsWGSL].join(''); const updateAgentsShaderModule = device.createShaderModule({ label: 'update agents: create shader module', code: updateAgentsWGSL, }); const updateAgentsComputeBindGroupLayout = device.createBindGroupLayout({ label: 'update agents: create compute bind group layout', entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform', }, }, { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'storage', }, }, { binding: 2, visibility: GPUShaderStage.COMPUTE, texture: { viewDimension: '2d', }, }, { binding: 3, visibility: GPUShaderStage.COMPUTE, storageTexture: { format: 'rgba8unorm', access: 'write-only', viewDimension: '2d', }, }, ], }); const updateAgentsComputePipelineLayout = device.createPipelineLayout({ label: 'update agents: create compute pipeline layout', bindGroupLayouts: [updateAgentsComputeBindGroupLayout], }); const updateAgentsComputePipeline = device.createComputePipeline({ label: 'update agents: create compute pipeline', layout: updateAgentsComputePipelineLayout, // todo: this seems to work, what are pros/cons of using auto? // layout: 'auto', compute: { entryPoint: 'updateAgents', module: updateAgentsShaderModule, }, }); const updateAgentsComputeBindGroup = device.createBindGroup({ label: 'update agents: create compute bind group', layout: updateAgentsComputeBindGroupLayout, // layout: updateAgentsComputePipeline.getBindGroupLayout(0), entries: [ { binding: 0, resource: { buffer: slimeSimUniformsBufferGPU, }, }, { binding: 1, resource: { buffer: agentsBufferGPU, }, }, { binding: 2, resource: gpuTextureForReadView, }, { binding: 3, resource: gpuTextureForStorageView, }, ], }); return { updateAgentsComputePipeline, updateAgentsComputeBindGroup }; }; const createFadeAgentsTrailComputePipeline = ( device: GPUDevice, slimeSimUniformsBufferGPU: GPUBuffer, gpuTextureForReadView: GPUTextureView, gpuTextureForStorageView: GPUTextureView, ) => { const fadeAgentsTrailWGSL = [commonUniformsWGSL, c2FadeAgentsTrailWGSL].join( '', ); const fadeAgentsTrailShaderModule = device.createShaderModule({ label: 'fade agents trail: create shader module', code: fadeAgentsTrailWGSL, }); const fadeAgentsTrailComputeBindGroupLayout = device.createBindGroupLayout({ label: 'fade agents trail: create bind group layout', entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform', }, }, { binding: 1, visibility: GPUShaderStage.COMPUTE, texture: { viewDimension: '2d', }, }, { binding: 2, visibility: GPUShaderStage.COMPUTE, storageTexture: { format: 'rgba8unorm', access: 'write-only', viewDimension: '2d', }, }, ], }); const fadeAgentsTrailComputePipelineLayout = device.createPipelineLayout({ label: 'fade agents trail: create compute pipeline layout', bindGroupLayouts: [fadeAgentsTrailComputeBindGroupLayout], }); const fadeAgentsTrailComputePipeline = device.createComputePipeline({ label: 'fade agents trail: create compute pipeline', layout: fadeAgentsTrailComputePipelineLayout, compute: { entryPoint: 'fadeAgentsTrail', module: fadeAgentsTrailShaderModule, }, }); const fadeAgentsTrailBindGroup = device.createBindGroup({ label: 'fade agents trail: create bind group', // layout: fadeAgentsTrailComputePipeline.getBindGroupLayout(0), layout: fadeAgentsTrailComputeBindGroupLayout, entries: [ { binding: 0, resource: { buffer: slimeSimUniformsBufferGPU, }, }, { binding: 1, resource: gpuTextureForReadView, }, { binding: 2, resource: gpuTextureForStorageView, }, ], }); return { fadeAgentsTrailComputePipeline, fadeAgentsTrailBindGroup }; }; const createBlurAgentsTrailComputePipeline = ( device: GPUDevice, slimeSimUniformsBufferGPU: GPUBuffer, colorizationUniformsBufferGPU: GPUBuffer, gpuTextureForReadView: GPUTextureView, gpuTextureForStorageView: GPUTextureView, ) => { // prettier-ignore const blurAgentsTrailWGSL = [commonUniformsWGSL, c3BlurAgentsTrailWGSL].join(''); const blurAgentsTrailShaderModule = device.createShaderModule({ label: 'blur agents trail: create shader module', code: blurAgentsTrailWGSL, }); const blurAgentsTrailComputeBindGroupLayout = device.createBindGroupLayout({ label: 'blur agents trail: create bindgroup layout', entries: [ { binding: 0, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform', }, }, { binding: 1, visibility: GPUShaderStage.COMPUTE, buffer: { type: 'uniform', }, }, { binding: 2, visibility: GPUShaderStage.COMPUTE, texture: { viewDimension: '2d', }, }, { binding: 3, visibility: GPUShaderStage.COMPUTE, storageTexture: { format: 'rgba8unorm', access: 'write-only', viewDimension: '2d', }, }, ], }); const blurAgentsTrailPipelineLayout = device.createPipelineLayout({ label: 'blur agents trail: create pipeline layout', bindGroupLayouts: [blurAgentsTrailComputeBindGroupLayout], }); const blurAgentsTrailPipeline = device.createComputePipeline({ label: 'blur agents trail: create compute pipeline', layout: blurAgentsTrailPipelineLayout, compute: { entryPoint: 'blurAgentsTrail', module: blurAgentsTrailShaderModule, }, }); const blurAgentsTrailBindGroup = device.createBindGroup({ label: 'blur agents trail: create bind group', layout: blurAgentsTrailComputeBindGroupLayout, entries: [ { binding: 0, resource: { buffer: slimeSimUniformsBufferGPU, }, }, { binding: 1, resource: { buffer: colorizationUniformsBufferGPU, }, }, { binding: 2, resource: gpuTextureForReadView, }, { binding: 3, resource: gpuTextureForStorageView, }, ], }); return { blurAgentsTrailPipeline, blurAgentsTrailBindGroup }; }; const createDrawAgentsRenderPipeline = ( device: GPUDevice, canvasFormat: GPUTextureFormat, slimeSimUniformsBufferGPU: GPUBuffer, colorizationUniformsBufferGPU: GPUBuffer, gpuTextureForReadView: GPUTextureView, ) => { const drawAgentsWGSL = [commonUniformsWGSL, r1DrawAgentsWGSL].join(''); const drawAgentsShaderModule = device.createShaderModule({ label: 'draw agents: create shader module', code: drawAgentsWGSL, }); const drawAgentsBindGroupLayout = device.createBindGroupLayout({ label: 'draw agents: create bind group layout', entries: [ { binding: 0, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform', }, }, { binding: 1, visibility: GPUShaderStage.FRAGMENT, buffer: { type: 'uniform', }, }, { binding: 2, visibility: GPUShaderStage.FRAGMENT, texture: { sampleType: 'float', }, }, ], }); const drawAgentsRenderPipeline = device.createRenderPipeline({ label: 'draw agents: create render pipeline', layout: device.createPipelineLayout({ bindGroupLayouts: [drawAgentsBindGroupLayout], }), vertex: { entryPoint: 'vertexShader', module: drawAgentsShaderModule, }, fragment: { entryPoint: 'fragmentShader', module: drawAgentsShaderModule, targets: [ { format: canvasFormat, }, ], }, primitive: { topology: 'triangle-list', }, }); const drawAgentsBindGroup = device.createBindGroup({ label: 'draw agents: create bind group', layout: drawAgentsBindGroupLayout, entries: [ { binding: 0, resource: { buffer: slimeSimUniformsBufferGPU, }, }, { binding: 1, resource: { buffer: colorizationUniformsBufferGPU, }, }, { binding: 2, resource: gpuTextureForReadView, }, ], }); return { drawAgentsRenderPipeline, drawAgentsBindGroup }; }; export { createUpdateAgentsComputePipeline, createFadeAgentsTrailComputePipeline, createBlurAgentsTrailComputePipeline, createDrawAgentsRenderPipeline, }; ================================================ FILE: src/slime-mold/initialize-fns.ts ================================================ import { Pane } from 'tweakpane'; import { UNIFORMS_COLORIZATION, UNIFORMS_SLIME_SIM } from './uniforms'; import { resetAgentsBuffer, resetColorizationUniformsBuffer, resetGPUTextures, resetSlimeSimUniformsBuffer, } from './initialize-helpers'; const initializeWebGPU = async (canvasWidth: number, canvasHeight: number) => { const canvas = document.querySelector('canvas'); if (!canvas) { throw new Error('No canvas detected in the browser.'); } if (!navigator.gpu) { throw new Error('WebGPU is not supported in this browser.'); } const adapter = await navigator.gpu.requestAdapter(); if (!adapter) { throw new Error('No appropriate GPUAdapter found.'); } // https://eliemichel.github.io/LearnWebGPU/getting-started/adapter-and-device/the-device.html // device is used to create all other gpu objects // once device is created, the adapter should in general no longer be used const device = await adapter.requestDevice(); device.addEventListener('uncapturederror', (event) => { console.log( `%c ${(event as GPUUncapturedErrorEvent).error.message}`, 'color: #FF0000; font-weight: bold; font-size: 12px', ); }); canvas.width = canvasWidth; canvas.height = canvasHeight; const canvasFormat = navigator.gpu.getPreferredCanvasFormat(); const context = canvas.getContext('webgpu'); if (!context) { throw new Error('Cannot recieve WebGPU context from canvas.'); } context.configure({ device: device, format: canvasFormat, }); return { device, canvas, canvasFormat, context }; }; const initializeSlimeSimUniforms = ( device: GPUDevice, canvas: HTMLCanvasElement, pane: Pane, ): GPUBuffer => { // ============================================================= // Set up tweakpane settings. // ============================================================= const generalFolder = pane.addFolder({ title: 'General' }); generalFolder.addBinding(UNIFORMS_SLIME_SIM.radius, 'value', { ...UNIFORMS_SLIME_SIM.radius, }); generalFolder.addBinding(UNIFORMS_SLIME_SIM.stepSize, 'value', { ...UNIFORMS_SLIME_SIM.stepSize, }); generalFolder.addBinding(UNIFORMS_SLIME_SIM.decayT, 'value', { ...UNIFORMS_SLIME_SIM.decayT, }); const agentFolder = pane.addFolder({ title: 'Agent' }); agentFolder.addBinding(UNIFORMS_SLIME_SIM.sensorOffset, 'value', { ...UNIFORMS_SLIME_SIM.sensorOffset, }); agentFolder.addBinding(UNIFORMS_SLIME_SIM.sensorAngle, 'value', { ...UNIFORMS_SLIME_SIM.sensorAngle, }); agentFolder.addBinding(UNIFORMS_SLIME_SIM.rotationAngle, 'value', { ...UNIFORMS_SLIME_SIM.rotationAngle, }); const randomizeAgentSettingsButton = agentFolder.addButton({ title: 'Randomize Agent Settings', }); // ============================================================= // Create gpu buffer(s). // // Array of size 8 is too small. // ============================================================= const uniformsCPU = new Float32Array(10); const uniformsBufferGPU = device.createBuffer({ label: 'create uniforms buffer for gpu', size: uniformsCPU.byteLength, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC | GPUBufferUsage.UNIFORM, }); resetSlimeSimUniformsBuffer(device, canvas, uniformsCPU, uniformsBufferGPU); // ============================================================= // Add tweakpane handlers. // ============================================================= pane.on('change', () => { resetSlimeSimUniformsBuffer(device, canvas, uniformsCPU, uniformsBufferGPU); console.log('pane changed!'); }); randomizeAgentSettingsButton.on('click', () => { console.log('randomize agents clicked!'); const getRandomValue = (min: number, max: number, step: number) => { const range = (max - min) / step; const randomStep = Math.floor(Math.random() * (range + 1)); return min + randomStep * step; }; const sensorOffset = UNIFORMS_SLIME_SIM.sensorOffset; const sensorAngle = UNIFORMS_SLIME_SIM.sensorAngle; const rotationAngle = UNIFORMS_SLIME_SIM.rotationAngle; UNIFORMS_SLIME_SIM.sensorOffset.value = getRandomValue( sensorOffset.min, sensorOffset.max, sensorOffset.step, ); UNIFORMS_SLIME_SIM.sensorAngle.value = getRandomValue( sensorAngle.min, sensorAngle.max, sensorAngle.step, ); UNIFORMS_SLIME_SIM.rotationAngle.value = getRandomValue( rotationAngle.min, rotationAngle.max, rotationAngle.step, ); pane.refresh(); }); return uniformsBufferGPU; }; const initializeColorizationUniforms = (device: GPUDevice, pane: Pane) => { // ============================================================= // Set up tweakpane settings. // ============================================================= const colorizationFolder = pane.addFolder({ title: 'Colorization' }); colorizationFolder.addBinding(UNIFORMS_COLORIZATION.blurTrail, 'value', { ...UNIFORMS_COLORIZATION.blurTrail, }); colorizationFolder.addBinding(UNIFORMS_COLORIZATION.enableLighting, 'value', { ...UNIFORMS_COLORIZATION.enableLighting, }); colorizationFolder.addBinding(UNIFORMS_COLORIZATION.slimeColor, 'value', { ...UNIFORMS_COLORIZATION.slimeColor, }); // ============================================================= // Create gpu buffer(s). // ============================================================= const colorizationUniformsArrayCPU = new Float32Array(12); const colorizationUniformsBufferGPU = device.createBuffer({ label: 'colorization uniforms buffer', size: colorizationUniformsArrayCPU.byteLength, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.COPY_SRC | GPUBufferUsage.UNIFORM, }); resetColorizationUniformsBuffer( device, colorizationUniformsArrayCPU, colorizationUniformsBufferGPU, ); // ============================================================= // Add tweakpane handlers. // ============================================================= colorizationFolder.on('change', () => { resetColorizationUniformsBuffer( device, colorizationUniformsArrayCPU, colorizationUniformsBufferGPU, ); }); return colorizationUniformsBufferGPU; }; const initializeGPUTextures = ( device: GPUDevice, canvas: HTMLCanvasElement, ) => { // ============================================================= // Create gpu buffer(s). // ============================================================= const gpuTextureForStorage = device.createTexture({ label: 'create texture A for storage on gpu', format: 'rgba8unorm', size: { width: canvas.width, height: canvas.height, }, usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC | GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING, }); const gpuTextureForRead = device.createTexture({ label: 'create texture B for read on gpu', format: 'rgba8unorm', size: { width: canvas.width, height: canvas.height, }, usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_BINDING, }); const gpuTextureForStorageView = gpuTextureForStorage.createView(); const gpuTextureForReadView = gpuTextureForRead.createView(); return { gpuTextureForStorage, gpuTextureForStorageView, gpuTextureForRead, gpuTextureForReadView, }; }; const initializeAgents = ( device: GPUDevice, canvas: HTMLCanvasElement, pane: Pane, gpuTextureForStorage: GPUTexture, gpuTextureForRead: GPUTexture, ) => { // ============================================================= // Set up tweakpane settings. // ============================================================= const simulationFolder = pane.addFolder({ title: 'Simulation' }); simulationFolder.addBinding(UNIFORMS_SLIME_SIM.numOfAgents, 'value', { ...UNIFORMS_SLIME_SIM.numOfAgents, }); simulationFolder.addBinding(UNIFORMS_SLIME_SIM.startRadius, 'value', { ...UNIFORMS_SLIME_SIM.startRadius, }); const downloadImageButton = simulationFolder.addButton({ title: 'Download Image', }); // ============================================================= // Create gpu buffer(s). // ============================================================= // todo: Currently, bind groups don't change variables so we initialize agentsBufferGPU // to be max size so that numOfAgents slider works as expected. More correct approach // could be to re-create bindgroups with agentsBufferGPU whenever it changes. // this will not incur performance hit because compute pass runs with SLIME_MOLD_UNIFORMS.numOfAgents // even if this gpu array is large, we won't use it for most calculations when numOfAgents is small const maxAgentsArraySize = UNIFORMS_SLIME_SIM.numOfAgents.max * 4; const fakeArrayCPU = new Float32Array(maxAgentsArraySize); const agentsBufferGPU = device.createBuffer({ label: 'create agents buffer', size: fakeArrayCPU.byteLength, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST, }); resetAgentsBuffer(device, canvas, agentsBufferGPU); resetGPUTextures(device, canvas, gpuTextureForStorage, gpuTextureForRead); // ============================================================= // Add tweakpane handlers. // ============================================================= simulationFolder.on('change', () => { resetAgentsBuffer(device, canvas, agentsBufferGPU); resetGPUTextures(device, canvas, gpuTextureForStorage, gpuTextureForRead); }); downloadImageButton.on('click', () => { const canvasImage = canvas.toDataURL('image/png'); // this can be used to download any image from webpage to local disk const xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = () => { const a = document.createElement('a'); a.href = window.URL.createObjectURL(xhr.response); a.download = 'slime-mold.png'; a.style.display = 'none'; document.body.appendChild(a); a.click(); a.remove(); }; xhr.open('GET', canvasImage); // This is to download the canvas Image xhr.send(); }); return agentsBufferGPU; }; export { initializeWebGPU, initializeGPUTextures, initializeAgents, initializeColorizationUniforms, initializeSlimeSimUniforms, }; ================================================ FILE: src/slime-mold/initialize-helpers.ts ================================================ import { UNIFORMS_COLORIZATION, UNIFORMS_SLIME_SIM } from './uniforms'; const resetAgentsBuffer = ( device: GPUDevice, canvas: HTMLCanvasElement, agentsBufferGPU: GPUBuffer, ) => { const numOfAgents = UNIFORMS_SLIME_SIM.numOfAgents.value; const agentsArraySize = numOfAgents * 4; const agentsArrayCPU = new Float32Array(agentsArraySize); // initialize agents data for (let i = 0; i < numOfAgents; i++) { // agent position let x = canvas.width / 2; let y = canvas.height / 2; let r = Math.random() * 10; agentsArrayCPU[i * 4 + 0] = x + Math.cos(r) * UNIFORMS_SLIME_SIM.startRadius.value; agentsArrayCPU[i * 4 + 1] = y + Math.sin(r) * UNIFORMS_SLIME_SIM.startRadius.value; // agent direction agentsArrayCPU[i * 4 + 2] = Math.random() * 2 - 1; agentsArrayCPU[i * 4 + 3] = Math.random() * 2 - 1; } // write to gpu buffer device.queue.writeBuffer(agentsBufferGPU, 0, agentsArrayCPU); return agentsBufferGPU; }; const resetSlimeSimUniformsBuffer = ( device: GPUDevice, canvas: HTMLCanvasElement, uniformsCPU: Float32Array, uniformsBufferGPU: GPUBuffer, ) => { // canvas uniformsCPU[0] = canvas.width; uniformsCPU[1] = canvas.height; // general uniformsCPU[2] = UNIFORMS_SLIME_SIM.radius.value; uniformsCPU[3] = UNIFORMS_SLIME_SIM.stepSize.value; uniformsCPU[4] = UNIFORMS_SLIME_SIM.decayT.value; // sensor uniformsCPU[5] = UNIFORMS_SLIME_SIM.sensorOffset.value; uniformsCPU[6] = UNIFORMS_SLIME_SIM.sensorAngle.value; uniformsCPU[7] = UNIFORMS_SLIME_SIM.rotationAngle.value; device.queue.writeBuffer(uniformsBufferGPU, 0, uniformsCPU); return uniformsBufferGPU; }; const resetColorizationUniformsBuffer = ( device: GPUDevice, colorizationUniformsCPU: Float32Array, colorizationUniformsBufferGPU: GPUBuffer, ) => { colorizationUniformsCPU[0] = UNIFORMS_COLORIZATION.blurTrail.value ? 1 : 0; colorizationUniformsCPU[1] = UNIFORMS_COLORIZATION.enableLighting.value ? 1 : 0; const slimeColor = UNIFORMS_COLORIZATION.slimeColor.value; // todo: dive a little deeper into struct memory packing // todo: for some reason, this needs to be 4th value, can't be the 1st one? colorizationUniformsCPU[4] = slimeColor.r / 255; colorizationUniformsCPU[5] = slimeColor.g / 255; colorizationUniformsCPU[6] = slimeColor.b / 255; device.queue.writeBuffer( colorizationUniformsBufferGPU, 0, colorizationUniformsCPU, ); }; const resetGPUTextures = ( device: GPUDevice, canvas: HTMLCanvasElement, gpuTextureForStorage: GPUTexture, gpuTextureForRead: GPUTexture, ) => { const size = Math.floor(canvas.width * canvas.height) * 4; const textureDataCPU = new Int8Array(size); for (let i = 0; i < canvas.width * canvas.height; i++) { textureDataCPU[i * 4 + 0] = 0; textureDataCPU[i * 4 + 1] = 0; textureDataCPU[i * 4 + 2] = 0; textureDataCPU[i * 4 + 3] = 255; } device.queue.writeTexture( { texture: gpuTextureForStorage, }, textureDataCPU, { bytesPerRow: canvas.width * 4, }, { width: canvas.width, height: canvas.height, }, ); device.queue.writeTexture( { texture: gpuTextureForRead, }, textureDataCPU, { bytesPerRow: canvas.width * 4, }, { width: canvas.width, height: canvas.height, }, ); }; export { resetAgentsBuffer, resetColorizationUniformsBuffer, resetGPUTextures, resetSlimeSimUniformsBuffer, }; ================================================ FILE: src/slime-mold/main.ts ================================================ import { Pane } from 'tweakpane'; import { UNIFORMS_SLIME_SIM } from './uniforms'; import { initializeWebGPU, initializeGPUTextures, initializeAgents, initializeColorizationUniforms, initializeSlimeSimUniforms, } from './initialize-fns'; import { createUpdateAgentsComputePipeline, createFadeAgentsTrailComputePipeline, createBlurAgentsTrailComputePipeline, createDrawAgentsRenderPipeline, } from './create-pipeline-fns'; // ============================================================= // These global variables are requied for the cleanUp fn. // ============================================================= let initializedPane: Pane = new Pane(); let rafId: number = 0; const main = async () => { let canvasWidth = 800; let canvasHeight = 600; // canvasWidth = 800; // canvasHeight = 800; // canvasWidth = 1600; // canvasHeight = 900; // canvasWidth *= 0.75; // canvasHeight *= 0.75; // ============================================================= // canvas -> ref to canvas, mainly used width/height info // device -> everything related to webgpu requires the device // canvasFormat -> needed for render pipeline fragment shader settings // context -> needed to create a view in the render pass // ============================================================= let device: GPUDevice | null = null; let canvas: HTMLCanvasElement | null = null; let canvasFormat: GPUTextureFormat | null = null; let context: GPUCanvasContext | null = null; try { const result = await initializeWebGPU(canvasWidth, canvasHeight); device = result.device; canvas = result.canvas; canvasFormat = result.canvasFormat; context = result.context; } catch (e: any) { throw e; } // ============================================================= // Initialize gpu storage texture that can be written to in compute shaders. // // Storage textures in WebGPU do not support read_write yet. This means // that we can write to storage texture in a compute pass, but we cannot // read from it in another compute pass. To get around this, we can create // a separate texture that copies the data from the storage texture after // every compute pass is complete. We can use this second texture to read // from in other compute passes. // ============================================================= const { gpuTextureForStorage, gpuTextureForStorageView, gpuTextureForRead, gpuTextureForReadView, } = initializeGPUTextures(device, canvas); // ============================================================= // Initialize the agents buffer. // ============================================================= const agentsBufferGPU = initializeAgents( device, canvas, initializedPane, gpuTextureForStorage, gpuTextureForRead, ); // ============================================================= // Initialize slime sim uniforms and tweakpane. // ============================================================= const slimeSimUniformsBufferGPU = initializeSlimeSimUniforms( device, canvas, initializedPane, ); // ============================================================= // Initialize colorization uniforms and tweakpane. // ============================================================= const colorizationUniformsBufferGPU = initializeColorizationUniforms( device, initializedPane, ); // ============================================================= // 1. Create updateAgents compute pipeline. // // This pass updates the position + direction of each agent. // It also draws the result onto a storage texture. // ============================================================= const { updateAgentsComputePipeline, updateAgentsComputeBindGroup } = createUpdateAgentsComputePipeline( device, slimeSimUniformsBufferGPU, agentsBufferGPU, gpuTextureForReadView, gpuTextureForStorageView, ); // ============================================================= // 2. Create fadeAgentsTrail compute pipeline. // ============================================================= const { fadeAgentsTrailComputePipeline, fadeAgentsTrailBindGroup } = createFadeAgentsTrailComputePipeline( device, slimeSimUniformsBufferGPU, gpuTextureForReadView, gpuTextureForStorageView, ); // ============================================================= // 3. Create blurAgentsTrail compute pipeline. // ============================================================= const { blurAgentsTrailPipeline, blurAgentsTrailBindGroup } = createBlurAgentsTrailComputePipeline( device, slimeSimUniformsBufferGPU, colorizationUniformsBufferGPU, gpuTextureForReadView, gpuTextureForStorageView, ); // ============================================================= // 4. Create drawAgents render pass. // ============================================================= const { drawAgentsRenderPipeline, drawAgentsBindGroup } = createDrawAgentsRenderPipeline( device, canvasFormat, slimeSimUniformsBufferGPU, colorizationUniformsBufferGPU, // todo: Which one is it? Storage or read? Both seem to work. // I'll stick with read view since that's what it's defined to // be in pipeline and WGSL shader. gpuTextureForReadView, // gpuTextureForStorageView, ); // ============================================================= // Define the render loop. // ============================================================= const render = () => { const encoder = device.createCommandEncoder(); // ============================================================= // 1. Run the updateAgents compute pass. // ============================================================= const updateAgentsComputePass = encoder.beginComputePass({ label: 'update agents: begin compute pass', }); updateAgentsComputePass.setPipeline(updateAgentsComputePipeline); updateAgentsComputePass.setBindGroup(0, updateAgentsComputeBindGroup); updateAgentsComputePass.dispatchWorkgroups( UNIFORMS_SLIME_SIM.numOfAgents.value, ); updateAgentsComputePass.end(); // ============================================================= // GPU storage textures do no support read + write (yet), so we need to // copy the storage texture data into a read texture so that it can be // accessed in the next pass (from the read texture). // // Copy agent positions from storage -> read texture. // ============================================================= encoder.copyTextureToTexture( { texture: gpuTextureForStorage }, // Source { texture: gpuTextureForRead }, // Destination [canvas.width, canvas.height, 1], // Size (width, height, depthOrArrayLayers) ); // ============================================================= // 2. Run the fadeAgentsTrail compute pass. // ============================================================= const fadeAgentsTrailComputePass = encoder.beginComputePass({ label: 'fade agents trail: begin compute pass', }); fadeAgentsTrailComputePass.setPipeline(fadeAgentsTrailComputePipeline); fadeAgentsTrailComputePass.setBindGroup(0, fadeAgentsTrailBindGroup); fadeAgentsTrailComputePass.dispatchWorkgroups(canvas.width, canvas.height); fadeAgentsTrailComputePass.end(); // ============================================================= // Copy fading trail from storage -> read texture. // ============================================================= encoder.copyTextureToTexture( { texture: gpuTextureForStorage }, // Source { texture: gpuTextureForRead }, // Destination [canvas.width, canvas.height, 1], // Size (width, height, depthOrArrayLayers) ); // ============================================================= // 3. Run the blurAgentsTrail compute pass. // ============================================================= const blurAgentsTrailComputePass = encoder.beginComputePass({ label: 'blur agents trail: begin compute pass', }); blurAgentsTrailComputePass.setPipeline(blurAgentsTrailPipeline); blurAgentsTrailComputePass.setBindGroup(0, blurAgentsTrailBindGroup); blurAgentsTrailComputePass.dispatchWorkgroups( // This means we need to create 8x8 workgroups in compute shader. canvas.width / 8, canvas.height / 8, ); blurAgentsTrailComputePass.end(); // ============================================================= // Copy blur agents trail from storage -> read texture. // ============================================================= encoder.copyTextureToTexture( { texture: gpuTextureForStorage }, // Source { texture: gpuTextureForRead }, // Destination [canvas.width, canvas.height, 1], // Size (width, height, depthOrArrayLayers) ); // ============================================================= // 4. Run the drawAgents (to canvas) render pass. // ============================================================= const drawAgentsRenderPass = encoder.beginRenderPass({ label: 'draw agents: begin render pass', colorAttachments: [ { view: context.getCurrentTexture().createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 1 }, }, ], }); drawAgentsRenderPass.setPipeline(drawAgentsRenderPipeline); drawAgentsRenderPass.setBindGroup(0, drawAgentsBindGroup); drawAgentsRenderPass.draw(6); drawAgentsRenderPass.end(); // ============================================================= // Final step. // ============================================================= device.queue.submit([encoder.finish()]); // ============================================================= // Keep track of rafId for the cleanUp fn. // ============================================================= rafId = requestAnimationFrame(render); }; // ============================================================= // Run the render loop. // ============================================================= render(); }; const cleanUp = () => { initializedPane.dispose(); cancelAnimationFrame(rafId); }; export { main, cleanUp }; ================================================ FILE: src/slime-mold/shaders/common-uniforms.wgsl ================================================ struct SlimeSimUniformsStruct { resolution: vec2f, // general radius: f32, stepSize: f32, decayT: f32, // sensor sensorOffset: f32, sensorAngle: f32, rotationAngle: f32, // other diffuseKernel: f32, }; struct ColorizationUniformsStruct { blurTrail: f32, enableLighting: f32, slimeColor: vec3f, }; ================================================ FILE: src/slime-mold/shaders/compute-01-update-agents.wgsl ================================================ // ============================================================= // Compute pass 1 -> update agents. // ============================================================= struct Agent { position: vec2f, direction: vec2f, } @group(0) @binding(0) var uSlimeSim: SlimeSimUniformsStruct; @group(0) @binding(1) var agentsArray: array; @group(0) @binding(2) var readFromThisTexture: texture_2d; @group(0) @binding(3) var writeToThisTexture: texture_storage_2d; fn rotationMatrix(degrees: f32) -> mat2x2f { let radians = radians(degrees); // Convert degrees to radians let cosTheta = cos(radians); let sinTheta = sin(radians); return mat2x2f( vec2f(cosTheta, -sinTheta), vec2f(sinTheta, cosTheta) ); } fn rotate(direction: vec2f, degrees: f32) -> vec2f { let rotMatrix = rotationMatrix(degrees); return rotMatrix * direction; } fn checkTrail(agentPosition: vec2f, newDir: vec2f) -> f32 { var sum: f32 = 0.0; let sensorWidth: i32 = 1; let sensorPosition = agentPosition + uSlimeSim.sensorOffset * newDir; for (var x = -sensorWidth; x <= sensorWidth; x++) { for (var y = -sensorWidth; y <= sensorWidth; y++) { let sampleX = i32(sensorPosition.x) + x; let sampleY = i32(sensorPosition.y) + y; sum += textureLoad(readFromThisTexture, vec2i(sampleX, sampleY), 0).r; } } return sum; } // takes a value and converts it between 0 and 1 fn hashTo01(value: u32) -> u32 { return (value * 2654435761u) % 2u; // Use a prime multiplier for hashing } @compute @workgroup_size(1) fn updateAgents( @builtin(global_invocation_id) id: vec3u ) { let idx = id.x; // Index for the current workgroup invocation if (idx < arrayLength(&agentsArray)) { // ============================================================= // 1. Motor stage -> update agents position. // reference: https://uwe-repository.worktribe.com/output/980579 // ============================================================= let uResolution: vec2f = uSlimeSim.resolution; let agentPosition: vec2f = agentsArray[idx].position; if (agentPosition.x < 0 || agentPosition.x > uResolution.x) { agentsArray[idx].direction.x *= -1.0; } if (agentPosition.y < 0 || agentPosition.y > uResolution.y) { agentsArray[idx].direction.y *= -1.0; } // In this case, we specifically want to use agents[idx].direction because that // is being changed, where as the local `agent` variable is not. // Make sure to normalize direction becaues otherwise, some agents move very slow. agentsArray[idx].position = agentPosition + normalize(agentsArray[idx].direction) * uSlimeSim.stepSize; // ============================================================= // 2. Sensory stage -> update agents direction based on sensors. // reference: https://uwe-repository.worktribe.com/output/980579 // // Lets say that abs(maxDegrees) = 145 // Add degrees to go left, subtract degrees to go right. // ============================================================= let uSensorAngle = uSlimeSim.sensorAngle; let sensorDegreeLeft = uSensorAngle; let sensorDegreeRight = -uSensorAngle; let sensorForwardDir = normalize(agentsArray[idx].direction); let sensorLeftDir = rotate(sensorForwardDir, sensorDegreeLeft); let sensorRightDir = rotate(sensorForwardDir, sensorDegreeRight); let F: f32 = checkTrail(agentsArray[idx].position, sensorForwardDir); let FL: f32 = checkTrail(agentsArray[idx].position, sensorLeftDir); let FR: f32 = checkTrail(agentsArray[idx].position, sensorRightDir); // // lets say that abs(maxDegrees) = 145 // // add degrees to go left, subtract degrees to go right let uRotationAngle = uSlimeSim.rotationAngle; let rotationDegreeLeft = uRotationAngle; let rotationDegreeRight = -uRotationAngle; let rotationForwardDir = normalize(agentsArray[idx].direction); let rotationLeftDir = rotate(rotationForwardDir, rotationDegreeLeft); let rotationRightDir = rotate(rotationForwardDir, rotationDegreeRight); if (F > FL && F > FR) { // do nothing } else if (F < FL && F < FR) { let zeroOrOne = f32(hashTo01(u32(F + FR + FL))); if (zeroOrOne < 0.1) { agentsArray[idx].direction = rotationLeftDir; } else { agentsArray[idx].direction = rotationRightDir; } } else if (FL < FR) { agentsArray[idx].direction = rotationRightDir; } else if (FR < FL) { agentsArray[idx].direction = rotationLeftDir; } else { // do nothing } } // ============================================================= // 3. Draw white dot with uSlimeSim.radius on texture. // ============================================================= let white = vec4f(1.0, 1.0, 1.0, 1.0); let agentCenterPos = vec2i(agentsArray[id.x].position); // Setting radius to decimal, like, 2.5 makes it an f32. // Type f32 doesn't allow x++ or y++ which is annoying in for-loops. // But type f32 can be useful if we want to make a circular agent with // a smaller radius since we can perform checks by incrementing 0.5 // units in the for-loop. let uRadius = uSlimeSim.radius; let rSquared = uRadius * uRadius; for (var x = -uRadius; x <= uRadius; x += 0.5) { for (var y = -uRadius; y <= uRadius; y += 0.5) { let offset = vec2f(x, y); let offsetDotProduct = dot(offset, offset); if (offsetDotProduct < rSquared) { // We need to cast offset to i32 since textureStore takes vec2i. // agentCenterPos has already been cast during initialization. let texelCoordToColorize = agentCenterPos + vec2i(offset); textureStore(writeToThisTexture, texelCoordToColorize, white); } } } } ================================================ FILE: src/slime-mold/shaders/compute-02-fade-agents-trail.wgsl ================================================ // ============================================================= // Compute pass 2 -> fade agents trail. // ============================================================= @group(0) @binding(0) var uSlimeSim: SlimeSimUniformsStruct; @group(0) @binding(1) var readFromThisTexture: texture_2d; @group(0) @binding(2) var writeToThisTexture: texture_storage_2d; @compute @workgroup_size(1) fn fadeAgentsTrail( @builtin(global_invocation_id) id: vec3u, ) { let currTextureColor = textureLoad(readFromThisTexture, id.xy, 0).rgb; let newTextureColor = currTextureColor - uSlimeSim.decayT; textureStore(writeToThisTexture, id.xy, vec4f(newTextureColor, 1.0)); } ================================================ FILE: src/slime-mold/shaders/compute-03-blur-agents-trail.wgsl ================================================ // ============================================================= // Compute pass 3 -> blur agents trail. // ============================================================= @group(0) @binding(0) var uSlimeSim: SlimeSimUniformsStruct; @group(0) @binding(1) var uColorization: ColorizationUniformsStruct; @group(0) @binding(2) var readFromThisTexture: texture_2d; @group(0) @binding(3) var writeToThisTexture: texture_storage_2d; @compute @workgroup_size(8, 8) fn blurAgentsTrail( @builtin(global_invocation_id) id: vec3u, ) { var newTextureColor = vec4f(0.0); let uBlurTrail = uColorization.blurTrail; let uCanvasSize = vec2u(uSlimeSim.resolution); // Avoid out-of-bounds access. if (id.x >= uCanvasSize.x || id.y >= uCanvasSize.y) { return; } // Seems like booleans cannot be passed as uniforms in a gpu buffer. // If blurTrail value is equal to 0, do not blur the texture. if (uBlurTrail < 1.0) { newTextureColor = textureLoad(readFromThisTexture, vec2i(id.xy), 0); } else { // todo: why does this loop seem slower? // var pixelCount = 0.0; // for (var x = -1; x <= 1; x++) { // for (var y = -1; y <= 1; y++) { // var currPos = vec2i(id.xy) + vec2i(x, y); // newTextureColor += textureLoad(readFromThisTexture, currPos, 0); // pixelCount += 1; // } // } // newTextureColor = newTextureColor / pixelCount; // this seems faster? var currPos = vec2i(id.xy); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(-1, 1), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(0, 1), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(1, 1), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(-1, 0), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(0, 0), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(1, 0), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(-1, -1), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(0, -1), 0); newTextureColor += textureLoad(readFromThisTexture, currPos + vec2i(1, -1), 0); newTextureColor /= 9.0; } textureStore(writeToThisTexture, id.xy, newTextureColor); } ================================================ FILE: src/slime-mold/shaders/render-01-draw-agents.wgsl ================================================ // ============================================================= // Draw agents render pass: vertex shader. // ============================================================= @vertex fn vertexShader( @builtin(vertex_index) index: u32 ) -> @builtin(position) vec4f { var positions = array( vec4(-1.0, -1.0, 0.0, 1.0), vec4( 1.0, -1.0, 0.0, 1.0), vec4(-1.0, 1.0, 0.0, 1.0), vec4( 1.0, -1.0, 0.0, 1.0), vec4( 1.0, 1.0, 0.0, 1.0), vec4(-1.0, 1.0, 0.0, 1.0) ); return positions[index]; } // ============================================================= // Draw agents render pass: fragment shader. // ============================================================= @group(0) @binding(0) var uSlimeSim: SlimeSimUniformsStruct; @group(0) @binding(1) var uColorization: ColorizationUniformsStruct; @group(0) @binding(2) var readFromThisTexture: texture_2d; fn calculateNormal(uv: vec2f) -> vec3f { // Sample neighboring pixels let h_x1 = textureLoad(readFromThisTexture, vec2i(uv) + vec2i(1, 0), 0).r; let h_x0 = textureLoad(readFromThisTexture, vec2i(uv) - vec2i(1, 0), 0).r; let h_y1 = textureLoad(readFromThisTexture, vec2i(uv) + vec2i(0, 1), 0).r; let h_y0 = textureLoad(readFromThisTexture, vec2i(uv) - vec2i(0, 1), 0).r; // Calculate gradients let strength = 2.0; let grad_x = (h_x1 - h_x0) * strength; let grad_y = (h_y1 - h_y0) * strength; // Compute and normalize the normal return normalize(vec3f(-grad_x, -grad_y, -1.0)); } @fragment fn fragmentShader( @builtin(position) fragCoord:vec4f ) -> @location(0) vec4f { // ============================================================= // Create the checkerboard pattern. // ============================================================= let checkerBoardUv = (2.0 * fragCoord.xy - uSlimeSim.resolution.xy) / uSlimeSim.resolution.y; let checkerBoardGridUv = vec2(floor(checkerBoardUv * 8.0)); var checkerBoardColor = vec3(0.0); if (floor((checkerBoardGridUv.x + checkerBoardGridUv.y) % 2) == 0) { checkerBoardColor = vec3(0.125); } else { checkerBoardColor = vec3(0.0625); } // ============================================================= // Set up uv coords and get texture color at the current coordinate. // ============================================================= let uv = fragCoord.xy / uSlimeSim.resolution; let currTextureColor = textureLoad(readFromThisTexture, vec2i(uv * uSlimeSim.resolution), 0); let uSlimeColor = uColorization.slimeColor; var fragColor = vec3f(0.0); // ============================================================= // Return early if we disabled lighting. // ============================================================= if (uColorization.enableLighting <= 0.0001) { // Mix between the checkerboard color, and slime color based on whether or not // the texture color is set to white. We can check for this using the r, g, or // b channels. Using alpha channel wouldn't make sense because it's always 1. fragColor = mix(checkerBoardColor, uSlimeColor, smoothstep(0.0, 1.0, currTextureColor.r)); return vec4(fragColor, 1.0); } // ============================================================= // Calculate lighting and stylize the result. // // Note that negative values for y moves the light source up. WebGPU has y in // reverse. Setting y = -0.25, will make light appear at the top-right! // ============================================================= let lightSource = vec3f(0.25, -0.25, -2.0); let viewSource = vec3f(0.0, 0.0, -1.0); let lightDir = normalize(lightSource); let viewDir = normalize(viewSource); // 32 or 64 seem like good numbers especially with lightSource // at vec3f(0.25, 0.25. -2.0). Higher value = sharper highlights. let shininess = 64.0; let surfaceNormal = calculateNormal(fragCoord.xy); let reflection = reflect(-lightDir, surfaceNormal); let specularIntensity = pow(max(dot(reflection, viewDir), 0.0), shininess); // Setting the baseColorIntensity to 0.8, ensures that specular highlights are // more easily visible. Setting it to 1.0 would make the specular highlights // harder to notice. let baseColorIntensity = 0.8; let lightColor = vec3f(1.0, 1.0, 1.0); let baseColor = uSlimeColor * currTextureColor.rgb * baseColorIntensity; let specularColor = lightColor * specularIntensity; fragColor = baseColor + specularColor; fragColor = pow(fragColor, vec3(2.0)); fragColor = mix(checkerBoardColor, fragColor, smoothstep(0.0, 1.0, currTextureColor.r)); return vec4f(fragColor, 1.0); } ================================================ FILE: src/slime-mold/uniforms.ts ================================================ const UNIFORMS_SLIME_SIM = { // simulation folder numOfAgents: { value: 20_000, label: 'NumOfAgents', min: 1_000, max: 60_000, step: 10_000, }, startRadius: { value: 100, label: 'StartRadius', min: 50, max: 250, step: 50, }, // general folder radius: { // The tweakpane UI shows 1 -> 3, but it's actually doing 0.5 -> 2.5 // Not sure if this is a bug with the library. value: 1.5, label: 'AgentSize', min: 0.5, max: 1.5, step: 1, }, stepSize: { value: 0.75, label: 'AgentSpeed', min: 0, max: 1.5, step: 0.25, }, decayT: { value: 0.005, label: 'TrailDecay', min: 0.005, max: 0.025, step: 0.005, }, // sensor settings folder sensorOffset: { value: 8, label: 'SensorOffset', min: 0, max: 20, step: 2, }, sensorAngle: { value: 45, label: 'SensorAngle', min: 5, max: 135, step: 5, }, rotationAngle: { value: 45, label: 'RotationAngle', min: 5, max: 135, step: 5, }, // todo: implement these fields? // sensorWidth: 1, // not really useful? // diffuseKernel: 0, // blur radius, not really useful? // pCD: 0, // probability of random change in direction }; const UNIFORMS_COLORIZATION = { blurTrail: { value: false, label: 'BlurTrail', }, enableLighting: { value: true, label: 'Lighting', }, slimeColor: { value: { r: 255, g: 0, b: 0 }, label: 'SlimeColor', picker: 'inline', // expanded: true, }, }; export { UNIFORMS_SLIME_SIM, UNIFORMS_COLORIZATION }; ================================================ FILE: src/vite-env.d.ts ================================================ /// ================================================ FILE: tailwind.config.js ================================================ /** @type {import('tailwindcss').Config} */ export default { content: ['./index.html', './src/**/*.{js,ts,jsx,tsx}'], theme: { extend: {}, }, plugins: [], }; ================================================ FILE: tsconfig.app.json ================================================ { "compilerOptions": { "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo", "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "Bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true, "types": ["@webgpu/types"] }, "include": ["src"] } ================================================ FILE: tsconfig.json ================================================ { "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" } ] } ================================================ FILE: tsconfig.node.json ================================================ { "compilerOptions": { "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", "target": "ES2022", "lib": ["ES2023"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "Bundler", "allowImportingTsExtensions": true, "isolatedModules": true, "moduleDetection": "force", "noEmit": true, /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "noUncheckedSideEffectImports": true }, "include": ["vite.config.ts"] } ================================================ FILE: vite.config.ts ================================================ import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; // https://vite.dev/config/ export default defineConfig({ plugins: [react()], base: '/slime-sim-webgpu', });