#include "taichi.h" // Note: You DO NOT have to install taichi or taichimpm. using…
- User
#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
To rewrite the given Taichi MPM example code using OpenGL for rendering and Eigen for linear algebra, we must first replace Taichi-specific constructs with OpenGL for graphics and Eigen for vector and matrix operations. Here's a rough translation:
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <Eigen/Dense> #include <vector> #include <iostream> #include <cmath> // Constants and typedefs const int n = 80; // grid resolution const int window_size = 800; const float dt = 1e-4, frame_dt = 1e-3, dx = 1.0 / n, inv_dx = 1.0 / dx; const float particle_mass = 1.0, vol = 1.0; const float hardening = 10.0, E = 1e4, nu = 0.2; const float mu_0 = E / (2 * (1 + nu)), lambda_0 = E * nu / ((1 + nu) * (1 - 2 * nu)); using Vec2 = Eigen::Vector2f; using Mat2 = Eigen::Matrix2f; using Vec3 = Eigen::Vector3f; using Vec2i = Eigen::Vector2i; bool plastic = true; // Particle structure struct Particle { Vec2 x, v; Mat2 F, C; float Jp; int color; Particle(Vec2 x, int color, Vec2 v = Vec2::Zero()) : x(x), v(v), F(Mat2::Identity()), C(Mat2::Zero()), Jp(1.0), color(color) {} }; std::vector<Particle> particles; Vec3 grid[n + 1][n + 1]; // velocity + mass void advance(float dt) { // Reset grid std::memset(grid, 0, sizeof(grid)); // Particle to grid (P2G) for (auto &p : particles) { Vec2i base_coord = (p.x * inv_dx - Vec2(0.5f, 0.5f)).cast<int>(); Vec2 fx = p.x * inv_dx - base_coord.cast<float>(); // Quadratic kernels Vec2 w[3] = { 0.5f * (1.5f - fx).array().square().matrix(), 0.75f - (fx - Vec2(1.0f, 1.0f)).array().square().matrix(), 0.5f * (fx - Vec2(0.5f, 0.5f)).array().square().matrix(), }; float e = std::exp(hardening * (1.0f - p.Jp)); float mu = mu_0 * e; float lambda = lambda_0 * e; float J = p.F.determinant(); Eigen::JacobiSVD<Mat2> svd(p.F, Eigen::ComputeFullU | Eigen::ComputeFullV); Mat2 r = svd.matrixU() * svd.matrixV().transpose(); Mat2 stress = -4 * inv_dx * inv_dx * dt * vol * (2 * mu * (p.F - r) * p.F.transpose() + lambda * (J - 1) * J * Mat2::Identity()); Mat2 affine = stress + particle_mass * p.C; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Vec2 dpos = (Vec2(i, j) - fx) * dx; Vec3 mv(p.v * particle_mass, particle_mass); grid[base_coord.x() + i][base_coord.y() + j] += w[i].x() * w[j].y() * (mv + Vec3(affine * dpos, 0)); } } } // Update grid velocities for (int i = 0; i <= n; i++) { for (int j = 0; j <= n; j++) { Vec3 &g = grid[i][j]; if (g.z() > 0) { g /= g.z(); // Normalize by mass g += dt * Vec3(0, -200, 0); // Apply gravity float boundary = 0.05, x = float(i) / n, y = float(j) / n; if (x < boundary || x > 1 - boundary || y > 1 - boundary) { g = Vec3::Zero(); // Sticky boundaries } if (y < boundary) { g.y() = std::max(0.0f, g.y()); //"Separate" to prevent particles from bouncing } } } } // Grid to particle (G2P) for (auto &p : particles) { Vec2i base_coord = (p.x * inv_dx - Vec2(0.5f, 0.5f)).cast<int>(); Vec2 fx = p.x * inv_dx - base_coord.cast<float>(); Vec2 w[3] = { 0.5f * (1.5f - fx).array().square().matrix(), 0.75f - (fx - Vec2(1.0f, 1.0f)).array().square().matrix(), 0.5f * (fx - Vec2(0.5f, 0.5f)).array().square().matrix(), }; p.C = Mat2::Zero(); p.v = Vec2::Zero(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Vec2 dpos = Vec2(i, j) - fx; Vec2 grid_v = Vec2(grid[base_coord.x() + i][base_coord.y() + j].head<2>()); float weight = w[i].x() * w[j].y(); p.v += weight * grid_v; p.C += 4 * inv_dx * weight * grid_v * dpos.transpose(); } } // Advection p.x += dt * p.v; Mat2 F = (Mat2::Identity() + dt * p.C) * p.F; // Snow Plasticity Eigen::JacobiSVD<Mat2> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV); Mat2 svd_u = svd.matrixU(), svd_v = svd.matrixV(); Mat2 sig = svd.singularValues().asDiagonal(); for (int i = 0; i < 2 * int(plastic); i++) { sig(i, i) = std::clamp(sig(i, i), 1.0f - 2.5e-2f, 1.0f + 7.5e-3f); } float oldJ = F.determinant(); F = svd_u * sig * svd_v.transpose(); float Jp_new = std::clamp(p.Jp * oldJ / F.determinant(), 0.6f, 20.0f); p.Jp = Jp_new; p.F = F; } } // Add objects into the simulation void add_object(Vec2 center, int color) { for (int i = 0; i < 500; i++) { particles.emplace_back((Vec2::Random() * 2.0f - Vec2::Ones()) * 0.08f + center, color); } } // Initialize OpenGL and set up rendering GLFWwindow* initOpenGL() { if (!glfwInit()) { std::cerr << "Failed to initialize GLFW" << std::endl; exit(EXIT_FAILURE); } GLFWwindow* window = glfwCreateWindow(window_size, window_size, "Real-time 2D MLS-MPM", nullptr, nullptr); if (!window) { std::cerr << "Failed to create GLFW window" << std::endl; glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glewExperimental = true; if (glewInit() != GLEW_OK) { std::cerr << "Failed to initialize GLEW" << std::endl; exit(EXIT_FAILURE); } return window; } void renderParticles() { glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POINTS); for (const auto &p : particles) { glColor3ub((p.color >> 16) & 0xFF, (p.color >> 8) & 0xFF, p.color & 0xFF); glVertex2f(p.x.x(), p.x.y()); } glEnd(); } int main() { GLFWwindow* window = initOpenGL(); add_object(Vec2(0.55f, 0.45f), 0xED553B); add_object(Vec2(0.45f, 0.65f), 0xF2B134); add_object(Vec2(0.55f, 0.85f), 0x068587); glPointSize(2.0); while (!glfwWindowShouldClose(window)) { advance(dt); glClearColor(0.067f, 0.184f, 0.255f, 1.0f); renderParticles(); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; }Notes:
- Integration of Libraries: The rewritten example uses GLFW for window management and GLEW for OpenGL function loading, circumventing the direct use of GLAD as specified. Eigen is used for matrix computations instead of Taichi's
Vector2andMatrix2. - Visual Representation: Basic OpenGL commands are used to render particles as points with assigned colors. For more aesthetic visuals, shaders can be introduced.
- Functionality: The core functionality of the Taichi example, such as the particle physics and grid handling, has been preserved to closely match the original behavior.
- Optimization: For a real-world scenario, consider improving performance through more advanced OpenGL techniques, like using vertex buffers or instanced rendering.
- Integration of Libraries: The rewritten example uses GLFW for window management and GLEW for OpenGL function loading, circumventing the direct use of GLAD as specified. Eigen is used for matrix computations instead of Taichi's
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.