#include "taichi.h" // Note: You DO NOT have to install taichi or taichi_mpm.
using namespace taichi;// You only need [taichi.h] - see below for instructions.
const int n = 80 /grid resolution (cells)/, window_size = 800;
const real dt = 1e-4_f, frame_dt = 1e-3_f, dx = 1.0_f / n, inv_dx = 1.0_f / dx;
auto particle_mass = 1.0_f, vol = 1.0_f;
auto hardening = 10.0_f, E = 1e4_f, nu = 0.2_f;
real mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1+nu) * (1 - 2 * nu));
using Vec = Vector2; using Mat = Matrix2; bool plastic = true;
struct Particle { Vec x, v; Mat F, C; real Jp; int c/color/;
Particle(Vec x, int c, Vec v=Vec(0)) : x(x), v(v), F(1), C(0), Jp(1), c(c){}};
std::vector particles;
Vector3 grid[n + 1][n + 1]; // velocity + mass, node_res = cell_res + 1
void advance(real dt) {
std::memset(grid, 0, sizeof(grid)); // Reset grid
for (auto &p : particles) { // P2G
Vector2i base_coord=(p.xinv_dx-Vec(0.5_f)).cast();//element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast();
// Quadratic kernels [http://mpm.graphics Eqn. 123, with x=fx, fx-1,fx-2]
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
auto e = std::exp(hardening * (1.0_f - p.Jp)), mu=mu_0e, lambda=lambda_0e;
real J = determinant(p.F); // Current volume
Mat r, s; polar_decomp(p.F, r, s); //Polar decomp. for fixed corotated model
auto stress = // Cauchy stress times dt and inv_dx
-4inv_dxinv_dxdtvol(2mu(p.F-r) * transposed(p.F)+lambda*(J-1)J);
auto affine = stress+particle_massp.C;
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { // Scatter to grid
auto dpos = (Vec(i, j) - fx) * dx;
Vector3 mv(p.v * particle_mass, particle_mass); //translational momentum
grid[base_coord.x + i][base_coord.y + j] +=
w[i].xw[j].y * (mv + Vector3(affinedpos, 0));
}
}
for(int i = 0; i <= n; i++) for(int j = 0; j <= n; j++) { //For all grid nodes
auto &g = grid[i][j];
if (g[2] > 0) { // No need for epsilon here
g /= g[2]; // Normalize by mass
g += dt * Vector3(0, -200, 0); // Gravity
real boundary=0.05,x=(real)i/n,y=real(j)/n; //boundary thick.,node coord
if (x < boundary||x > 1-boundary||y > 1-boundary) g=Vector3(0); //Sticky
if (y < boundary) g[1] = std::max(0.0_f, g[1]); //"Separate"
}
}
for (auto &p : particles) { // Grid to particle
Vector2i base_coord=(p.x*inv_dx-Vec(0.5_f)).cast();//element-wise floor
Vec fx = p.x * inv_dx - base_coord.cast();
Vec w[3]{Vec(0.5) * sqr(Vec(1.5) - fx), Vec(0.75) - sqr(fx - Vec(1.0)),
Vec(0.5) * sqr(fx - Vec(0.5))};
p.C = Mat(0); p.v = Vec(0);
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) {
auto dpos = (Vec(i, j) - fx),
grid_v = Vec(grid[base_coord.x + i][base_coord.y + j]);
auto weight = w[i].x * w[j].y;
p.v += weight * grid_v; // Velocity
p.C += 4 * inv_dx * Mat::outer_product(weight * grid_v, dpos); // APIC C
}
p.x += dt * p.v; // Advection
auto F = (Mat(1) + dt * p.C) * p.F; // MLS-MPM F-update
Mat svd_u, sig, svd_v; svd(F, svd_u, sig, svd_v);
for (int i = 0; i < 2 * int(plastic); i++) // Snow Plasticity
sig[i][i] = clamp(sig[i][i], 1.0_f - 2.5e-2_f, 1.0_f + 7.5e-3_f);
real oldJ = determinant(F); F = svd_u * sig * transposed(svd_v);
real Jp_new = clamp(p.Jp * oldJ / determinant(F), 0.6_f, 20.0_f);
p.Jp = Jp_new; p.F = F;
}
}
void add_object(Vec center, int c) { // Seed particles with position and color
for (int i = 0; i < 500; i++) // Randomly sample 1000 particles in the square
particles.push_back(Particle((Vec::rand()*2.0_f-Vec(1))*0.08_f + center, c));
}
int main() {
GUI gui("Real-time 2D MLS-MPM", window_size, window_size);
add_object(Vec(0.55,0.45), 0xED553B); add_object(Vec(0.45,0.65), 0xF2B134);
add_object(Vec(0.55,0.85), 0x068587); auto &canvas = gui.get_canvas();int f=0;
for (int i = 0;; i++) { // Main Loop
advance(dt); // Advance simulation
if (i % int(frame_dt / dt) == 0) { // Visualize frame
canvas.clear(0x112F41); // Clear background
canvas.rect(Vec(0.04), Vec(0.96)).radius(2).color(0x4FB99F).close();// Box
for(auto p:particles)canvas.circle(p.x).radius(2).color(p.c);//Particles
gui.update(); // Update image
// canvas.img.write_as_image(fmt::format("tmp/{:05d}.png", f++));
}
}
}
Rewrite it so it uses opengl and eigen, don't use glad
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a complete C++ program that rewrites your Taichi-based Material Point Method (MPM) simulation to use OpenGL for rendering and Eigen for linear algebra operations. This version leverages GLFW for window and context creation instead of Taichi's GUI system.
Dependencies:
Eigen: For vector and matrix operations.
GLFW: For window creation and managing the OpenGL context.
OpenGL: For rendering the simulation.
Note: OpenGL requires function pointers to be loaded at runtime. Typically, libraries like GLAD or GLEW are used for this purpose. However, since you've requested not to use GLAD, this example uses GLFW's native support to load OpenGL functions. Ensure that your development environment supports the necessary OpenGL version (3.3 or higher is recommended).
Project Setup
Before diving into the code, ensure you have the following:
Eigen Library: Download and include Eigen in your project. You can get it from Eigen's official website.
// Required Headers
#include <GLFW/glfw3.h>
#include <Eigen/Dense>
#include <vector>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <random>
// Define Types using Eigen
using Vec = Eigen::Vector2f;
using Vec3 = Eigen::Vector3f;
using Mat = Eigen::Matrix2f;
// Simulation Constants
const int n = 80; // Grid resolution (cells)
const int window_size = 800;
const float dt = 1e-4f;
const float frame_dt = 1e-3f;
const float dx = 1.0f / n;
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 {
Vec x, v;
Mat F, C;
float Jp;
int color;
Particle(const Vec& x_, int c, const Vec& v_ = Vec::Zero())
: x(x_), v(v_), F(Mat::Identity()), C(Mat::Zero()), Jp(1.0f), color(c) {}
};
// Grid Node Structure
struct GridNode {
Vec3 velocity_mass; // x, y velocity and mass
} typedef GridNode;
// Global Variables
std::vector<Particle> particles;
std::vector<std::vector<GridNode>> grid;
// Shader Sources
const char* vertex_shader_src = R"(#version 330 core
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
uniform mat4 uProjection;
out vec3 vColor;
void main(){
gl_Position = uProjection * vec4(aPos, 0.0, 1.0);
vColor = aColor;
gl_PointSize = 4.0;
}
)";
const char* fragment_shader_src = R"(#version 330 core
in vec3 vColor;
out vec4 FragColor;
void main(){
FragColor = vec4(vColor, 1.0);
}
)";
// Function to Compile Shaders
GLuint compile_shader(GLenum type, const char* source){
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
// Check for compile errors
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if(!success){
char infoLog[512];
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cerr << "ERROR: Shader compilation failed\n" << infoLog << std::endl;
}
return shader;
}
// Function to Link Shader Program
GLuint link_program(GLuint vertex_shader, GLuint fragment_shader){
GLuint program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
// Check for linking errors
GLint success;
glGetProgramiv(program, GL_LINK_STATUS, &success);
if(!success){
char infoLog[512];
glGetProgramInfoLog(program, 512, NULL, infoLog);
std::cerr << "ERROR: Program linking failed\n" << infoLog << std::endl;
}
return program;
}
// Function to Advance Simulation
void advance_simulation(float dt){
// Reset Grid
for(int i = 0; i <= n; ++i)
for(int j = 0; j <= n; ++j)
grid[i][j].velocity_mass.setZero();
// P2G: Particle to Grid
for(auto &p : particles){
// Base Cell Coordinates
Vec base_f = p.x * inv_dx - Vec(0.5f, 0.5f);
Eigen::Vector2i base_coord = base_f.cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<float>();
// Quadratic Kernels
Vec w0 = 0.5f * (Vec(1.5f, 1.5f) - fx).cwiseMax(Vec::Zero()).cwiseMin(Vec(1.0f, 1.0f)).array().square().matrix();
Vec w1 = (0.75f - (fx.array() - 1.0f).square()).cwiseMax(Vec::Zero());
Vec w2 = 0.5f * (Vec(fx[0], fx[1]) - Vec(0.5f, 0.5f)).cwiseMax(Vec::Zero()).array().square().matrix();
Vec weights[3] = {w0, w1, w2};
// Stress Calculation
float e = std::exp(hardening * (1.0f - p.Jp));
float mu = mu_0 * e;
float lambda_ = lambda_0 * e;
float J = p.F.determinant();
// Polar Decomposition using SVD
Eigen::JacobiSVD<Mat> svd(p.F, Eigen::ComputeFullU | Eigen::ComputeFullV);
Mat R = svd.matrixU() * svd.matrixV().transpose();
Mat S = svd.matrixV() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();
// Cauchy Stress
Mat stress = (2.0f * mu / (dx * dx * dt * vol)) * (p.F - R) + (lambda_ * (J - 1.0f) * J) * Mat::Identity();
// Affine Velocity
Mat affine = stress + p.C * particle_mass;
// Scatter to Grid
for(int i = 0; i < 3; ++i){
for(int j = 0; j < 3; ++j){
int node_x = base_coord.x() + i;
int node_y = base_coord.y() + j;
if(node_x < 0 || node_x > n || node_y < 0 || node_y > n) continue;
Vec weight = weights[i].cwiseProduct(weights[j]);
Vec3 grid_v = Vec3(p.v[0], p.v[1], particle_mass);
grid[node_x][node_y].velocity_mass += weight.x() * weight.y() * (grid_v + Vec3(affine(0,0)*dx, affine(1,1)*dx, 0.0f));
}
}
}
// Update Grid Velocities
for(int i = 0; i <= n; ++i){
for(int j = 0; j <= n; ++j){
auto &g = grid[i][j].velocity_mass;
if(g[2] > 0){
g /= g[2];
g += dt * Vec3(0.0f, -200.0f, 0.0f); // Gravity
float boundary = 0.05f;
float x = static_cast<float>(i) / static_cast<float>(n);
float y = static_cast<float>(j) / static_cast<float>(n);
// Sticky Boundaries
if(x < boundary || x > 1.0f - boundary || y > 1.0f - boundary){
g = Vec3::Zero();
}
// Separate Boundaries
if(y < boundary){
g[1] = std::max(0.0f, g[1]);
}
}
}
}
// Grid to Particle
for(auto &p : particles){
Vec base_f = p.x * inv_dx - Vec(0.5f, 0.5f);
Eigen::Vector2i base_coord = base_f.cast<int>();
Vec fx = p.x * inv_dx - base_coord.cast<float>();
// Quadratic Kernels
Vec w0 = 0.5f * (Vec(1.5f, 1.5f) - fx).cwiseMax(Vec::Zero()).cwiseMin(Vec(1.0f, 1.0f)).array().square().matrix();
Vec w1 = (0.75f - (fx.array() - 1.0f).square()).cwiseMax(Vec::Zero());
Vec w2 = 0.5f * (Vec(fx[0], fx[1]) - Vec(0.5f, 0.5f)).cwiseMax(Vec::Zero()).array().square().matrix();
Vec weights[3] = {w0, w1, w2};
p.v.setZero();
p.C.setZero();
for(int i = 0; i < 3; ++i){
for(int j = 0; j < 3; ++j){
int node_x = base_coord.x() + i;
int node_y = base_coord.y() + j;
if(node_x < 0 || node_x > n || node_y < 0 || node_y > n) continue;
Vec weight = weights[i].cwiseProduct(weights[j]);
Vec3 grid_v = grid[node_x][node_y].velocity_mass;
p.v += weight.x() * weight.y() * grid_v.head<2>();
p.C += (4.0f * inv_dx) * (weight.x() * weight.y()) * (grid_v.head<2>() * (Vec(i, j) - fx).transpose());
}
}
// Update Position and Deformation Gradient
p.x += dt * p.v;
Mat F_new = (Mat::Identity() + dt * p.C) * p.F;
// SVD for Polar Decomposition
Eigen::JacobiSVD<Mat> svd_new(F_new, Eigen::ComputeFullU | Eigen::ComputeFullV);
Mat svd_u = svd_new.matrixU();
Mat svd_v = svd_new.matrixV();
Mat sig = svd_new.singularValues().asDiagonal();
if(plastic){
for(int d = 0; d < sig.rows(); ++d){
sig(d,d) = std::clamp(sig(d,d), 1.0f - 2.5e-2f, 1.0f + 7.5e-3f);
}
}
Mat F = svd_u * sig * svd_v.transpose();
float oldJ = F_new.determinant();
float Jp_new = std::clamp(p.Jp * oldJ / F.determinant(), 0.6f, 20.0f);
p.Jp = Jp_new;
p.F = F;
}
}
// Function to Add Objects (Particles)
void add_object(const Vec& center, int c) {
std::mt19937 gen(std::random_device{}());
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
for(int i = 0; i < 500; ++i){
Vec pos = Vec(dis(gen), dis(gen)) * 0.08f + center;
particles.emplace_back(pos, c);
}
}
// Main Function
int main(){
// Initialize Grid
grid.resize(n+1, std::vector<GridNode>(n+1, GridNode{Vec3::Zero()}));
// Initialize GLFW
if(!glfwInit()){
std::cerr << "Failed to initialize GLFW\n";
return -1;
}
// Configure GLFW for OpenGL 3.3 Core Profile
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR,3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Create GLFW Window
GLFWwindow* window = glfwCreateWindow(window_size, window_size, "Real-time 2D MLS-MPM", NULL, NULL);
if(!window){
std::cerr << "Failed to create GLFW window\n";
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize OpenGL function pointers using GLFW (No GLAD)
if(!glfwExtensionSupported("GL_VERSION_3_3")){
std::cerr << "OpenGL 3.3 not supported\n";
return -1;
}
// Compile Shaders and Link Program
GLuint vertex_shader = compile_shader(GL_VERTEX_SHADER, vertex_shader_src);
GLuint fragment_shader = compile_shader(GL_FRAGMENT_SHADER, fragment_shader_src);
GLuint shader_program = link_program(vertex_shader, fragment_shader);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
// Set Up Vertex Data and Buffers
GLuint VAO, VBO, colorVBO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glGenBuffers(1, &colorVBO);
glBindVertexArray(VAO);
// Position Attribute
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, particles.size() * 2 * sizeof(float), NULL, GL_DYNAMIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);
// Color Attribute
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glBufferData(GL_ARRAY_BUFFER, particles.size() * 3 * sizeof(float), NULL, GL_DYNAMIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (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; // Scale X
projection(1,1) = 2.0f / 1.0f; // Scale Y
projection(3,0) = -1.0f; // Translate X
projection(3,1) = -1.0f; // Translate Y
// Add Initial Objects
add_object(Vec(0.55f, 0.45f), 0xED553B); // Example colors
add_object(Vec(0.45f, 0.65f), 0xF2B134);
add_object(Vec(0.55f, 0.85f), 0x068587);
// Main Loop Variables
int frame = 0;
float accumulated_time = 0.0f;
// Main Rendering Loop
while(!glfwWindowShouldClose(window)){
// Advance Simulation
advance_simulation(dt);
accumulated_time += dt;
// Render Frame at Specified Frame Rate
if(accumulated_time >= frame_dt){
// Prepare Data for Rendering
std::vector<float> positions;
std::vector<float> colors;
for(auto &p : particles){
positions.push_back(p.x[0]);
positions.push_back(p.x[1]);
// Extract RGB from Hex Color
int c = p.color;
float r = ((c >> 16) & 0xFF) / 255.0f;
float g = ((c >> 8) & 0xFF) / 255.0f;
float b = (c & 0xFF) / 255.0f;
colors.push_back(r);
colors.push_back(g);
colors.push_back(b);
}
// Update Buffer Data
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, positions.size() * sizeof(float), positions.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, colorVBO);
glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(float), colors.data(), GL_DYNAMIC_DRAW);
// Clear Screen
glClearColor(0.07f, 0.18f, 0.25f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
// Use Shader Program
glUseProgram(shader_program);
// Set Projection Uniform
GLuint proj_loc = glGetUniformLocation(shader_program, "uProjection");
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection.data());
// Bind VAO and Draw Particles
glBindVertexArray(VAO);
glDrawArrays(GL_POINTS, 0, particles.size());
glBindVertexArray(0);
// Swap Buffers and Poll Events
glfwSwapBuffers(window);
glfwPollEvents();
// Reset Accumulated Time
accumulated_time -= frame_dt;
frame++;
}
}
// Cleanup Resources
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &colorVBO);
glDeleteVertexArrays(1, &VAO);
glDeleteProgram(shader_program);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
Explanation of the Code
Libraries and Types:
Eigen: Utilized for all vector (Vec) and matrix (Mat) operations, simplifying linear algebra computations.
GLFW: Handles window creation, OpenGL context management, and input/events.
Simulation Setup:
Particles and Grid: The simulation initializes particles and a grid to perform Particle-to-Grid (P2G) and Grid-to-Particle (G2P) transfers essential for the MPM simulation.
Physical Constants: Parameters like mass, volume (vol), elasticity modulus (E), Poisson's ratio (nu), etc., are defined.
Shaders:
Vertex Shader: Transforms particle positions to screen space and passes color data to the fragment shader.
Fragment Shader: Assigns color to each fragment (pixel) of the rendered particles.
Rendering Setup:
Vertex Array Object (VAO) and Vertex Buffer Objects (VBOs): Manage the particle positions and colors.
Projection Matrix: An orthographic projection is used to map simulation coordinates to screen coordinates.
Simulation Loop:
The main loop advances the simulation by a small timestep (dt), updates particle positions and velocities, and then renders the updated particle states.
Frame Rate Control: Rendering occurs at intervals defined by frame_dt to ensure real-time visualization.
Adding Objects:
The add_object function initializes particles at specified centers with given colors. This simulates different materials or matter in the simulation.
Cleanup:
Properly deletes OpenGL buffers and terminates GLFW upon exiting the simulation.
Compiling the Code
Ensure you link against the necessary libraries when compiling. Here's an example using g++:
Replace /path_to_eigen with the actual path to your Eigen installation. Also, ensure that the OpenGL development headers are installed on your system.
Running the Simulation
Execute the compiled binary. A window titled "Real-time 2D MLS-MPM" should appear, visualizing the simulated particles. Particles are rendered as colored points, and their behavior results from the MPM simulation.
Additional Notes
Performance Optimization: For larger simulations, consider optimizing data structures, leveraging GPU computations, or implementing spatial partitioning to enhance performance.
Interactivity: GLFW allows you to handle user inputs. You can extend the simulation by adding mouse interactions to add or manipulate particles in real-time.
Visualization Enhancements: Implement shaders for better visualization effects, such as lighting, shadows, or particle animations.
This rewritten code should provide a solid foundation for your MPM simulation using OpenGL and Eigen. Adjust the simulation parameters and rendering details as needed to fit your specific requirements.