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