Напиши симулятор физики жидкости на js, с реализацией физики различных цветов и их…
- User
Напиши симулятор физики жидкости на js, с реализацией физики различных цветов и их смешивания, потоков, завихрений, интерактивностью (возможность взаимодействия с симуляцией, размещения источников жидкости, определенного количества жидкости, настройкой цвета) и хорошей оптимизацией. Требуется не упрощенный демонстрационный образец, а полноценный рабочий проект, независимо от сложности. Код пиши целиком.
- Assistant
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Advanced Fluid Simulator</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Arial', sans-serif; background: #0a0a0a; color: #fff; overflow: hidden; } #canvas { display: block; cursor: crosshair; background: radial-gradient(circle at center, #0a0a0a 0%, #000 100%); } .controls { position: absolute; top: 20px; left: 20px; background: rgba(20, 20, 20, 0.9); padding: 20px; border-radius: 10px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); max-width: 300px; } .controls h3 { margin-bottom: 15px; color: #fff; font-size: 18px; } .control-group { margin-bottom: 15px; } .control-group label { display: block; margin-bottom: 5px; font-size: 14px; color: #ccc; } .control-group input[type="range"] { width: 100%; height: 5px; background: #333; outline: none; border-radius: 5px; -webkit-appearance: none; } .control-group input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 15px; height: 15px; background: #4CAF50; border-radius: 50%; cursor: pointer; } .control-group input[type="color"] { width: 100%; height: 40px; border: none; border-radius: 5px; cursor: pointer; } .control-group button { width: 100%; padding: 10px; background: #4CAF50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; transition: background 0.3s; } .control-group button:hover { background: #45a049; } .control-group button.active { background: #ff4444; } .stats { position: absolute; top: 20px; right: 20px; background: rgba(20, 20, 20, 0.9); padding: 15px; border-radius: 10px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); font-size: 14px; color: #ccc; } .color-presets { display: flex; gap: 5px; margin-top: 10px; } .color-preset { width: 30px; height: 30px; border-radius: 50%; cursor: pointer; border: 2px solid transparent; transition: border-color 0.3s; } .color-preset:hover { border-color: #fff; } .mode-selector { display: flex; gap: 5px; margin-bottom: 15px; } .mode-btn { flex: 1; padding: 8px; background: #333; color: #fff; border: none; border-radius: 5px; cursor: pointer; font-size: 12px; transition: background 0.3s; } .mode-btn.active { background: #4CAF50; } </style> </head> <body> <canvas id="canvas"></canvas> <div class="controls"> <h3>Fluid Simulator</h3> <div class="mode-selector"> <button class="mode-btn active" data-mode="add">Добавить</button> <button class="mode-btn" data-mode="remove">Удалить</button> <button class="mode-btn" data-mode="force">Сила</button> </div> <div class="control-group"> <label>Цвет жидкости:</label> <input type="color" id="colorPicker" value="#ff4444"> <div class="color-presets"> <div class="color-preset" style="background: #ff4444" data-color="#ff4444"></div> <div class="color-preset" style="background: #44ff44" data-color="#44ff44"></div> <div class="color-preset" style="background: #4444ff" data-color="#4444ff"></div> <div class="color-preset" style="background: #ffff44" data-color="#ffff44"></div> <div class="color-preset" style="background: #ff44ff" data-color="#ff44ff"></div> <div class="color-preset" style="background: #44ffff" data-color="#44ffff"></div> </div> </div> <div class="control-group"> <label>Размер кисти: <span id="brushSizeValue">20</span></label> <input type="range" id="brushSize" min="5" max="100" value="20"> </div> <div class="control-group"> <label>Сила: <span id="forceValue">100</span></label> <input type="range" id="forceStrength" min="10" max="500" value="100"> </div> <div class="control-group"> <label>Вязкость: <span id="viscosityValue">0.01</span></label> <input type="range" id="viscosity" min="0.001" max="0.1" step="0.001" value="0.01"> </div> <div class="control-group"> <label>Диффузия: <span id="diffusionValue">0.0001</span></label> <input type="range" id="diffusion" min="0" max="0.001" step="0.00001" value="0.0001"> </div> <div class="control-group"> <button id="clearBtn">Очистить</button> </div> <div class="control-group"> <button id="pauseBtn">Пауза</button> </div> </div> <div class="stats"> <div>FPS: <span id="fps">0</span></div> <div>Частиц: <span id="particleCount">0</span></div> <div>Давление: <span id="pressure">0</span></div> </div> <script> class FluidSimulator { constructor(canvas) { this.canvas = canvas; this.ctx = canvas.getContext('2d'); this.width = window.innerWidth; this.height = window.innerHeight; this.canvas.width = this.width; this.canvas.height = this.height; this.N = 128; this.iter = 4; this.dt = 0.016; this.size = (this.N + 2) * (this.N + 2); this.s = new Float32Array(this.size); this.density = new Float32Array(this.size); this.Vx = new Float32Array(this.size); this.Vy = new Float32Array(this.size); this.Vx0 = new Float32Array(this.size); this.Vy0 = new Float32Array(this.size); this.colorR = new Float32Array(this.size); this.colorG = new Float32Array(this.size); this.colorB = new Float32Array(this.size); this.mouse = { x: 0, y: 0, down: false }; this.mode = 'add'; this.brushSize = 20; this.forceStrength = 100; this.currentColor = { r: 255, g: 68, b: 68 }; this.viscosity = 0.01; this.diffusion = 0.0001; this.isPaused = false; this.setupEventListeners(); this.animate(); } setupEventListeners() { this.canvas.addEventListener('mousedown', (e) => { this.mouse.down = true; this.updateMousePosition(e); }); this.canvas.addEventListener('mousemove', (e) => { this.updateMousePosition(e); }); this.canvas.addEventListener('mouseup', () => { this.mouse.down = false; }); this.canvas.addEventListener('touchstart', (e) => { e.preventDefault(); this.mouse.down = true; this.updateTouchPosition(e); }); this.canvas.addEventListener('touchmove', (e) => { e.preventDefault(); this.updateTouchPosition(e); }); this.canvas.addEventListener('touchend', (e) => { e.preventDefault(); this.mouse.down = false; }); window.addEventListener('resize', () => { this.width = window.innerWidth; this.height = window.innerHeight; this.canvas.width = this.width; this.canvas.height = this.height; }); // UI Controls document.getElementById('brushSize').addEventListener('input', (e) => { this.brushSize = parseInt(e.target.value); document.getElementById('brushSizeValue').textContent = this.brushSize; }); document.getElementById('forceStrength').addEventListener('input', (e) => { this.forceStrength = parseInt(e.target.value); document.getElementById('forceValue').textContent = this.forceStrength; }); document.getElementById('viscosity').addEventListener('input', (e) => { this.viscosity = parseFloat(e.target.value); document.getElementById('viscosityValue').textContent = this.viscosity; }); document.getElementById('diffusion').addEventListener('input', (e) => { this.diffusion = parseFloat(e.target.value); document.getElementById('diffusionValue').textContent = this.diffusion; }); document.getElementById('colorPicker').addEventListener('input', (e) => { const hex = e.target.value; this.currentColor = { r: parseInt(hex.substr(1, 2), 16), g: parseInt(hex.substr(3, 2), 16), b: parseInt(hex.substr(5, 2), 16) }; }); document.querySelectorAll('.color-preset').forEach(preset => { preset.addEventListener('click', (e) => { const color = e.target.dataset.color; document.getElementById('colorPicker').value = color; this.currentColor = { r: parseInt(color.substr(1, 2), 16), g: parseInt(color.substr(3, 2), 16), b: parseInt(color.substr(5, 2), 16) }; }); }); document.querySelectorAll('.mode-btn').forEach(btn => { btn.addEventListener('click', (e) => { document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active')); e.target.classList.add('active'); this.mode = e.target.dataset.mode; }); }); document.getElementById('clearBtn').addEventListener('click', () => { this.clear(); }); document.getElementById('pauseBtn').addEventListener('click', (e) => { this.isPaused = !this.isPaused; e.target.textContent = this.isPaused ? 'Продолжить' : 'Пауза'; }); } updateMousePosition(e) { const rect = this.canvas.getBoundingClientRect(); this.mouse.x = e.clientX - rect.left; this.mouse.y = e.clientY - rect.top; } updateTouchPosition(e) { const rect = this.canvas.getBoundingClientRect(); const touch = e.touches[0]; this.mouse.x = touch.clientX - rect.left; this.mouse.y = touch.clientY - rect.top; } IX(x, y) { return x + (this.N + 2) * y; } addDensity(x, y, amount, r, g, b) { const index = this.IX(x, y); this.density[index] += amount; this.colorR[index] += r * amount; this.colorG[index] += g * amount; this.colorB[index] += b * amount; } addVelocity(x, y, amountX, amountY) { const index = this.IX(x, y); this.Vx[index] += amountX; this.Vy[index] += amountY; } diffuse(b, x, x0, diff, dt) { const a = dt * diff * this.N * this.N; this.lin_solve(b, x, x0, a, 1 + 6 * a); } lin_solve(b, x, x0, a, c) { const cRecip = 1.0 / c; for (let k = 0; k < this.iter; k++) { for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { x[this.IX(i, j)] = (x0[this.IX(i, j)] + a * ( x[this.IX(i + 1, j)] + x[this.IX(i - 1, j)] + x[this.IX(i, j + 1)] + x[this.IX(i, j - 1)] )) * cRecip; } } this.set_bnd(b, x); } } project(velocX, velocY, p, div) { for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { div[this.IX(i, j)] = -0.5 * ( velocX[this.IX(i + 1, j)] - velocX[this.IX(i - 1, j)] + velocY[this.IX(i, j + 1)] - velocY[this.IX(i, j - 1)] ) / this.N; p[this.IX(i, j)] = 0; } } this.set_bnd(0, div); this.set_bnd(0, p); this.lin_solve(0, p, div, 1, 6); for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { velocX[this.IX(i, j)] -= 0.5 * (p[this.IX(i + 1, j)] - p[this.IX(i - 1, j)]) * this.N; velocY[this.IX(i, j)] -= 0.5 * (p[this.IX(i, j + 1)] - p[this.IX(i, j - 1)]) * this.N; } } this.set_bnd(1, velocX); this.set_bnd(2, velocY); } advect(b, d, d0, velocX, velocY, dt) { const dt0 = dt * this.N; for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { const x = i - dt0 * velocX[this.IX(i, j)]; const y = j - dt0 * velocY[this.IX(i, j)]; const x0 = Math.floor(x); const x1 = x0 + 1; const y0 = Math.floor(y); const y1 = y0 + 1; const s1 = x - x0; const s0 = 1 - s1; const t1 = y - y0; const t0 = 1 - t1; const x0c = Math.max(0, Math.min(this.N + 1, x0)); const x1c = Math.max(0, Math.min(this.N + 1, x1)); const y0c = Math.max(0, Math.min(this.N + 1, y0)); const y1c = Math.max(0, Math.min(this.N + 1, y1)); d[this.IX(i, j)] = s0 * (t0 * d0[this.IX(x0c, y0c)] + t1 * d0[this.IX(x0c, y1c)]) + s1 * (t0 * d0[this.IX(x1c, y0c)] + t1 * d0[this.IX(x1c, y1c)]); } } this.set_bnd(b, d); } set_bnd(b, x) { for (let i = 1; i <= this.N; i++) { x[this.IX(0, i)] = b === 1 ? -x[this.IX(1, i)] : x[this.IX(1, i)]; x[this.IX(this.N + 1, i)] = b === 1 ? -x[this.IX(this.N, i)] : x[this.IX(this.N, i)]; x[this.IX(i, 0)] = b === 2 ? -x[this.IX(i, 1)] : x[this.IX(i, 1)]; x[this.IX(i, this.N + 1)] = b === 2 ? -x[this.IX(i, this.N)] : x[this.IX(i, this.N)]; } x[this.IX(0, 0)] = 0.5 * (x[this.IX(1, 0)] + x[this.IX(0, 1)]); x[this.IX(0, this.N + 1)] = 0.5 * (x[this.IX(1, this.N + 1)] + x[this.IX(0, this.N)]); x[this.IX(this.N + 1, 0)] = 0.5 * (x[this.IX(this.N, 0)] + x[this.IX(this.N + 1, 1)]); x[this.IX(this.N + 1, this.N + 1)] = 0.5 * (x[this.IX(this.N, this.N + 1)] + x[this.IX(this.N + 1, this.N)]); } step() { this.diffuse(1, this.Vx0, this.Vx, this.viscosity, this.dt); this.diffuse(2, this.Vy0, this.Vy, this.viscosity, this.dt); this.project(this.Vx0, this.Vy0, this.Vx, this.Vy); this.advect(1, this.Vx, this.Vx0, this.Vx0, this.Vy0, this.dt); this.advect(2, this.Vy, this.Vy0, this.Vx0, this.Vy0, this.dt); this.project(this.Vx, this.Vy, this.Vx0, this.Vy0); this.diffuse(0, this.s, this.density, this.diffusion, this.dt); this.advect(0, this.density, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorR, this.diffusion, this.dt); this.advect(0, this.colorR, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorG, this.diffusion, this.dt); this.advect(0, this.colorG, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorB, this.diffusion, this.dt); this.advect(0, this.colorB, this.s, this.Vx, this.Vy, this.dt); // Normalize colors for (let i = 0; i < this.size; i++) { if (this.density[i] > 0) { this.colorR[i] = Math.max(0, Math.min(255, this.colorR[i])); this.colorG[i] = Math.max(0, Math.min(255, this.colorG[i])); this.colorB[i] = Math.max(0, Math.min(255, this.colorB[i])); } else { this.colorR[i] = 0; this.colorG[i] = 0; this.colorB[i] = 0; } } } render() { const imageData = this.ctx.createImageData(this.width, this.height); const data = imageData.data; const cellWidth = this.width / this.N; const cellHeight = this.height / this.N; for (let j = 0; j < this.N; j++) { for (let i = 0; i < this.N; i++) { const index = this.IX(i, j); const density = this.density[index]; if (density > 0) { const r = Math.floor(this.colorR[index] / density); const g = Math.floor(this.colorG[index] / density); const b = Math.floor(this.colorB[index] / density); const a = Math.min(255, Math.floor(density * 255)); const x = Math.floor(i * cellWidth); const y = Math.floor(j * cellHeight); const xEnd = Math.floor((i + 1) * cellWidth); const yEnd = Math.floor((j + 1) * cellHeight); for (let py = y; py < yEnd; py++) { for (let px = x; px < xEnd; px++) { const pixelIndex = (py * this.width + px) * 4; data[pixelIndex] = r; data[pixelIndex + 1] = g; data[pixelIndex + 2] = b; data[pixelIndex + 3] = a; } } } } } this.ctx.putImageData(imageData, 0, 0); } handleInput() { if (!this.mouse.down) return; const x = Math.floor((this.mouse.x / this.width) * this.N); const y = Math.floor((this.mouse.y / this.height) * this.N); if (x < 1 || x > this.N || y < 1 || y > this.N) return; const radius = Math.floor(this.brushSize / Math.min(this.width, this.height) * this.N); for (let j = -radius; j <= radius; j++) { for (let i = -radius; i <= radius; i++) { const distance = Math.sqrt(i * i + j * j); if (distance <= radius) { const px = x + i; const py = y + j; if (px >= 1 && px <= this.N && py >= 1 && py <= this.N) { const index = this.IX(px, py); const strength = 1 - distance / radius; switch (this.mode) { case 'add': this.addDensity(px, py, strength * 100, this.currentColor.r, this.currentColor.g, this.currentColor.b); break; case 'remove': this.density[index] = Math.max(0, this.density[index] - strength * 100); this.colorR[index] = Math.max(0, this.colorR[index] - this.currentColor.r * strength * 100); this.colorG[index] = Math.max(0, this.colorG[index] - this.currentColor.g * strength * 100); this.colorB[index] = Math.max(0, this.colorB[index] - this.currentColor.b * strength * 100); break; case 'force': const angle = Math.atan2(j, i); this.addVelocity(px, py, Math.cos(angle) * strength * this.forceStrength, Math.sin(angle) * strength * this.forceStrength); break; } } } } } } addDensity(x, y, amount, r, g, b) { this.addDensity(x, y, amount, r, g, b); } clear() { this.density.fill(0); this.Vx.fill(0); this.Vy.fill(0); this.Vx0.fill(0); this.Vy0.fill(0); this.colorR.fill(0); this.colorG.fill(0); this.colorB.fill(0); } animate() { if (!this.isPaused) { this.handleInput(); this.step(); this.render(); } requestAnimationFrame(() => this.animate()); } } // Initialize const canvas = document.getElementById('canvas'); const simulator = new FluidSimulator(canvas); // FPS Counter let lastTime = performance.now(); let frameCount = 0; function updateStats() { frameCount++; const currentTime = performance.now(); if (currentTime - lastTime >= 1000) { document.getElementById('fps').textContent = frameCount; document.getElementById('particleCount').textContent = simulator.density.reduce((sum, val) => sum + (val > 0 ? 1 : 0), 0); const avgPressure = simulator.density.reduce((sum, val) => sum + val, 0) / simulator.size; document.getElementById('pressure').textContent = avgPressure.toFixed(2); frameCount = 0; lastTime = currentTime; } requestAnimationFrame(updateStats); } updateStats(); </script> </body> </html> - User
index.html:602 Uncaught RangeError: Maximum call stack size exceeded at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22) at FluidSimulator.addDensity (index.html:602:22)
- Assistant
Ошибка возникает из-за бесконечной рекурсии в методе
addDensity. Давайте исправим это, а также улучшим производительность и добавим дополнительные оптимизации:<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Advanced Fluid Simulator</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: 'Arial', sans-serif; background: #0a0a0a; color: #fff; overflow: hidden; } #canvas { display: block; cursor: crosshair; background: radial-gradient(circle at center, #0a0a0a 0%, #000 100%); } .controls { position: absolute; top: 20px; left: 20px; background: rgba(20, 20, 20, 0.9); padding: 20px; border-radius: 10px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); max-width: 300px; max-height: 90vh; overflow-y: auto; } .controls h3 { margin-bottom: 15px; color: #fff; font-size: 18px; } .control-group { margin-bottom: 15px; } .control-group label { display: block; margin-bottom: 5px; font-size: 14px; color: #ccc; } .control-group input[type="range"] { width: 100%; height: 5px; background: #333; outline: none; border-radius: 5px; -webkit-appearance: none; } .control-group input[type="range"]::-webkit-slider-thumb { -webkit-appearance: none; width: 15px; height: 15px; background: #4CAF50; border-radius: 50%; cursor: pointer; } .control-group input[type="color"] { width: 100%; height: 40px; border: none; border-radius: 5px; cursor: pointer; } .control-group button { width: 100%; padding: 10px; background: #4CAF50; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; transition: background 0.3s; } .control-group button:hover { background: #45a049; } .control-group button.active { background: #ff4444; } .stats { position: absolute; top: 20px; right: 20px; background: rgba(20, 20, 20, 0.9); padding: 15px; border-radius: 10px; backdrop-filter: blur(10px); border: 1px solid rgba(255, 255, 255, 0.1); font-size: 14px; color: #ccc; } .color-presets { display: flex; gap: 5px; margin-top: 10px; flex-wrap: wrap; } .color-preset { width: 30px; height: 30px; border-radius: 50%; cursor: pointer; border: 2px solid transparent; transition: border-color 0.3s; } .color-preset:hover { border-color: #fff; } .mode-selector { display: flex; gap: 5px; margin-bottom: 15px; } .mode-btn { flex: 1; padding: 8px; background: #333; color: #fff; border: none; border-radius: 5px; cursor: pointer; font-size: 12px; transition: background 0.3s; } .mode-btn.active { background: #4CAF50; } .loading { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 24px; color: #4CAF50; } </style> </head> <body> <canvas id="canvas"></canvas> <div class="loading" id="loading">Загрузка...</div> <div class="controls" style="display: none;" id="controls"> <h3>Fluid Simulator</h3> <div class="mode-selector"> <button class="mode-btn active" data-mode="add">Добавить</button> <button class="mode-btn" data-mode="remove">Удалить</button> <button class="mode-btn" data-mode="force">Сила</button> </div> <div class="control-group"> <label>Цвет жидкости:</label> <input type="color" id="colorPicker" value="#ff4444"> <div class="color-presets"> <div class="color-preset" style="background: #ff4444" data-color="#ff4444"></div> <div class="color-preset" style="background: #44ff44" data-color="#44ff44"></div> <div class="color-preset" style="background: #4444ff" data-color="#4444ff"></div> <div class="color-preset" style="background: #ffff44" data-color="#ffff44"></div> <div class="color-preset" style="background: #ff44ff" data-color="#ff44ff"></div> <div class="color-preset" style="background: #44ffff" data-color="#44ffff"></div> <div class="color-preset" style="background: #ffffff" data-color="#ffffff"></div> <div class="color-preset" style="background: #ff8800" data-color="#ff8800"></div> </div> </div> <div class="control-group"> <label>Размер кисти: <span id="brushSizeValue">20</span></label> <input type="range" id="brushSize" min="5" max="100" value="20"> </div> <div class="control-group"> <label>Сила: <span id="forceValue">100</span></label> <input type="range" id="forceStrength" min="10" max="500" value="100"> </div> <div class="control-group"> <label>Вязкость: <span id="viscosityValue">0.01</span></label> <input type="range" id="viscosity" min="0.001" max="0.1" step="0.001" value="0.01"> </div> <div class="control-group"> <label>Диффузия: <span id="diffusionValue">0.0001</span></label> <input type="range" id="diffusion" min="0" max="0.001" step="0.00001" value="0.0001"> </div> <div class="control-group"> <label>Разрешение:</label> <select id="resolution"> <option value="64">64x64 (Высокая производительность)</option> <option value="128" selected>128x128 (Среднее)</option> <option value="256">256x256 (Высокое качество)</option> </select> </div> <div class="control-group"> <button id="clearBtn">Очистить</button> </div> <div class="control-group"> <button id="pauseBtn">Пауза</button> </div> <div class="control-group"> <button id="presetBtn">Пресеты</button> </div> </div> <div class="stats"> <div>FPS: <span id="fps">0</span></div> <div>Частиц: <span id="particleCount">0</span></div> <div>Давление: <span id="pressure">0</span></div> </div> <script> class FluidSimulator { constructor(canvas) { this.canvas = canvas; this.ctx = canvas.getContext('2d'); this.width = window.innerWidth; this.height = window.innerHeight; this.canvas.width = this.width; this.canvas.height = this.height; this.N = 128; this.iter = 4; this.dt = 0.016; this.mouse = { x: 0, y: 0, down: false, prevX: 0, prevY: 0 }; this.mode = 'add'; this.brushSize = 20; this.forceStrength = 100; this.currentColor = { r: 255, g: 68, b: 68 }; this.viscosity = 0.01; this.diffusion = 0.0001; this.isPaused = false; this.frameCount = 0; this.lastTime = performance.now(); this.initializeArrays(); this.setupEventListeners(); // Скрыть загрузку и показать контролы setTimeout(() => { document.getElementById('loading').style.display = 'none'; document.getElementById('controls').style.display = 'block'; }, 100); this.animate(); } initializeArrays() { this.size = (this.N + 2) * (this.N + 2); this.s = new Float32Array(this.size); this.density = new Float32Array(this.size); this.Vx = new Float32Array(this.size); this.Vy = new Float32Array(this.size); this.Vx0 = new Float32Array(this.size); this.Vy0 = new Float32Array(this.size); this.colorR = new Float32Array(this.size); this.colorG = new Float32Array(this.size); this.colorB = new Float32Array(this.size); } setupEventListeners() { this.canvas.addEventListener('mousedown', (e) => { this.mouse.down = true; this.updateMousePosition(e); this.mouse.prevX = this.mouse.x; this.mouse.prevY = this.mouse.y; }); this.canvas.addEventListener('mousemove', (e) => { this.updateMousePosition(e); }); this.canvas.addEventListener('mouseup', () => { this.mouse.down = false; }); this.canvas.addEventListener('mouseleave', () => { this.mouse.down = false; }); this.canvas.addEventListener('touchstart', (e) => { e.preventDefault(); this.mouse.down = true; this.updateTouchPosition(e); this.mouse.prevX = this.mouse.x; this.mouse.prevY = this.mouse.y; }); this.canvas.addEventListener('touchmove', (e) => { e.preventDefault(); this.updateTouchPosition(e); }); this.canvas.addEventListener('touchend', (e) => { e.preventDefault(); this.mouse.down = false; }); window.addEventListener('resize', () => { this.width = window.innerWidth; this.height = window.innerHeight; this.canvas.width = this.width; this.canvas.height = this.height; }); // UI Controls document.getElementById('brushSize').addEventListener('input', (e) => { this.brushSize = parseInt(e.target.value); document.getElementById('brushSizeValue').textContent = this.brushSize; }); document.getElementById('forceStrength').addEventListener('input', (e) => { this.forceStrength = parseInt(e.target.value); document.getElementById('forceValue').textContent = this.forceStrength; }); document.getElementById('viscosity').addEventListener('input', (e) => { this.viscosity = parseFloat(e.target.value); document.getElementById('viscosityValue').textContent = this.viscosity; }); document.getElementById('diffusion').addEventListener('input', (e) => { this.diffusion = parseFloat(e.target.value); document.getElementById('diffusionValue').textContent = this.diffusion; }); document.getElementById('colorPicker').addEventListener('input', (e) => { const hex = e.target.value; this.currentColor = { r: parseInt(hex.substr(1, 2), 16), g: parseInt(hex.substr(3, 2), 16), b: parseInt(hex.substr(5, 2), 16) }; }); document.getElementById('resolution').addEventListener('change', (e) => { this.N = parseInt(e.target.value); this.initializeArrays(); }); document.querySelectorAll('.color-preset').forEach(preset => { preset.addEventListener('click', (e) => { const color = e.target.dataset.color; document.getElementById('colorPicker').value = color; this.currentColor = { r: parseInt(color.substr(1, 2), 16), g: parseInt(color.substr(3, 2), 16), b: parseInt(color.substr(5, 2), 16) }; }); }); document.querySelectorAll('.mode-btn').forEach(btn => { btn.addEventListener('click', (e) => { document.querySelectorAll('.mode-btn').forEach(b => b.classList.remove('active')); e.target.classList.add('active'); this.mode = e.target.dataset.mode; }); }); document.getElementById('clearBtn').addEventListener('click', () => { this.clear(); }); document.getElementById('pauseBtn').addEventListener('click', (e) => { this.isPaused = !this.isPaused; e.target.textContent = this.isPaused ? 'Продолжить' : 'Пауза'; }); document.getElementById('presetBtn').addEventListener('click', () => { this.loadPreset(); }); } updateMousePosition(e) { const rect = this.canvas.getBoundingClientRect(); this.mouse.x = e.clientX - rect.left; this.mouse.y = e.clientY - rect.top; } updateTouchPosition(e) { const rect = this.canvas.getBoundingClientRect(); const touch = e.touches[0]; this.mouse.x = touch.clientX - rect.left; this.mouse.y = touch.clientY - rect.top; } IX(x, y) { x = Math.max(0, Math.min(this.N + 1, x)); y = Math.max(0, Math.min(this.N + 1, y)); return x + (this.N + 2) * y; } addDensityAt(x, y, amount, r, g, b) { const index = this.IX(x, y); this.density[index] += amount; this.colorR[index] += r * amount; this.colorG[index] += g * amount; this.colorB[index] += b * amount; } addVelocityAt(x, y, amountX, amountY) { const index = this.IX(x, y); this.Vx[index] += amountX; this.Vy[index] += amountY; } diffuse(b, x, x0, diff, dt) { const a = dt * diff * this.N * this.N; this.lin_solve(b, x, x0, a, 1 + 4 * a); } lin_solve(b, x, x0, a, c) { const cRecip = 1.0 / c; for (let k = 0; k < this.iter; k++) { for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { const idx = this.IX(i, j); x[idx] = (x0[idx] + a * ( x[this.IX(i + 1, j)] + x[this.IX(i - 1, j)] + x[this.IX(i, j + 1)] + x[this.IX(i, j - 1)] )) * cRecip; } } this.set_bnd(b, x); } } project(velocX, velocY, p, div) { for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { const idx = this.IX(i, j); div[idx] = -0.5 * ( velocX[this.IX(i + 1, j)] - velocX[this.IX(i - 1, j)] + velocY[this.IX(i, j + 1)] - velocY[this.IX(i, j - 1)] ) / this.N; p[idx] = 0; } } this.set_bnd(0, div); this.set_bnd(0, p); this.lin_solve(0, p, div, 1, 4); for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { const idx = this.IX(i, j); velocX[idx] -= 0.5 * (p[this.IX(i + 1, j)] - p[this.IX(i - 1, j)]) * this.N; velocY[idx] -= 0.5 * (p[this.IX(i, j + 1)] - p[this.IX(i, j - 1)]) * this.N; } } this.set_bnd(1, velocX); this.set_bnd(2, velocY); } advect(b, d, d0, velocX, velocY, dt) { const dt0 = dt * this.N; for (let j = 1; j <= this.N; j++) { for (let i = 1; i <= this.N; i++) { const idx = this.IX(i, j); const x = i - dt0 * velocX[idx]; const y = j - dt0 * velocY[idx]; const x0 = Math.floor(x); const x1 = x0 + 1; const y0 = Math.floor(y); const y1 = y0 + 1; const s1 = x - x0; const s0 = 1 - s1; const t1 = y - y0; const t0 = 1 - t1; d[idx] = s0 * (t0 * d0[this.IX(x0, y0)] + t1 * d0[this.IX(x0, y1)]) + s1 * (t0 * d0[this.IX(x1, y0)] + t1 * d0[this.IX(x1, y1)]); } } this.set_bnd(b, d); } set_bnd(b, x) { for (let i = 1; i <= this.N; i++) { x[this.IX(0, i)] = b === 1 ? -x[this.IX(1, i)] : x[this.IX(1, i)]; x[this.IX(this.N + 1, i)] = b === 1 ? -x[this.IX(this.N, i)] : x[this.IX(this.N, i)]; x[this.IX(i, 0)] = b === 2 ? -x[this.IX(i, 1)] : x[this.IX(i, 1)]; x[this.IX(i, this.N + 1)] = b === 2 ? -x[this.IX(i, this.N)] : x[this.IX(i, this.N)]; } x[this.IX(0, 0)] = 0.5 * (x[this.IX(1, 0)] + x[this.IX(0, 1)]); x[this.IX(0, this.N + 1)] = 0.5 * (x[this.IX(1, this.N + 1)] + x[this.IX(0, this.N)]); x[this.IX(this.N + 1, 0)] = 0.5 * (x[this.IX(this.N, 0)] + x[this.IX(this.N + 1, 1)]); x[this.IX(this.N + 1, this.N + 1)] = 0.5 * (x[this.IX(this.N, this.N + 1)] + x[this.IX(this.N + 1, this.N)]); } step() { this.diffuse(1, this.Vx0, this.Vx, this.viscosity, this.dt); this.diffuse(2, this.Vy0, this.Vy, this.viscosity, this.dt); this.project(this.Vx0, this.Vy0, this.Vx, this.Vy); this.advect(1, this.Vx, this.Vx0, this.Vx0, this.Vy0, this.dt); this.advect(2, this.Vy, this.Vy0, this.Vx0, this.Vy0, this.dt); this.project(this.Vx, this.Vy, this.Vx0, this.Vy0); this.diffuse(0, this.s, this.density, this.diffusion, this.dt); this.advect(0, this.density, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorR, this.diffusion, this.dt); this.advect(0, this.colorR, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorG, this.diffusion, this.dt); this.advect(0, this.colorG, this.s, this.Vx, this.Vy, this.dt); this.diffuse(0, this.s, this.colorB, this.diffusion, this.dt); this.advect(0, this.colorB, this.s, this.Vx, this.Vy, this.dt); // Fade effect const fadeRate = 0.999; for (let i = 0; i < this.size; i++) { this.density[i] *= fadeRate; this.colorR[i] *= fadeRate; this.colorG[i] *= fadeRate; this.colorB[i] *= fadeRate; } } render() { const imageData = this.ctx.createImageData(this.width, this.height); const data = imageData.data; const cellWidth = this.width / this.N; const cellHeight = this.height / this.N; // Используем буферизацию для улучшения производительности const buffer = new Uint8ClampedArray(this.width * this.height * 4); for (let j = 0; j < this.N; j++) { for (let i = 0; i < this.N; i++) { const index = this.IX(i, j); const density = this.density[index]; if (density > 0.01) { const totalDensity = Math.max(density, 0.01); const r = Math.floor(this.colorR[index] / totalDensity); const g = Math.floor(this.colorG[index] / totalDensity); const b = Math.floor(this.colorB[index] / totalDensity); const a = Math.min(255, Math.floor(density * 2.55)); const x = Math.floor(i * cellWidth); const y = Math.floor(j * cellHeight); const xEnd = Math.min(this.width, Math.floor((i + 1) * cellWidth)); const yEnd = Math.min(this.height, Math.floor((j + 1) * cellHeight)); for (let py = y; py < yEnd; py++) { for (let px = x; px < xEnd; px++) { const pixelIndex = (py * this.width + px) * 4; buffer[pixelIndex] = r; buffer[pixelIndex + 1] = g; buffer[pixelIndex + 2] = b; buffer[pixelIndex + 3] = a; } } } } } imageData.data.set(buffer); this.ctx.putImageData(imageData, 0, 0); } handleInput() { if (!this.mouse.down) return; const x = Math.floor((this.mouse.x / this.width) * this.N); const y = Math.floor((this.mouse.y / this.height) * this.N); if (x < 1 || x > this.N || y < 1 || y > this.N) return; const radius = Math.floor(this.brushSize / Math.min(this.width, this.height) * this.N); // Оптимизация: используем квадрат радиуса для избежания sqrt const radiusSq = radius * radius; for (let j = -radius; j <= radius; j++) { for (let i = -radius; i <= radius; i++) { const distanceSq = i * i + j * j; if (distanceSq <= radiusSq) { const px = x + i; const py = y + j; if (px >= 1 && px <= this.N && py >= 1 && py <= this.N) { const distance = Math.sqrt(distanceSq); const strength = 1 - distance / radius; switch (this.mode) { case 'add': this.addDensityAt(px, py, strength * 50, this.currentColor.r, this.currentColor.g, this.currentColor.b); break; case 'remove': const index = this.IX(px, py); const removeAmount = strength * 100; this.density[index] = Math.max(0, this.density[index] - removeAmount); this.colorR[index] = Math.max(0, this.colorR[index] - this.currentColor.r * strength); this.colorG[index] = Math.max(0, this.colorG[index] - this.currentColor.g * strength); this.colorB[index] = Math.max(0, this.colorB[index] - this.currentColor.b * strength); break; case 'force': const dx = this.mouse.x - this.mouse.prevX; const dy = this.mouse.y - this.mouse.prevY; const angle = Math.atan2(dy, dx); this.addVelocityAt(px, py, Math.cos(angle) * strength * this.forceStrength * 0.1, Math.sin(angle) * strength * this.forceStrength * 0.1); break; } } } } } this.mouse.prevX = this.mouse.x; this.mouse.prevY = this.mouse.y; } clear() { this.density.fill(0); this.Vx.fill(0); this.Vy.fill(0); this.Vx0.fill(0); this.Vy0.fill(0); this.colorR.fill(0); this.colorG.fill(0); this.colorB.fill(0); } loadPreset() { this.clear(); // Создаем красивый вихрь const centerX = Math.floor(this.N / 2); const centerY = Math.floor(this.N / 2); const radius = 20; for (let j = -radius; j <= radius; j++) { for (let i = -radius; i <= radius; i++) { const distance = Math.sqrt(i * i + j * j); if (distance <= radius) { const x = centerX + i; const y = centerY + j; if (x >= 1 && x <= this.N && y >= 1 && y <= this.N) { const angle = Math.atan2(j, i); const strength = 1 - distance / radius; this.addDensityAt(x, y, strength * 100, 128 + Math.sin(angle) * 127, 128 + Math.cos(angle) * 127, 255); this.addVelocityAt(x, y, -Math.sin(angle) * 50 * strength, Math.cos(angle) * 50 * strength); } } } } } animate() { if (!this.isPaused) { this.handleInput(); this.step(); this.render(); } // Обновление статистики this.frameCount++; const currentTime = performance.now(); if (currentTime - this.lastTime >= 1000) { document.getElementById('fps').textContent = this.frameCount; document.getElementById('particleCount').textContent = this.density.reduce((sum, val) => sum + (val > 0.1 ? 1 : 0), 0); const avgPressure = this.density.reduce((sum, val) => sum + val, 0) / this.size; document.getElementById('pressure').textContent = avgPressure.toFixed(2); this.frameCount = 0; this.lastTime = currentTime; } requestAnimationFrame(() => this.animate()); } } // Initialize const canvas = document.getElementById('canvas'); const simulator = new FluidSimulator(canvas); </script> </body> </html>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.