├── static
└── js
│ └── .gitkeep
├── .eslintignore
├── .gitignore
├── screenshot.png
├── webpack.prod.js
├── src
├── ts
│ ├── shader.d.ts
│ ├── flipper.ts
│ └── index.ts
└── glsl
│ ├── triangles.vert
│ ├── rendercells.frag
│ ├── rendertexture.frag
│ ├── rendercells.vert
│ ├── deposit.frag
│ └── life.frag
├── webpack.dev.js
├── index.html
├── tsconfig.json
├── webpack.common.js
├── .eslintrc.json
├── package.json
├── README.md
└── LICENSE.md
/static/js/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | static/js/*.generated.js
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | .vscode
3 | static/js/*.generated.js
4 |
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ollien/slime-mold/HEAD/screenshot.png
--------------------------------------------------------------------------------
/webpack.prod.js:
--------------------------------------------------------------------------------
1 | const common = require('./webpack.common.js');
2 |
3 | module.exports = common;
4 |
--------------------------------------------------------------------------------
/src/ts/shader.d.ts:
--------------------------------------------------------------------------------
1 | declare module '@shader/*' {
2 | const value: string;
3 | export default value;
4 | }
5 |
--------------------------------------------------------------------------------
/src/glsl/triangles.vert:
--------------------------------------------------------------------------------
1 | attribute vec2 a_position;
2 |
3 | void main() {
4 | gl_Position = vec4(a_position, 0., 1.);
5 | }
6 |
--------------------------------------------------------------------------------
/src/glsl/rendercells.frag:
--------------------------------------------------------------------------------
1 | #ifdef GL_ES
2 | precision mediump float;
3 | #endif
4 |
5 | void main() {
6 | gl_FragColor = vec4(1.);
7 | }
8 |
--------------------------------------------------------------------------------
/webpack.dev.js:
--------------------------------------------------------------------------------
1 | const merge = require('webpack-merge'); // eslint-disable-line import/no-extraneous-dependencies
2 | const common = require('./webpack.common.js');
3 |
4 | module.exports = merge(common, {
5 | devtool: 'eval-source-map',
6 | });
7 |
--------------------------------------------------------------------------------
/src/glsl/rendertexture.frag:
--------------------------------------------------------------------------------
1 | #ifdef GL_ES
2 | precision mediump float;
3 | #endif
4 |
5 | uniform vec2 resolution;
6 | uniform vec3 color;
7 | uniform sampler2D luma_texture;
8 |
9 | void main() {
10 | vec2 p = gl_FragCoord.xy/resolution;
11 |
12 | gl_FragColor = vec4(color/255. * texture2D(luma_texture, p).rgb, 1.0);
13 | }
14 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Slime Mold Simulation
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./src/ts",
4 | "module": "ES6",
5 | "sourceMap": true,
6 | "moduleResolution": "node",
7 | "lib": [
8 | "DOM",
9 | "DOM.Iterable",
10 | "ES2015",
11 | "ScriptHost"
12 | ],
13 | "esModuleInterop": true
14 | },
15 | "include": [
16 | "src/ts/*.ts",
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/src/glsl/rendercells.vert:
--------------------------------------------------------------------------------
1 | #ifdef GL_ES
2 | precision highp float;
3 | #endif
4 |
5 | attribute vec2 a_position;
6 | uniform sampler2D simulation_texture;
7 |
8 | void main() {
9 | vec2 cell = texture2D(simulation_texture, a_position).rg;
10 | // Vertex shaders must be from -1 to 1, but our positions are from to 0 to 1
11 | cell = cell * 2. - vec2(1.);
12 |
13 | // Render the cell at the position it told us it's at.
14 | gl_Position = vec4(cell, 0., 1.);
15 | gl_PointSize = 1.;
16 | }
17 |
--------------------------------------------------------------------------------
/webpack.common.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | entry: {
3 | index: ['./src/ts/index.ts'],
4 | },
5 | output: {
6 | filename: '[name].generated.js',
7 | path: `${__dirname}/static/js`,
8 | },
9 | module: {
10 | rules: [
11 | {
12 | test: /\.ts$/,
13 | use: 'ts-loader',
14 | exclude: /node_modules/,
15 | },
16 | {
17 | test: /\.(glsl|vert|frag)$/,
18 | use: [
19 | 'raw-loader',
20 | 'glslify-loader',
21 | ],
22 | exclude: /node_modules/,
23 | },
24 | ],
25 | },
26 | resolve: {
27 | extensions: ['.wasm', '.mjs', '.js', '.ts', '.json', '.frag', '.vert'],
28 | alias: {
29 | '@shader': `${__dirname}/src/glsl/`,
30 | },
31 | },
32 | };
33 |
--------------------------------------------------------------------------------
/src/ts/flipper.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Allows one to flip between a "front" and "back" object
3 | */
4 | export class Flipper {
5 | private sides: Array
6 |
7 | /**
8 | *
9 | * @param front The object to start with (i.e. the first one to be returned from flip())
10 | * @param back The object ot end with (i.e. the second to be returned from flip())
11 | */
12 | constructor(front: T, back: T) {
13 | this.sides = [front, back];
14 | }
15 |
16 | /**
17 | * Flip front and back, then return what was currently the "front"
18 | */
19 | flip(): T {
20 | const current = this.sides[0];
21 | this.sides.reverse();
22 |
23 | return current;
24 | }
25 |
26 | /**
27 | * Peek the front without flipping.
28 | */
29 | peekFront(): T {
30 | return this.sides[0];
31 | }
32 |
33 | /**
34 | * Peek the back without flipping.
35 | */
36 | peekBack(): T {
37 | return this.sides[1];
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/glsl/deposit.frag:
--------------------------------------------------------------------------------
1 | #ifdef GL_ES
2 | precision mediump float;
3 | #endif
4 |
5 | #define FEEDBACK_AMOUNT 0.925
6 | #define BLUR_RADIUS 5.
7 |
8 | uniform vec2 resolution;
9 | uniform sampler2D cell_texture;
10 | uniform sampler2D feedback_texture;
11 |
12 | /**
13 | * Perform a small blur effect by averaging points around the given point.
14 | */
15 | vec3 get_with_diffuse(sampler2D texture, vec2 pos) {
16 | vec3 color = vec3(0.);
17 | for (float i = -BLUR_RADIUS; i <= BLUR_RADIUS; i++) {
18 | for (float j = -BLUR_RADIUS; j <= BLUR_RADIUS; j++) {
19 | color += texture2D(texture, pos + vec2(i, j)/resolution).rgb;
20 | }
21 | }
22 |
23 | return color / pow(BLUR_RADIUS * 2. + 1., 2.);
24 | }
25 |
26 |
27 | void main() {
28 | vec2 p = gl_FragCoord.xy / resolution;
29 | vec3 cell = texture2D(cell_texture, p).rgb;
30 | vec3 old_deposit = get_with_diffuse(feedback_texture, p).rgb;
31 |
32 | gl_FragColor = vec4(cell + FEEDBACK_AMOUNT * old_deposit, 1.);
33 | }
34 |
--------------------------------------------------------------------------------
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "browser": true,
4 | "es6": true
5 | },
6 | "extends": [
7 | "airbnb-base"
8 | ],
9 | "globals": {
10 | "Atomics": "readonly",
11 | "SharedArrayBuffer": "readonly"
12 | },
13 | "parser": "@typescript-eslint/parser",
14 | "parserOptions": {
15 | "ecmaVersion": 2018,
16 | "sourceType": "module"
17 | },
18 | "plugins": [
19 | "@typescript-eslint"
20 | ],
21 | "rules": {
22 | "no-tabs": 0,
23 | "indent": ["error", "tab"],
24 | "no-plusplus": 0,
25 | "no-console": "off",
26 | "lines-between-class-members": "off",
27 | "import/extensions": "off",
28 | "import/prefer-default-export": "off",
29 | "max-len": ["error", {"code": 120}],
30 | "no-bitwise": "off"
31 | },
32 | "settings": {
33 | "import/resolver": {
34 | "node": {
35 | "extensions": [".js", ".ts"]
36 | }
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "cs-420x-assignment-3",
3 | "version": "0.1.0",
4 | "description": "Slime Mold Simulation",
5 | "scripts": {
6 | "build": "webpack --config webpack.prod.js",
7 | "start": "npm run web-server && webpack --watch --config webpack.dev.js",
8 | "web-server": "http-server -a 127.0.0.1 -p 8000 ./ &"
9 | },
10 | "author": "ollien",
11 | "dependencies": {
12 | "@types/dat.gui": "^0.7.5",
13 | "dat.gui": "^0.7.6",
14 | "glsl-random": "0.0.5",
15 | "lodash": "^4.17.15",
16 | "regl": "^1.3.13"
17 | },
18 | "devDependencies": {
19 | "@types/lodash": "^4.14.149",
20 | "@typescript-eslint/eslint-plugin": "^2.19.2",
21 | "@typescript-eslint/parser": "^2.19.2",
22 | "eslint": "^6.8.0",
23 | "eslint-config-airbnb-base": "^14.0.0",
24 | "eslint-plugin-import": "^2.20.1",
25 | "glslify": "^7.0.0",
26 | "glslify-loader": "^2.0.0",
27 | "http-server": "^0.12.1",
28 | "raw-loader": "^4.0.0",
29 | "ts-loader": "^6.2.1",
30 | "typescript": "^3.7.5",
31 | "webpack": "^4.41.6",
32 | "webpack-cli": "^3.3.11",
33 | "webpack-merge": "^4.2.2"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Slime Mold: CS420X Assignment 3
2 |
3 | Slime Mold (physarum) simulation. Based on [this blog post](https://sagejenson.com/physarum) and [this paper](https://uwe-repository.worktribe.com/output/980579). Inspiration for the implementation was sourced from [this blog post](https://kaesve.nl/projects/mold/summary.html).
4 |
5 | [Demo](https://ollien.github.io/slime-mold/)
6 |
7 | If you get poor performance with the demo, shrink your window and/or zoom in. This shader renders about 622k particles on a 1080p screen, so performance can suffer on some systems.
8 |
9 | 
10 |
11 | ## Controls
12 | Parameters of the simulation, which are described in the paper, can be adjusted in a GUI within the simulation. Further, dragging within the simulation will "disturb" the mold, allowing you to cut through it. Holding shift while you do this will bring some mold closer to your cursor.
13 |
14 | ## Installation
15 |
16 | To run the development server, run.
17 | ```
18 | npm install
19 | npm start
20 | ```
21 | If you just wish to build the static files and host this on your own webserver, you can run
22 | ```
23 | npm run-script build
24 | ```
25 |
--------------------------------------------------------------------------------
/src/glsl/life.frag:
--------------------------------------------------------------------------------
1 | #ifdef GL_ES
2 | precision highp float;
3 | #endif
4 |
5 | #define PI 3.14159
6 |
7 | #pragma glslify: random = require(glsl-random)
8 |
9 | uniform float step_size;
10 | uniform float sensor_distance_multiplier;
11 | uniform float sensor_angle_deg;
12 | uniform float rotate_angle_deg;
13 | uniform vec2 mouse_drag_position;
14 | uniform float disturb_radius;
15 | uniform bool paused;
16 | uniform bool pull_inwards;
17 |
18 | uniform vec2 resolution;
19 | uniform sampler2D simulation_texture;
20 | uniform sampler2D deposit_texture;
21 |
22 | vec4 get_simulation_value(vec2 coords) {
23 | return texture2D(simulation_texture, coords);
24 | }
25 |
26 | float get_deposit_value(vec2 coords) {
27 | return length(texture2D(deposit_texture, mod(coords, 1.)).rgb);
28 | }
29 |
30 | float relative_angle_to_rads(float angle) {
31 | return 2. * PI * angle;
32 | }
33 |
34 | float degrees_to_rads(float angle) {
35 | return angle / 180. * PI;
36 | }
37 |
38 | /**
39 | * Get the offset a cell will move in one step moving at the given angle (which must be in radians).
40 | */
41 | vec2 get_position_offset_from_angle(vec2 position, float angle) {
42 | vec2 step_coeff = vec2(step_size)/resolution;
43 |
44 | return step_coeff * vec2(cos(angle), sin(angle));
45 | }
46 |
47 | /**
48 | * Get the angle for the cell to move to after observing all of the sensors.
49 | */
50 | float get_movement_angle(vec2 current_position, float current_angle) {
51 | float sensor_angle = degrees_to_rads(sensor_angle_deg);
52 | float rotate_angle = degrees_to_rads(rotate_angle_deg);
53 | vec2 forward_sensor_pos = current_position + sensor_distance_multiplier * get_position_offset_from_angle(current_position, current_angle);
54 | vec2 left_sensor_pos = current_position + sensor_distance_multiplier * get_position_offset_from_angle(current_position, current_angle - sensor_angle);
55 | vec2 right_sensor_pos = current_position + sensor_distance_multiplier * get_position_offset_from_angle(current_position, current_angle + sensor_angle);
56 | float forward_sensor_value = get_deposit_value(forward_sensor_pos);
57 | float left_sensor_value = get_deposit_value(left_sensor_pos);
58 | float right_sensor_value = get_deposit_value(right_sensor_pos);
59 |
60 | if (forward_sensor_value > left_sensor_value && forward_sensor_value > right_sensor_value) {
61 | return current_angle;
62 | } else if (forward_sensor_value < left_sensor_value && forward_sensor_value < right_sensor_value) {
63 | // Randomly add or subtract ROTATION_ANGLE
64 | return (2. * step(0.5, random(gl_FragCoord.xy/resolution)) - 1.) * current_angle * rotate_angle;
65 | } else if (left_sensor_value < right_sensor_value) {
66 | return current_angle + rotate_angle;
67 | } else if (left_sensor_value > right_sensor_value) {
68 | return current_angle - rotate_angle;
69 | } else {
70 | return 0.;
71 | }
72 | }
73 |
74 | /**
75 | * Get the distance of this cell from the disturb center (i.e. where the mouse is clicked)
76 | */
77 | vec2 get_offset_from_disturb_center(vec2 cell_pos) {
78 | if (mouse_drag_position == vec2(-1.)) {
79 | return vec2(-1.);
80 | }
81 |
82 | return vec2(cell_pos.x - mouse_drag_position.x, cell_pos.y - mouse_drag_position.y);
83 | }
84 |
85 | void main() {
86 | // res holds the current cell, which will be augmented to its new position.
87 | // r represents x position, g represents y position, b represents angle and a is a boolean representing if the cell
88 | // is part of the simulation.
89 | vec4 res = get_simulation_value(gl_FragCoord.xy/resolution);
90 |
91 | float cell_angle = relative_angle_to_rads(res.b);
92 | float movement_angle = get_movement_angle(res.xy, cell_angle);
93 | vec2 offset = paused ? vec2(0.) : get_position_offset_from_angle(res.xy, movement_angle);
94 |
95 | vec2 disturb_offset = get_offset_from_disturb_center(res.xy);
96 | // If the user has clicked somewhere, we will have a disturb center (i.e. non -1). Check if this cell is within the radius of that click.
97 | if (disturb_offset != vec2(-1.) && length(disturb_offset) < length(vec2(disturb_radius)/resolution)) {
98 | // Divide this by sixteen so it takes a few frames for things to move out of the way
99 | float disturb_multiplier = disturb_radius/16.;
100 | offset = disturb_multiplier/resolution * vec2(sign(disturb_offset.x), sign(disturb_offset.y));
101 | if (pull_inwards) {
102 | offset *= -1.;
103 | }
104 | }
105 |
106 | vec2 new_pos = res.xy + offset;
107 | res.r = mod(new_pos.x, 1.);
108 | res.g = mod(new_pos.y, 1.);
109 |
110 | // If a pixel was already not part of the simulation, we don't want to put it into the simulation.
111 | // This step function shouldn't be needed, but due to floating point precision issues, simply doing a *= res.a will not work.
112 | res *= step(0., res.a);
113 |
114 | gl_FragColor = res;
115 | }
116 |
--------------------------------------------------------------------------------
/src/ts/index.ts:
--------------------------------------------------------------------------------
1 | import reglModule, { Framebuffer } from 'regl'; // eslint-disable-line no-unused-vars
2 | import dat from 'dat.gui';
3 | import lodash from 'lodash';
4 | import renderTextureShaderSource from '@shader/rendertexture.frag'; // eslint-disable-line import/no-unresolved
5 | import renderCellShaderSource from '@shader/rendercells.frag'; // eslint-disable-line import/no-unresolved
6 | import depositShaderSource from '@shader/deposit.frag'; // eslint-disable-line import/no-unresolved
7 | import renderCellVertexShaderSource from '@shader/rendercells.vert'; // eslint-disable-line import/no-unresolved
8 | import lifeShaderSource from '@shader/life.frag'; // eslint-disable-line import/no-unresolved
9 | import triangleVertexShaderSource from '@shader/triangles.vert'; // eslint-disable-line import/no-unresolved
10 | import { Flipper } from './flipper';
11 |
12 | const CANVAS_ID = 'gl';
13 | const CELL_PERCENTAGE = 0.30;
14 | const RENDER_TRIANGLE_VERTS = [
15 | [-1, -1],
16 | [1, -1],
17 | [-1, 1],
18 | [-1, 1],
19 | [1, -1],
20 | [1, 1],
21 | ];
22 |
23 | // Represents properties that can be varied in the simulation.
24 | interface SimulationProperties {
25 | stepSize: number,
26 | sensorDistance: number,
27 | sensorAngle: number,
28 | rotateAngle: number,
29 | color: [number, number, number],
30 | dragPosition: [number, number],
31 | disturbRadius: number,
32 | paused: boolean,
33 | pullInwards: boolean,
34 | }
35 |
36 | function setCanvasSize(canvas: HTMLCanvasElement): void {
37 | const html = document.querySelector('html');
38 | /* eslint-disable no-param-reassign */
39 | canvas.height = html.clientHeight - 4;
40 | canvas.width = html.clientWidth;
41 | /* eslint-enable no-param-reassign */
42 | }
43 |
44 | /**
45 | * Generates random up to n random pixels of the following form.
46 | * r: x coordinate
47 | * g: y coordinate
48 | * b: z coordinate
49 | * a: 1 if the pixel is part of the simulation, 0 otherwise.
50 | *
51 | * @param numRandomItems The number of items to generate. Must be <= length.
52 | * @param length The size of the array to generate. Will be padded with zeroes.
53 | */
54 | function makeRandomData(numRandomItems: number, length: number): number[] {
55 | if (numRandomItems > length) {
56 | throw Error('Attempted to generate more random items than array length');
57 | }
58 |
59 | const values = Array(length).fill(0).map((_, index): [number, number, number, number] => {
60 | if (index >= numRandomItems) {
61 | return [0, 0, 0, 0];
62 | }
63 |
64 | return [
65 | Math.random(),
66 | Math.random(),
67 | Math.random(),
68 | 1,
69 | ];
70 | });
71 |
72 | return lodash.flatten(values);
73 | }
74 |
75 | /**
76 | * Sets up the GUI needed to control the simulation.
77 | *
78 | * @param controlObject The object whose properties will control the simulation.
79 | */
80 | function setupSimulationGUI(controlObject: SimulationProperties) {
81 | const gui = new dat.GUI();
82 | gui.add(controlObject, 'stepSize', 0, 10);
83 | gui.add(controlObject, 'sensorDistance', 0, 50);
84 | gui.add(controlObject, 'sensorAngle', 0, 90);
85 | gui.add(controlObject, 'rotateAngle', 0, 90);
86 | gui.add(controlObject, 'disturbRadius', 0, 256);
87 | gui.add(controlObject, 'paused');
88 | gui.addColor(controlObject, 'color');
89 | }
90 |
91 | /**
92 | * Sets up an event to update the controlObject with the current drag position of the mouse.
93 | *
94 | * @param eventTarget The element to drag on
95 | * @param controlObject The object whose properties will control the simulation.
96 | */
97 | function setupMouseDragControl(eventTarget: HTMLElement, controlObject: SimulationProperties) {
98 | function assignPositionToController(event: MouseEvent) {
99 | if ((event.buttons & 1) !== 1) {
100 | return;
101 | }
102 |
103 | const { height, width } = eventTarget.getBoundingClientRect();
104 | // eslint-disable-next-line no-param-reassign
105 | controlObject.dragPosition = [
106 | event.x / width,
107 | // Our shader expects zero to be the bottom, but the event has zero be the top.
108 | 1 - event.y / height,
109 | ];
110 | }
111 |
112 | function assignDisturbDirectionToController(event: KeyboardEvent) {
113 | // eslint-disable-next-line no-param-reassign
114 | controlObject.pullInwards = event.shiftKey;
115 | }
116 |
117 | document.addEventListener('keydown', assignDisturbDirectionToController);
118 | document.addEventListener('keyup', assignDisturbDirectionToController);
119 |
120 | eventTarget.addEventListener('mousedown', assignPositionToController);
121 | eventTarget.addEventListener('mousemove', assignPositionToController);
122 | eventTarget.addEventListener('mouseup', () => {
123 | // eslint-disable-next-line no-param-reassign
124 | controlObject.dragPosition = [-1, -1];
125 | });
126 | }
127 |
128 | /**
129 | * Make one vertex for each cell, with coordinates for each cell.
130 | *
131 | * @param n The number of vertices to make
132 | * @param width The width of the rendering output
133 | * @param height The height of the rendering output
134 | */
135 | function makeCellVertices(n: number, width: number, height: number): [number, number][] {
136 | const res = [];
137 | for (let i = 0; i < width && res.length < n; i++) {
138 | for (let j = 0; j < height && res.length < n; j++) {
139 | res.push([i / width, j / height]);
140 | }
141 | }
142 |
143 | return res;
144 | }
145 |
146 | window.addEventListener('load', () => {
147 | const canvas = document.getElementById(CANVAS_ID);
148 | const simulationProperties: SimulationProperties = {
149 | stepSize: 1.1,
150 | sensorDistance: 9,
151 | sensorAngle: 22.5,
152 | rotateAngle: 45,
153 | color: [255, 255, 255],
154 | dragPosition: [-1, -1],
155 | disturbRadius: 32,
156 | paused: false,
157 | pullInwards: false,
158 | };
159 |
160 | setCanvasSize(canvas);
161 | setupSimulationGUI(simulationProperties);
162 | setupMouseDragControl(canvas, simulationProperties);
163 |
164 | const regl = reglModule({ canvas, extensions: ['OES_texture_float', 'WEBGL_color_buffer_float'] });
165 |
166 | /**
167 | * Makes an FBO with the settings needed to run the simulation.
168 | * @param data The data to use for the FBO
169 | */
170 | function makeFBO(data: number[]): Framebuffer {
171 | const { width, height } = canvas;
172 | return regl.framebuffer({
173 | width,
174 | height,
175 | colorType: 'float',
176 | color: regl.texture({
177 | width,
178 | height,
179 | data,
180 | format: 'rgba',
181 | // unit8 is not precise enough for the angle calculations that are required.
182 | type: 'float',
183 | }),
184 | depthStencil: false,
185 | });
186 | }
187 |
188 | const numPixels = canvas.width * canvas.height;
189 | const numCells = numPixels * CELL_PERCENTAGE;
190 | const cellData = makeRandomData(numCells, numPixels);
191 | const simulationStates = new Flipper(makeFBO(cellData), makeFBO(cellData));
192 | const emptyData = Array(numPixels * 4).fill(0);
193 | const cellStates = new Flipper(makeFBO(emptyData), makeFBO(emptyData));
194 | const depositStates = new Flipper(makeFBO(emptyData), makeFBO(emptyData));
195 |
196 | /**
197 | * Flip all of the Framebuffer flippers to allow for the next iteration to read the output of the current iteration.
198 | */
199 | function flipBuffers() {
200 | simulationStates.flip();
201 | cellStates.flip();
202 | depositStates.flip();
203 | }
204 |
205 | // Runs the simulation's calculations, calculating cell positions as needed.
206 | const runSimulation = regl({
207 | frag: lifeShaderSource,
208 | uniforms: {
209 | deposit_texture: (): Framebuffer => depositStates.peekBack(),
210 | simulation_texture: (): Framebuffer => simulationStates.peekFront(),
211 | // The type definitions for the properties state we must specify the key in the argument and the generic.
212 | step_size: regl.prop('stepSize'),
213 | sensor_distance_multiplier: regl.prop('sensorDistance'),
214 | sensor_angle_deg: regl.prop('sensorAngle'),
215 | rotate_angle_deg: regl.prop('rotateAngle'),
216 | mouse_drag_position: regl.prop('dragPosition'),
217 | disturb_radius: regl.prop('disturbRadius'),
218 | paused: regl.prop('paused'),
219 | pull_inwards: regl.prop('pullInwards'),
220 | },
221 | framebuffer: (): Framebuffer => simulationStates.peekBack(),
222 | });
223 |
224 | const cellVertices = makeCellVertices(numCells, canvas.width, canvas.height);
225 | // Renders the cells each as a vertex on the screen
226 | const renderCells = regl({
227 | frag: renderCellShaderSource,
228 | vert: renderCellVertexShaderSource,
229 | framebuffer: (): Framebuffer => cellStates.peekBack(),
230 | attributes: {
231 | a_position: cellVertices,
232 | },
233 | count: cellVertices.length,
234 | uniforms: {
235 | resolution: [canvas.width, canvas.height],
236 | simulation_texture: (): Framebuffer => simulationStates.peekFront(),
237 | },
238 | primitive: 'points',
239 | });
240 |
241 | // Renders the deposits from the cells, which is just the cells fed back into a texture.
242 | const renderDeposits = regl({
243 | frag: depositShaderSource,
244 | framebuffer: (): Framebuffer => depositStates.peekBack(),
245 | uniforms: {
246 | cell_texture: (): Framebuffer => cellStates.peekFront(),
247 | feedback_texture: (): Framebuffer => depositStates.peekFront(),
248 | },
249 | });
250 |
251 | // Renders the entire simulation to the screen
252 | const renderSimulation = regl({
253 | frag: renderTextureShaderSource,
254 | uniforms: {
255 | color: regl.prop('color'),
256 | luma_texture: (): Framebuffer => depositStates.peekFront(),
257 | },
258 | });
259 |
260 |
261 | regl.frame(() => {
262 | // Make sure we clear any cells that existed on the last frame
263 | regl.clear({ color: [0, 0, 0, 0], framebuffer: cellStates.peekBack() });
264 |
265 | regl({
266 | // All commands (except for renderCells) will use this vertex shader with the triangle attributes
267 | vert: triangleVertexShaderSource,
268 | attributes: {
269 | a_position: RENDER_TRIANGLE_VERTS,
270 | },
271 | count: RENDER_TRIANGLE_VERTS.length,
272 | // All commands will use the resolution uniform
273 | uniforms: {
274 | resolution: [canvas.width, canvas.height],
275 | },
276 | // None of the shaders need depth calculations
277 | depth: { enable: false },
278 | })(() => {
279 | // Pass the properties to the simulation as regl properties
280 | runSimulation(simulationProperties);
281 | // Render the cells as verts to the framebuffer
282 | renderCells();
283 | // Render and fade the old cells
284 | renderDeposits();
285 | // Render the whole thing to the screen.
286 | renderSimulation(simulationProperties);
287 | });
288 |
289 | flipBuffers();
290 | });
291 | });
292 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2020 Nicholas Krichevsky
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------