-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
369 lines (317 loc) · 14.1 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
const canvas = document.getElementById('canvas');
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (!gl) {
alert('WebGL is not supported by your browser. Please try another browser.');
}
class Particle {
constructor(x, y, temperature, lifetime) {
this.position = { x: x, y: y };
this.velocity = { x: 0, y: 0 };
this.acceleration = { x: 0, y: 0 };
this.density = 0;
this.pressure = 0;
this.temperature = temperature;
this.lifetime = lifetime;
this.buoyancy = 0;
this.coolingRate = 0.5
}
}
const timeStep = 0.01;
let smoothingRadius = 3;
let mass = 1;
let gasConstant = 8000;
let viscosity = 1;
let gravity = -9.8;
let maxTemperature = 5;
let maxLifetime = 2;
let emissionRate = 50;
let buoyancyConstant = -150;
let particleSize = 6;
let fireSourceY = 0;
let emitVelocity = 50;
let fireSourceRange = 50;
let numParticles = 800;
const particles = [];
// Create event listeners for the sliders
document.getElementById('smoothingRadius').addEventListener('input', function (event) {
smoothingRadius = parseFloat(event.target.value);
document.getElementById('smoothingRadiusValue').textContent = smoothingRadius;
});
document.getElementById('mass').addEventListener('input', function (event) {
mass = parseFloat(event.target.value);
document.getElementById('massValue').textContent = mass;
});
document.getElementById('gasConstant').addEventListener('input', function (event) {
gasConstant = parseFloat(event.target.value);
document.getElementById('gasConstantValue').textContent = gasConstant;
});
document.getElementById('viscosity').addEventListener('input', function (event) {
viscosity = parseFloat(event.target.value);
document.getElementById('viscosityValue').textContent = viscosity;
});
document.getElementById('gravity').addEventListener('input', function (event) {
gravity = parseFloat(event.target.value);
document.getElementById('gravityValue').textContent = gravity;
});
const maxTemperatureSelect = document.getElementById('maxTemperature');
maxTemperatureSelect.addEventListener('change', (event) => {
maxTemperature = parseFloat(event.target.value);
});
document.getElementById('maxLifetime').addEventListener('input', function (event) {
maxLifetime = parseFloat(event.target.value);
document.getElementById('maxLifetimeValue').textContent = maxLifetime;
});
document.getElementById('numParticles').addEventListener('input', function (event) {
numParticles = parseInt(event.target.value);
document.getElementById('numParticlesValue').textContent = numParticles;
});
document.getElementById('emissionRate').addEventListener('input', function (event) {
emissionRate = parseInt(event.target.value);
document.getElementById('emissionRateValue').textContent = emissionRate;
});
document.getElementById('buoyancyConstant').addEventListener('input', function (event) {
buoyancyConstant = parseFloat(event.target.value);
document.getElementById('buoyancyConstantValue').textContent = buoyancyConstant;
});
document.getElementById('particleSize').addEventListener('input', function (event) {
particleSize = parseFloat(event.target.value);
document.getElementById('particleSizeValue').textContent = particleSize;
});
document.getElementById('fireSourceY').addEventListener('input', function (event) {
fireSourceY = parseFloat(event.target.value);
document.getElementById('fireSourceYValue').textContent = fireSourceY;
});
document.getElementById('emitVelocity').addEventListener('input', function (event) {
emitVelocity = parseFloat(event.target.value);
document.getElementById('emitVelocityValue').textContent = emitVelocity;
});
document.getElementById('fireSourceRange').addEventListener('input', function (event) {
fireSourceRange = parseFloat(event.target.value);
document.getElementById('fireSourceRangeValue').textContent = fireSourceRange;
});
// Set the initial values for the labels
document.getElementById('smoothingRadiusValue').textContent = smoothingRadius;
document.getElementById('massValue').textContent = mass;
document.getElementById('gasConstantValue').textContent = gasConstant;
document.getElementById('viscosityValue').textContent = viscosity;
document.getElementById('gravityValue').textContent = gravity;
document.getElementById('maxLifetimeValue').textContent = maxLifetime;
document.getElementById('numParticlesValue').textContent = numParticles;
document.getElementById('emissionRateValue').textContent = emissionRate;
document.getElementById('buoyancyConstantValue').textContent = buoyancyConstant;
document.getElementById('particleSizeValue').textContent = particleSize;
document.getElementById('fireSourceYValue').textContent = fireSourceY;
document.getElementById('emitVelocityValue').textContent = emitVelocity;
document.getElementById('fireSourceRangeValue').textContent = fireSourceRange;
for (let i = 0; i < numParticles; i++) {
const x = Math.random() * canvas.width;
const y = Math.random() * canvas.height;
const temperature = Math.random() * maxTemperature;
const lifetime = Math.random() * maxLifetime;
particles.push(new Particle(x, y, temperature, lifetime));
}
function emitParticles(emissionRate) {
const fireSourceX = Math.floor(Math.random() * fireSourceRange) - (fireSourceRange/2) + (canvas.width / 2);
for (let i = 0; i < emissionRate; i++) {
const temperature = Math.random() * maxTemperature;
const lifetime = Math.random() * maxLifetime;
const particle = new Particle(fireSourceX, fireSourceY, temperature, lifetime);
particle.velocity.x = (Math.random() - 0.5) * emitVelocity;
particles.push(particle);
}
}
function poly6Kernel(r, h) {
const coefficient = 315 / (64 * Math.PI * Math.pow(h, 9));
const r2 = r * r;
const h2 = h * h;
return coefficient * Math.pow(h2 - r2, 3);
}
function spikyGradientKernel(r, h) {
const coefficient = -45 / (Math.PI * Math.pow(h, 6));
const h_r = h - r;
return coefficient * Math.pow(h_r, 2);
}
function viscosityLaplacianKernel(r, h) {
const coefficient = 45 / (Math.PI * Math.pow(h, 6));
return coefficient * (h - r);
}
function computeDensityAndPressure() {
for (let i = 0; i < numParticles; i++) {
let density = 0;
for (let j = 0; j < numParticles; j++) {
const dx = particles[i].position.x - particles[j].position.x;
const dy = particles[i].position.y - particles[j].position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < smoothingRadius) {
density += mass * poly6Kernel(distance, smoothingRadius);
}
}
particles[i].density = density;
particles[i].pressure = gasConstant * (density - 1);
}
}
function computeForces() {
for (let i = 0; i < numParticles; i++) {
let pressureForceX = 0;
let pressureForceY = 0;
let viscosityForceX = 0;
let viscosityForceY = 0;
for (let j = 0; j < numParticles; j++) {
if (i !== j) {
const dx = particles[i].position.x - particles[j].position.x;
const dy = particles[i].position.y - particles[j].position.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < smoothingRadius) {
const spikyGradient = spikyGradientKernel(distance, smoothingRadius);
const pressureTerm = -mass * (particles[i].pressure + particles[j].pressure) / (2 * particles[j].density) * spikyGradient;
pressureForceX += dx * pressureTerm / distance;
pressureForceY += dy * pressureTerm / distance;
const viscosityLaplacian = viscosityLaplacianKernel(distance, smoothingRadius);
const viscosityTerm = viscosity * mass / particles[j].density * viscosityLaplacian;
viscosityForceX += (particles[j].velocity.x - particles[i].velocity.x) * viscosityTerm;
viscosityForceY += (particles[j].velocity.y - particles[i].velocity.y) * viscosityTerm;
}
}
}
particles[i].buoyancy = -gravity * (particles[i].density - 1) * buoyancyConstant;
particles[i].acceleration.x = pressureForceX + viscosityForceX;
particles[i].acceleration.y = pressureForceY + viscosityForceY + gravity + particles[i].buoyancy;
}
}
function updateParticles() {
for (let i = particles.length - 1; i >= 0; i--) {
particles[i].velocity.x += particles[i].acceleration.x * timeStep;
particles[i].velocity.y += particles[i].acceleration.y * timeStep;
particles[i].position.x += particles[i].velocity.x * timeStep;
particles[i].position.y += particles[i].velocity.y * timeStep;
// Update the particle's lifetime
particles[i].lifetime -= timeStep;
if (particles[i].lifetime <= 0) {
particles.splice(i, 1);
continue;
}
// Update the particle's temperature
particles[i].temperature -= particles[i].coolingRate * timeStep;
particles[i].temperature = Math.max(particles[i].temperature, 0); // ensure temperature doesn't go below 0
// Keep the particles within the canvas bounds
particles[i].position.x = Math.min(Math.max(particles[i].position.x, 0), canvas.width);
particles[i].position.y = Math.min(Math.max(particles[i].position.y, 0), canvas.height);
}
}
const vertexShaderSource = `
attribute vec2 a_position;
uniform vec2 u_resolution;
uniform float u_particleSize;
void main() {
vec2 position = (a_position / u_resolution) * 2.0 - 1.0;
gl_Position = vec4(position, 0, 1);
gl_PointSize = u_particleSize;
}
`;
const fragmentShaderSource = `
precision mediump float;
uniform float u_maxTemperature;
void main() {
float dist = length(gl_PointCoord - vec2(0.5, 0.5));
if (dist < 0.5) {
float intensity = 1.0 - dist;
float temperature = intensity * u_maxTemperature;
vec3 color = vec3(1.0, 1.0, 1.0);
if (temperature > 3.0) {
color = vec3(1.0, 0.0, 0.0); // red
}
else if (temperature > 2.0) {
color = vec3(1.0, 0.5, 0.0); // orange
}
else if (temperature > 1.0) {
color = vec3(1.0, 1.0, 0.0); // yellow
}
gl_FragColor = vec4(color, 1.0);
}
else {
discard;
}
}
`;
function createShader(gl, type, source) {
const shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.error(`Error compiling shader: ${gl.getShaderInfoLog(shader)}`);
gl.deleteShader(shader);
return null;
}
return shader;
}
function drawParticles(particles) {
// Update the position and temperature data in the buffer
const data = new Float32Array(particles.length * 3);
for (let i = 0; i < particles.length; i++) {
data[i * 3] = particles[i].position.x;
data[i * 3 + 1] = particles[i].position.y;
data[i * 3 + 2] = particles[i].temperature;
}
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
// Set up the WebGL viewport and clear the color buffer
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0, 0, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
// Use the WebGL program and set the uniform and attribute values
gl.useProgram(program);
gl.uniform2f(resolutionUniformLocation, canvas.width, canvas.height);
gl.uniform1f(gl.getUniformLocation(program, 'u_maxTemperature'), maxTemperature);
gl.uniform1f(gl.getUniformLocation(program, 'u_particleSize'), particleSize);
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);
// Draw the particles
gl.drawArrays(gl.POINTS, 0, particles.length);
}
function time() {
var date = new Date();
var time = date.getTime();
return time;
}
// Display the FPS
let frameTime = 18;
let lastTime = time();
let tempTime = time();
function displayFPS() {
currentTime = time();
frameTime = frameTime * 0.9 + (currentTime - lastTime) * 0.1;
fps = 1000.0/frameTime;
if (currentTime - tempTime > 100) {
document.getElementById("fps").textContent = "FPS: " + Math.round(fps);
tempTime = currentTime;
}
lastTime = currentTime;
}
function mainLoop() {
displayFPS();
emitParticles(emissionRate);
// Update the simulation (e.g., call your SPH update functions)
computeDensityAndPressure();
computeForces();
updateParticles();
// Render the particles
drawParticles(particles);
// Request the next frame
requestAnimationFrame(mainLoop);
}
// initialize the WebGL context
const vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexShaderSource);
const fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentShaderSource);
const program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
console.error(`Error linking program: ${gl.getProgramInfoLog(program)}`);
}
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positionAttributeLocation = gl.getAttribLocation(program, 'a_position');
gl.enableVertexAttribArray(positionAttributeLocation);
gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);
const resolutionUniformLocation = gl.getUniformLocation(program, 'u_resolution');
mainLoop();