Certainly! Below is a rewritten version of your 2D MLS-MPM (Material Point Method) simulation using Eigen for linear algebra operations and OpenGL (with GLFW for window/context creation and GLAD for OpenGL function loading) for rendering. This version replaces Taichi's functionalities with Eigen and OpenGL equivalents to handle simulation logic and visualization.
Overview
-
Dependencies:
- Eigen: A C++ template library for linear algebra.
- GLFW: A library for creating windows and OpenGL contexts.
- GLAD: An extension loader for OpenGL.
- GLM (optional): If you prefer a math library similar to Eigen for OpenGL transformations (though in this example, Eigen is used).
-
Key Components:
- Linear Algebra with Eigen: Replaces Taichi's vector and matrix operations.
- Rendering with OpenGL: Replaces Taichi's GUI and canvas for visualization.
- Particle Management: Using Eigen types for particle attributes.
- Simulation Loop: Combines simulation advancement and rendering.
-
Setup:
- Ensure you have the necessary libraries installed.
- Configure your build system (e.g., CMake) to include Eigen, GLFW, and GLAD.
Step-by-Step Implementation
1. Setting Up Dependencies
Before diving into the code, ensure you have the following libraries installed:
- Eigen: Download Eigen and include it in your project.
- GLFW: Install via package manager or from GLFW website.
- GLAD: Generate the loader from GLAD website for OpenGL version 3.3 or higher and include it in your project.
2. Code Implementation
Below is the complete C++ code implementing the simulation with Eigen and OpenGL:
// main.cpp
#include <Eigen/Dense>
#include <GLFW/glfw3.h>
#include <glad/glad.h>
#include <vector>
#include <iostream>
#include <cmath>
#include <cstdlib>
// Alias Eigen types for convenience
using Vec2 = Eigen::Vector2f;
using Vec3 = Eigen::Vector3f;
using Mat2 = Eigen::Matrix2f;
// Constants
const int n = 80; // Grid resolution (cells)
const int window_size = 800; // Window size in pixels
const float dt = 1e-4f; // Time step
const float frame_dt = 1e-3f; // Frame duration
const float dx = 1.0f / n; // Grid cell size
const float inv_dx = 1.0f / dx;
const float particle_mass = 1.0f;
const float vol = 1.0f;
const float hardening = 10.0f;
const float E = 1e4f;
const float nu = 0.2f;
const float mu_0 = E / (2.0f * (1.0f + nu));
const float lambda_0 = E * nu / ((1.0f + nu) * (1.0f - 2.0f * nu));
bool plastic = true;
// Particle structure
struct Particle {
Vec2 x; // Position
Vec2 v; // Velocity
Mat2 F; // Deformation gradient
Mat2 C; // APIC affine velocity field
float Jp; // Plasticity factor
int c; // Color
Particle(const Vec2& x_, int c_, const Vec2& v_ = Vec2::Zero())
: x(x_), v(v_), F(Mat2::Identity()), C(Mat2::Zero()), Jp(1.0f), c(c_) {}
};
// Grid node structure: velocity (Vec2) and mass (float)
struct GridNode {
Vec2 velocity;
float mass;
GridNode() : velocity(Vec2::Zero()), mass(0.0f) {}
};
// Global variables
std::vector<Particle> particles;
std::vector<std::vector<GridNode>> grid(n + 1, std::vector<GridNode>(n + 1));
// Utility functions
// Clamp function
template <typename T>
T clamp(const T& val, const T& min_val, const T& max_val) {
return std::max(min_val, std::min(val, max_val));
}
// Polar decomposition for 2x2 matrix
void polar_decomp(const Mat2& F, Mat2& R, Mat2& S) {
Eigen::JacobiSVD<Mat2> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);
R = svd.matrixU() * svd.matrixV().transpose();
S = svd.matrixV() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();
}
// SVD for 2x2 matrix
void svd_decompose(const Mat2& F, Mat2& U, Eigen::Vector2f& S_values, Mat2& V) {
Eigen::JacobiSVD<Mat2> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);
U = svd.matrixU();
S_values = svd.singularValues();
V = svd.matrixV();
}
// Add object function: seeds particles with position and color
void add_object(const Vec2& center, int c, int num_particles = 500) {
for (int i = 0; i < num_particles; ++i) {
// Random positions within a small square around the center
float rand_x = ((static_cast<float>(rand()) / RAND_MAX) * 2.0f - 1.0f) * 0.08f;
float rand_y = ((static_cast<float>(rand()) / RAND_MAX) * 2.0f - 1.0f) * 0.08f;
particles.emplace_back(center + Vec2(rand_x, rand_y), c);
}
}
// Advance simulation by one time step
void advance_simulation(float dt_sim) {
// Reset grid
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
grid[i][j].velocity.setZero();
grid[i][j].mass = 0.0f;
}
}
// Particle to Grid (P2G)
for (auto& p : particles) {
// Base cell
Vec2 base_coord_f = p.x * inv_dx - Vec2(0.5f, 0.5f);
Eigen::Vector2i base_coord = base_coord_f.cast<int>();
Vec2 fx = p.x * inv_dx - base_coord.cast<float>();
// Quadratic B-spline weights
float w0 = 0.5f * (1.5f - fx.x()) * (1.5f - fx.y());
float w1 = (0.75f - (fx.array() - 1.0f).square()).prod();
float w2 = 0.5f * (fx.array() - 0.5f).square().prod();
// Compute stress
float e = std::exp(hardening * (1.0f - p.Jp));
float mu = mu_0 * e;
float lambda_ = lambda_0 * e;
float J = p.F.determinant();
Mat2 R, S;
polar_decomp(p.F, R, S);
Mat2 stress =
-4.0f * inv_dx * inv_dx * dt_sim * vol *
(2.0f * mu * (p.F - R) + lambda_ * (J - 1.0f) * J * Mat2::Identity());
Mat2 affine = stress + p.C * p.mass;
// Scatter to grid
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int gi = base_coord.x() + i;
int gj = base_coord.y() + j;
if (gi < 0 || gi > n || gj < 0 || gj > n) continue;
Vec2 dpos = Vec2(i, j) - fx;
Vec2 momentum = p.v * p.mass;
Vec2 grid_v_part = (affine * dpos);
float weight = 0.0f;
switch (i) {
case 0: weight += 0.5f * std::pow(1.5f - fx.x(), 2); break;
case 1: weight += 0.75f - std::pow(fx.x() - 1.0f, 2); break;
case 2: weight += 0.5f * std::pow(fx.x() - 0.5f, 2); break;
}
float wj = 0.0f;
switch (j) {
case 0: wj += 0.5f * std::pow(1.5f - fx.y(), 2); break;
case 1: wj += 0.75f - std::pow(fx.y() - 1.0f, 2); break;
case 2: wj += 0.5f * std::pow(fx.y() - 0.5f, 2); break;
}
float w = weight * wj;
grid[gi][gj].velocity += w * (momentum + grid_v_part);
grid[gi][gj].mass += w * particle_mass;
}
}
}
// Grid operations: apply gravity and boundary conditions
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= n; ++j) {
auto& g = grid[i][j];
if (g.mass > 0.0f) {
// Normalize velocity by mass
g.velocity /= g.mass;
// Apply gravity
g.velocity += Vec2(0.0f, -200.0f * dt_sim);
// Boundary conditions
float boundary = 0.05f;
float x = static_cast<float>(i) / n;
float y = static_cast<float>(j) / n;
if (x < boundary || x > 1.0f - boundary || y > 1.0f - boundary) {
g.velocity.setZero();
}
if (y < boundary) {
g.velocity.y() = std::max(0.0f, g.velocity.y());
}
}
}
}
// Grid to Particle (G2P)
for (auto& p : particles) {
// Base cell
Vec2 base_coord_f = p.x * inv_dx - Vec2(0.5f, 0.5f);
Eigen::Vector2i base_coord = base_coord_f.cast<int>();
Vec2 fx = p.x * inv_dx - base_coord.cast<float>();
// Quadratic B-spline weights
float w0 = 0.5f * (1.5f - fx.x()) * (1.5f - fx.y());
float w1 = (0.75f - (fx.array() - 1.0f).square()).prod();
float w2 = 0.5f * (fx.array() - 0.5f).square().prod();
// Reset for accumulation
p.v.setZero();
p.C.setZero();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
int gi = base_coord.x() + i;
int gj = base_coord.y() + j;
if (gi < 0 || gi > n || gj < 0 || gj > n) continue;
Vec2 dpos = Vec2(i, j) - fx;
auto& g = grid[gi][gj];
if (g.mass <= 0.0f) continue;
// Weight
float w = 0.0f;
switch (i) {
case 0: w += 0.5f * std::pow(1.5f - fx.x(), 2); break;
case 1: w += 0.75f - std::pow(fx.x() - 1.0f, 2); break;
case 2: w += 0.5f * std::pow(fx.x() - 0.5f, 2); break;
}
float wj = 0.0f;
switch (j) {
case 0: wj += 0.5f * std::pow(1.5f - fx.y(), 2); break;
case 1: wj += 0.75f - std::pow(fx.y() - 1.0f, 2); break;
case 2: wj += 0.5f * std::pow(fx.y() - 0.5f, 2); break;
}
w *= wj;
Vec2 grid_v = g.velocity;
p.v += w * grid_v;
p.C += 4.0f * inv_dx * w * grid_v * dpos.transpose();
}
}
// Advection
p.x += dt_sim * p.v;
// Update deformation gradient
Mat2 F = (Mat2::Identity() + dt_sim * p.C) * p.F;
// Plasticity (SVD-based)
Mat2 U, V;
Eigen::Vector2f S_values;
svd_decompose(F, U, S_values, V);
// Clamp singular values for plasticity
for (int i = 0; i < (plastic ? 2 : 0); ++i) {
S_values[i] = clamp(S_values[i], 1.0f - 2.5e-2f, 1.0f + 7.5e-3f);
}
// Reconstruct F
F = U * S_values.asDiagonal() * V.transpose();
// Update plasticity factor
float oldJ = F.determinant();
float Jp_new = clamp(p.Jp * oldJ / F.determinant(), 0.6f, 20.0f);
p.Jp = Jp_new;
p.F = F;
}
}
// OpenGL Utility Functions
// Shader sources
const char* vertexShaderSource = R"(
#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
out vec3 ourColor;
uniform mat4 projection;
void main()
{
gl_PointSize = 4.0;
gl_Position = projection * vec4(aPos, 0.0, 1.0);
ourColor = aColor;
}
)";
const char* fragmentShaderSource = R"(
#version 330 core
in vec3 ourColor;
out vec4 FragColor;
void main()
{
// Simple circular point
float dist = length(gl_PointCoord - vec2(0.5));
if (dist > 0.5)
discard;
FragColor = vec4(ourColor, 1.0);
}
)";
// Compile shader and check for errors
GLuint compileShader(GLenum type, const char* source) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, nullptr);
glCompileShader(shader);
// Check
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
GLint logLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logLength);
std::vector<char> infoLog(logLength);
glGetShaderInfoLog(shader, logLength, nullptr, infoLog.data());
std::cerr << "ERROR::SHADER_COMPILATION_ERROR\n" << infoLog.data() << std::endl;
}
return shader;
}
// Create shader program
GLuint createShaderProgram() {
GLuint vertexShader = compileShader(GL_VERTEX_SHADER, vertexShaderSource);
GLuint fragmentShader = compileShader(GL_FRAGMENT_SHADER, fragmentShaderSource);
// Link shaders
GLuint program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
// Check
GLint success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if(!success){
GLint logLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
std::vector<char> infoLog(logLength);
glGetProgramInfoLog(program, logLength, nullptr, infoLog.data());
std::cerr << "ERROR::PROGRAM_LINKING_ERROR\n" << infoLog.data() << std::endl;
}
// Cleanup
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return program;
}
int main() {
// Initialize GLFW
if (!glfwInit()) {
std::cerr << "Failed to initialize GLFW\n";
return -1;
}
// Configure GLFW: OpenGL version 3.3 Core
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create Window
GLFWwindow* window = glfwCreateWindow(window_size, window_size, "Real-time 2D MLS-MPM", nullptr, nullptr);
if (!window) {
std::cerr << "Failed to create GLFW window\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLAD
if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) {
std::cerr << "Failed to initialize GLAD\n";
return -1;
}
// Set viewport
glViewport(0, 0, window_size, window_size);
// Compile and link shaders
GLuint shaderProgram = createShaderProgram();
// Generate buffers
GLuint VAO, VBO, colorVBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &colorVBO);
glBindVertexArray(VAO);
// Position buffer
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, (void*)0);
glEnableVertexAttribArray(0);
// Color buffer
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glBufferData(GL_ARRAY_BUFFER, 0, nullptr, GL_DYNAMIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Projection matrix: orthographic
Eigen::Matrix4f projection = Eigen::Matrix4f::Identity();
projection(0,0) = 2.0f / 1.0f; // Assuming domain [0,1] x [0,1]
projection(1,1) = 2.0f / 1.0f;
projection(3,0) = -1.0f;
projection(3,1) = -1.0f;
// Add objects (particles)
add_object(Vec2(0.55f, 0.45f), 0xED553B / 255.0);
add_object(Vec2(0.45f, 0.65f), 0xF2B134 / 255.0);
add_object(Vec2(0.55f, 0.85f), 0x068587 / 255.0);
// Convert hexadecimal colors to RGB
auto hex_to_rgb = [](int hex) -> Vec3 {
float r = ((hex >> 16) & 0xFF) / 255.0f;
float g = ((hex >> 8) & 0xFF) / 255.0f;
float b = (hex & 0xFF) / 255.0f;
return Vec3(r, g, b);
};
// Main simulation loop
float accumulated_time = 0.0f;
int frame_count = 0;
while (!glfwWindowShouldClose(window)) {
// Poll events
glfwPollEvents();
// Advance simulation
advance_simulation(dt);
accumulated_time += dt;
// Render frame if enough time has passed
if (accumulated_time >= frame_dt) {
// Prepare data for rendering
std::vector<float> vertices;
std::vector<float> colors;
for (const auto& p : particles) {
vertices.push_back(p.x.x());
vertices.push_back(p.x.y());
Vec3 color = hex_to_rgb(p.c);
colors.push_back(color.x());
colors.push_back(color.y());
colors.push_back(color.z());
}
// Update buffers
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), vertices.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(float), colors.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// Clear screen
glClearColor(0.07f, 0.18f, 0.25f, 1.0f); // Similar to 0x112F41
glClear(GL_COLOR_BUFFER_BIT);
// Render particles
glUseProgram(shaderProgram);
glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, projection.data());
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, particles.size());
glBindVertexArray(0);
// Optional: Render boundary box
// You can implement rendering a rectangle using line loops if desired
// Swap buffers
glfwSwapBuffers(window);
accumulated_time = 0.0f;
frame_count++;
}
}
// Cleanup
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &colorVBO);
glDeleteVertexArrays(1, &VAO);
glDeleteProgram(shaderProgram);
glfwTerminate();
return 0;
}
3. Explanation of the Code
Dependencies and Setup
-
Eigen: Used for all linear algebra operations such as vectors (Vec2, Vec3) and matrices (Mat2). Eigen's types simplify matrix and vector manipulations inherent in MPM simulations.
-
GLFW and GLAD: Manage window creation and OpenGL context setup. GLAD is used to load OpenGL functions, and GLFW handles windowing and input.
Particle and Grid Representation
-
Particle: Each particle has a position (x), velocity (v), deformation gradient (F), affine velocity field (C), plasticity factor (Jp), and color (c).
-
Grid: A 2D grid of GridNode structures, each holding velocity and mass information for grid nodes.
Simulation Steps
-
Particle to Grid (P2G):
- Particles contribute to nearby grid nodes based on quadratic B-spline weights.
- Computes stress based on the deformation gradient and applies it to update grid velocities.
-
Grid Operations:
- Applies gravity by modifying grid velocities.
- Handles boundary conditions by resetting velocities of grid nodes near the domain boundaries.
-
Grid to Particle (G2P):
- Updates particle velocities and affine velocity fields based on grid node data.
- Updates particle positions and deformation gradients.
- Applies plasticity via SVD decomposition and clamps singular values to simulate material behavior.
Rendering with OpenGL
Utility Functions
-
Clamping: Ensures values stay within specified bounds, crucial for stability in simulations.
-
Polar Decomposition and SVD: Used for updating the deformation gradient and applying plasticity to simulate material behavior.
Color Handling
- Particle colors are specified as hexadecimal values and converted to normalized RGB values for OpenGL rendering.
4. Building the Project
To compile this project, you can use a build system like CMake or compile manually using g++ or clang++. Here's an example using g++:
g++ main.cpp -o mpm_simulation -I/path/to/eigen -lglfw -ldl -lGL
Make sure to replace /path/to/eigen with the actual path to the Eigen library on your system. Also, ensure that GLAD's generated source files are included if you have them.
5. Running the Simulation
Once compiled, run the executable. A window titled "Real-time 2D MLS-MPM" should appear, displaying the simulated particles. The particles should interact according to the MPM simulation logic, showing behaviors such as deformation and plasticity.
Additional Enhancements
-
Rendering the Boundary Box: Currently, the boundary box isn't rendered. To visualize boundaries, you can add line rendering using OpenGL's GL_LINE_LOOP.
-
Interactivity: Implement user controls to add/remove particles or interact with the simulation.
-
Performance Optimization: For large numbers of particles, consider optimizing data structures and leveraging GPU compute shaders for simulation steps.
-
Visualization Improvements: Implement zooming, panning, or particle scaling for better visualization.
This implementation provides a foundation to perform MPM simulations using Eigen for computations and OpenGL for rendering. Depending on your requirements, you can further enhance and optimize the simulation and visualization aspects.