here is the metal code and original in cuda, I am doing in metal shading language and it doesn;t work. please review and fix it. method summary - Vertex Block Descent (VBD) for physics-based simulation, focusing on elastic body dynamics. It introduces a block-coordinate descent method using vertex-level Gauss-Seidel iterations to solve the variational form of implicit Euler integration. VBD operates by updating vertex positions to minimize global variational energy, allowing for high levels of parallelism. It guarantees unconditional stability and fast convergence, especially for complex simulations like elastic bodies, particle systems, and rigid bodies.
Main Equations:
Global Optimization Problem:
x
t
+
1
arg
min
x
G
(
x
)
x
t+1
=arg
x
min
G(x)
Where
G
(
x
)
G(x) represents the global variational energy.
Variational Energy:
G
(
x
)
1
2
h
2
∥
x
−
y
∥
M
2
+
E
(
x
)
G(x)=
2h
2
1
∥x−y∥
M
2
+E(x)
Where
y
x
t
+
h
v
t
+
h
2
a
e
x
t
y=x
t
+hv
t
+h
2
a
ext
, and
E
(
x
)
E(x) is the potential energy of the system.
Local Energy Minimization: For each vertex
i
i, the local variational energy is:
G
i
(
x
)
m
i
2
h
2
∥
x
i
−
y
i
∥
2
+
∑
j
∈
F
i
E
j
(
x
)
G
i
(x)=
2h
2
m
i
∥x
i
−y
i
∥
2
+
j∈F
i
∑
E
j
(x)
The update step for vertex
i
i:
x
i
←
arg
min
x
i
G
i
(
x
)
x
i
←arg
x
i
min
G
i
(x)
Newton’s Method for Local System:
H
i
Δ
x
i
f
i
H
i
Δx
i
=f
i
Where
H
i
H
i
is the Hessian, and
f
i
f
i
is the total force on vertex
i
i.
Velocity Update:
v
t
+
1
1
h
(
x
t
+
1
−
x
t
)
v
t+1
h
1
(x
t+1
−x
t
)
struct Mat9x9Static {
float data[81];
METAL_FUNC thread float& operator()(int row, int col) {
return data[col * 9 + row];
}
METAL_FUNC const thread float& operator()(int row, int col) const {
return data[col * 9 + row];
}
METAL_FUNC void multiplyBy(float scalar) {
for (int i = 0; i < 81; ++i) {
data[i] *= scalar;
}
}
// Initialize to zero
METAL_FUNC void initializeZero() {
for (int i = 0; i < 81; ++i) {
data[i] = 0.0f;
}
}
};
METAL_FUNC void vec9OuterProduct(const thread float* a, const thread float* b, thread Mat9x9Static& result) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
result(i, j) = a[i] * b[j];
}
}
}
METAL_FUNC void vec9Mul(const thread float* a, float scalar, thread float* result) {
for (int i = 0; i < 9; ++i) {
result[i] = a[i] * scalar;
}
}
METAL_FUNC void vec9Add(const thread float* a, const thread float* b, thread float* result) {
for (int i = 0; i < 9; ++i) {
result[i] = a[i] + b[i];
}
}
// Compute the force components
// Note: The force is the negative gradient of the energy
force.x -= A1 * m1 + A4 * m2 + A7 * m3;
force.y -= A2 * m1 + A5 * m2 + A8 * m3;
force.z -= A3 * m1 + A6 * m2 + A9 * m3;
// Initialize temporary storage for Hessian computation
float HL_Row1[9], HL_Row2[9], HL_Row3[9];
thread float* HL[3] = { HL_Row1, HL_Row2, HL_Row3 };
// Compute the product of d2E_dF_dF with the shape function derivatives
for (int iCol = 0; iCol < 9; iCol++) {
HL_Row1[iCol] = d2E_dF_dF(0, iCol) * m1 + d2E_dF_dF(3, iCol) * m2 + d2E_dF_dF(6, iCol) * m3;
HL_Row2[iCol] = d2E_dF_dF(1, iCol) * m1 + d2E_dF_dF(4, iCol) * m2 + d2E_dF_dF(7, iCol) * m3;
HL_Row3[iCol] = d2E_dF_dF(2, iCol) * m1 + d2E_dF_dF(5, iCol) * m2 + d2E_dF_dF(8, iCol) * m3;
}
// Assemble the final Hessian
for (int iRow = 0; iRow < 3; iRow++) {
// Compute the diagonal elements of the Hessian
h[iRow] += HL[iRow][0] * m1 + HL[iRow][3] * m2 + HL[iRow][6] * m3;
// Compute the off-diagonal elements of the Hessian
h[iRow + 3] += HL[iRow][1] * m1 + HL[iRow][4] * m2 + HL[iRow][7] * m3;
h[iRow + 6] += HL[iRow][2] * m1 + HL[iRow][5] * m2 + HL[iRow][8] * m3;
}
}
METAL_FUNC void assembleDeterminantHessian(const thread float* ddetF_dF, thread Mat9x9Static& d2DetF_dF_dF) {
// Compute the second derivative of detF
// d2(detF)/dF_ij dF_kl = Cof(F)_jk * delta_il - Cof(F)_jl * delta_ik
for(int i = 0; i < 3; ++i) { // i corresponds to row in F
for(int j = 0; j < 3; ++j) { // j corresponds to column in F
for(int k = 0; k < 3; ++k) { // k corresponds to row in second F
for(int l = 0; l < 3; ++l) { // l corresponds to column in second F
int row = i * 3 + j;
int col = k * 3 + l;
float delta_il = (i == l) ? 1.0f : 0.0f;
float delta_ik = (i == k) ? 1.0f : 0.0f;
float value = ddetF_dF[j * 3 + k] * delta_il - ddetF_dF[j * 3 + l] * delta_ik;
d2DetF_dF_dF(row, col) += value;
}
}
}
}
}
METAL_FUNC void evaluateNeoHookeanMaterialForceAndHessian(float miu, float lmbd, float volume,
int vOrderInTet, const uint4 tetVIds, constant float3* vs,
const constant float3* vsPrev,
float3x3 DmInv,
thread float3& force,
thread float* h,
float dampingHydrostatic,
float dampingDeviatoric,
float dt)
{
// Retrieve the positions of the four vertices of the tetrahedron
float3 v0 = vs[int(tetVIds[0])];
float3 v1 = vs[int(tetVIds[1])];
float3 v2 = vs[int(tetVIds[2])];
float3 v3 = vs[int(tetVIds[3])];
// Compute the deformation matrix Ds
float3x3 Ds;
Ds[0] = v1 - v0; // Edge vector from v0 to v1
Ds[1] = v2 - v0; // Edge vector from v0 to v2
Ds[2] = v3 - v0; // Edge vector from v0 to v3
// Compute the deformation gradient F
float3x3 F = Ds * DmInv;
// Compute the 'a' parameter for the Neo-Hookean model
float a = 1 + miu / lmbd;
// Compute the determinant of F, which represents the volume change
float detF = determinant(F);
// Create a 1D array representation of F for easier access
float F_array[9] = {F[0][0], F[0][1], F[0][2],
F[1][0], F[1][1], F[1][2],
F[2][0], F[2][1], F[2][2]};
// Store individual components of F for later use
float F1_1 = F[0][0], F2_1 = F[1][0], F3_1 = F[2][0];
float F1_2 = F[0][1], F2_2 = F[1][1], F3_2 = F[2][1];
float F1_3 = F[0][2], F2_3 = F[1][2], F3_3 = F[2][2];
// Compute the derivative of detF with respect to F (cofactor matrix)
float ddetF_dF[9] = {
F2_2 * F3_3 - F2_3 * F3_2,
F1_3 * F3_2 - F1_2 * F3_3,
F1_2 * F2_3 - F1_3 * F2_2,
F2_3 * F3_1 - F2_1 * F3_3,
F1_1 * F3_3 - F1_3 * F3_1,
F1_3 * F2_1 - F1_1 * F2_3,
F2_1 * F3_2 - F2_2 * F3_1,
F1_2 * F3_1 - F1_1 * F3_2,
F1_1 * F2_2 - F1_2 * F2_1
};
// Initialize the Hessian matrix correctly
Mat9x9Static d2E_dF_dF;
d2E_dF_dF.initializeZero();
// Compute the outer product of ddetF_dF
Mat9x9Static outerProduct;
outerProduct.initializeZero();
vec9OuterProduct(ddetF_dF, ddetF_dF, outerProduct);
// Scale the outer product by lambda and add to Hessian
outerProduct.multiplyBy(lmbd);
for(int i = 0; i < 81; ++i) {
d2E_dF_dF.data[i] += outerProduct.data[i];
}
// Compute the second derivative of detF and add it to the Hessian
Mat9x9Static d2DetF_dF_dF;
d2DetF_dF_dF.initializeZero();
assembleDeterminantHessian(ddetF_dF, d2DetF_dF_dF);
// Scale the second derivative by lambda * k and add to Hessian
float k = detF - a;
for(int i = 0; i < 81; ++i) {
d2E_dF_dF.data[i] += d2DetF_dF_dF.data[i] * lmbd * k;
}
// Add mu to the diagonal elements of the Hessian
for (int i = 0; i < 9; ++i) {
d2E_dF_dF(i, i) += miu;
}
// Scale the Hessian by the volume
d2E_dF_dF.multiplyBy(volume);
// Compute the derivative of the deviatoric energy with respect to F
float dPhi_D_dF[9];
vec9Mul(F_array, miu, dPhi_D_dF);
// Compute the derivative of the volumetric energy with respect to F
float scaled_ddetF_dF[9];
vec9Mul(ddetF_dF, lmbd * k, scaled_ddetF_dF);
// Compute the total energy derivative
float dE_dF[9];
vec9Add(dPhi_D_dF, scaled_ddetF_dF, dE_dF);
vec9Mul(dE_dF, volume, dE_dF);
// Extract inverse rest matrix components
float DmInv1_1 = DmInv[0][0];
float DmInv2_1 = DmInv[1][0];
float DmInv3_1 = DmInv[2][0];
float DmInv1_2 = DmInv[0][1];
float DmInv2_2 = DmInv[1][1];
float DmInv3_2 = DmInv[2][1];
float DmInv1_3 = DmInv[0][2];
float DmInv2_3 = DmInv[1][2];
float DmInv3_3 = DmInv[2][2];
// Shape function derivatives for all vertices in the tetrahedron
float ms[4][3] = {
{-DmInv1_1 - DmInv2_1 - DmInv3_1, -DmInv1_2 - DmInv2_2 - DmInv3_2, -DmInv1_3 - DmInv2_3 - DmInv3_3},
{DmInv1_1, DmInv1_2, DmInv1_3},
{DmInv2_1, DmInv2_2, DmInv2_3},
{DmInv3_1, DmInv3_2, DmInv3_3}
};
// Get the shape function derivatives for the current vertex
float m1 = ms[vOrderInTet][0], m2 = ms[vOrderInTet][1], m3 = ms[vOrderInTet][2];
// Assemble the force and Hessian for the current vertex
assembleVertexVForceAndHessian(dE_dF, d2E_dF_dF, m1, m2, m3, force, h);
// Apply damping if needed
if (dampingHydrostatic > 0.f || dampingDeviatoric > 0.f) {
float dampingH[9];
vec9Mul(h, dampingHydrostatic, dampingH);
float tmp = (m1 * m1 + m2 * m2 + m3 * m3) * miu * volume;
h[0] += tmp;
h[4] += tmp;
h[8] += tmp;
tmp *= dampingDeviatoric;
dampingH[0] += tmp;
dampingH[4] += tmp;
dampingH[8] += tmp;
vec9Mul(dampingH, 1 / dt, dampingH);
// Compute the displacement
float3 v = vs[tetVIds[vOrderInTet]];
float3 vPrev = vsPrev[tetVIds[vOrderInTet]];
float3 displacement = vPrev - v;
// Compute the damping force
float3 dampingForce;
dampingForce.x = dot(float3(dampingH[0], dampingH[3], dampingH[6]), displacement);
dampingForce.y = dot(float3(dampingH[1], dampingH[4], dampingH[7]), displacement);
dampingForce.z = dot(float3(dampingH[2], dampingH[5], dampingH[8]), displacement);
force += dampingForce;
// Add damping to the Hessian
for (int i = 0; i < 9; ++i) {
h[i] += dampingH[i];
}
}
}. for comparison here is working metal version of xpbd stable neo hookean. but in need VBD (with hessian and force base formation). METAL_FUNC void reduceAndSolve(
uint simdIndex,
uint vertexIndex,
float3 force,
float3x3 hessian,
constant float3* prevPositions,
device float3* positions,
constant float3* preIterPositions,
constant float3* originalPositions,
constant float3* inertias,
StepInfo stepInfo,
SimulationConfigurationGPU configuration,
float3 p)
{
float3 totalForce = simd_sum(force);
if (simdIndex == 0) {
float3 currentForce = totalForce;
p = p.x == FLT_MAX ? preIterPositions[vertexIndex].xyz : p;
positions[vertexIndex].xyz = p + currentForce;
}
It seems that the primary issue in your Metal code is due to incorrect indexing when accessing matrix elements. In Metal, matrices are stored in column-major order, which means that the way you access elements differs from the way it's done in CUDA (which often uses row-major order). This can lead to misaligned data and, subsequently, incorrect calculations.
Here's how you can fix the indexing issues:
Correct the Matrix Indexing: Ensure that when you're accessing elements from float3x3 matrices in Metal, you account for the column-major storage. This means that to access the element at row i and column j, you should use F.columns[j][i].
Adjust Flattening of Matrices: When converting a matrix to a 1D array for easier access, make sure that you're correctly mapping the 2D indices to 1D indices, considering the column-major storage.
Update the Computation of Derived Quantities: After fixing the indexing, revisit the computations that rely on the matrix elements, such as the calculation of ddetF_dF and the assembly of the Hessian matrix.
Below is the corrected version of your Metal code with the necessary changes:
struct Mat9x9Static {
float data[81];
METAL_FUNC thread float& operator()(int row, int col) {
return data[col * 9 + row];
}
METAL_FUNC const thread float& operator()(int row, int col) const {
return data[col * 9 + row];
}
METAL_FUNC void multiplyBy(float scalar) {
for (int i = 0; i < 81; ++i) {
data[i] *= scalar;
}
}
// Initialize to zero
METAL_FUNC void initializeZero() {
for (int i = 0; i < 81; ++i) {
data[i] = 0.0f;
}
}
};
METAL_FUNC void vec9OuterProduct(const thread float* a, const thread float* b, thread Mat9x9Static& result) {
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9; ++j) {
result(i, j) = a[i] * b[j];
}
}
}
METAL_FUNC void vec9Mul(const thread float* a, float scalar, thread float* result) {
for (int i = 0; i < 9; ++i) {
result[i] = a[i] * scalar;
}
}
METAL_FUNC void vec9Add(const thread float* a, const thread float* b, thread float* result) {
for (int i = 0; i < 9; ++i) {
result[i] = a[i] + b[i];
}
}
METAL_FUNC void assembleVertexVForceAndHessian(const thread float* dE_dF, const thread Mat9x9Static& d2E_dF_dF,
float m1, float m2, float m3,
thread float3& force, thread float* h) {
// Extract components of dE_dF for easier access
float A1 = dE_dF[0];
float A2 = dE_dF[1];
float A3 = dE_dF[2];
float A4 = dE_dF[3];
float A5 = dE_dF[4];
float A6 = dE_dF[5];
float A7 = dE_dF[6];
float A8 = dE_dF[7];
float A9 = dE_dF[8];
// Compute the force components
// Note: The force is the negative gradient of the energy
force.x -= A1 * m1 + A4 * m2 + A7 * m3;
force.y -= A2 * m1 + A5 * m2 + A8 * m3;
force.z -= A3 * m1 + A6 * m2 + A9 * m3;
// Initialize temporary storage for Hessian computation
float HL_Row1[9], HL_Row2[9], HL_Row3[9];
thread float* HL[3] = { HL_Row1, HL_Row2, HL_Row3 };
// Compute the product of d2E_dF_dF with the shape function derivatives
for (int iCol = 0; iCol < 9; iCol++) {
HL_Row1[iCol] = d2E_dF_dF(0, iCol) * m1 + d2E_dF_dF(3, iCol) * m2 + d2E_dF_dF(6, iCol) * m3;
HL_Row2[iCol] = d2E_dF_dF(1, iCol) * m1 + d2E_dF_dF(4, iCol) * m2 + d2E_dF_dF(7, iCol) * m3;
HL_Row3[iCol] = d2E_dF_dF(2, iCol) * m1 + d2E_dF_dF(5, iCol) * m2 + d2E_dF_dF(8, iCol) * m3;
}
// Assemble the final Hessian
for (int iRow = 0; iRow < 3; iRow++) {
// Compute the diagonal elements of the Hessian
h[iRow] += HL[iRow][0] * m1 + HL[iRow][3] * m2 + HL[iRow][6] * m3;
// Compute the off-diagonal elements of the Hessian
h[iRow + 3] += HL[iRow][1] * m1 + HL[iRow][4] * m2 + HL[iRow][7] * m3;
h[iRow + 6] += HL[iRow][2] * m1 + HL[iRow][5] * m2 + HL[iRow][8] * m3;
}
}
METAL_FUNC void assembleDeterminantHessian(const thread float* ddetF_dF, thread Mat9x9Static& d2DetF_dF_dF, float3x3 F) {
// Compute the second derivative of detF
// d2(detF)/dF_ij dF_kl = Cof(F)_jk * delta_il - Cof(F)_jl * delta_ik
// Cof(F) is the cofactor matrix, which is the transpose of the adjugate of F
// Since we're dealing with the cofactor, we need to compute Cof(F)_jk and Cof(F)_jl
float3x3 CofF = cofactor(F); // Compute the cofactor matrix
for(int i = 0; i < 3; ++i) { // i corresponds to row in F
for(int j = 0; j < 3; ++j) { // j corresponds to column in F
for(int k = 0; k < 3; ++k) { // k corresponds to row in second F
for(int l = 0; l < 3; ++l) { // l corresponds to column in second F
int row = i * 3 + j;
int col = k * 3 + l;
float delta_il = (i == l) ? 1.0f : 0.0f;
float delta_ik = (i == k) ? 1.0f : 0.0f;
float value = CofF[j][k] * delta_il - CofF[j][l] * delta_ik;
d2DetF_dF_dF(row, col) += value;
}
}
}
}
}
METAL_FUNC void evaluateNeoHookeanMaterialForceAndHessian(float miu, float lmbd, float volume,
int vOrderInTet, const uint4 tetVIds, constant float3* vs,
const constant float3* vsPrev,
float3x3 DmInv,
thread float3& force,
thread float* h,
float dampingHydrostatic,
float dampingDeviatoric,
float dt)
{
// Retrieve the positions of the four vertices of the tetrahedron
float3 v0 = vs[int(tetVIds[0])];
float3 v1 = vs[int(tetVIds[1])];
float3 v2 = vs[int(tetVIds[2])];
float3 v3 = vs[int(tetVIds[3])];
// Compute the deformation matrix Ds
float3x3 Ds;
Ds[0] = v1 - v0; // Edge vector from v0 to v1
Ds[1] = v2 - v0; // Edge vector from v0 to v2
Ds[2] = v3 - v0; // Edge vector from v0 to v3
// Compute the deformation gradient F
float3x3 F = Ds * DmInv;
// Compute the 'a' parameter for the Neo-Hookean model
float a = 1 + miu / lmbd;
// Compute the determinant of F, which represents the volume change
float detF = determinant(F);
// Correctly flatten F into an array in row-major order
float F_array[9] = {
F.columns[0][0], F.columns[1][0], F.columns[2][0], // Row 0
F.columns[0][1], F.columns[1][1], F.columns[2][1], // Row 1
F.columns[0][2], F.columns[1][2], F.columns[2][2] // Row 2
};
// Store individual components of F for later use
float F1_1 = F.columns[0][0], F2_1 = F.columns[0][1], F3_1 = F.columns[0][2];
float F1_2 = F.columns[1][0], F2_2 = F.columns[1][1], F3_2 = F.columns[1][2];
float F1_3 = F.columns[2][0], F2_3 = F.columns[2][1], F3_3 = F.columns[2][2];
// Compute the derivative of detF with respect to F (cofactor matrix)
float ddetF_dF[9] = {
F2_2 * F3_3 - F2_3 * F3_2,
F2_3 * F3_1 - F2_1 * F3_3,
F2_1 * F3_2 - F2_2 * F3_1,
F3_2 * F1_3 - F3_3 * F1_2,
F3_3 * F1_1 - F3_1 * F1_3,
F3_1 * F1_2 - F3_2 * F1_1,
F1_2 * F2_3 - F1_3 * F2_2,
F1_3 * F2_1 - F1_1 * F2_3,
F1_1 * F2_2 - F1_2 * F2_1
};
// Initialize the Hessian matrix correctly
Mat9x9Static d2E_dF_dF;
d2E_dF_dF.initializeZero();
// Compute the outer product of ddetF_dF
Mat9x9Static outerProduct;
outerProduct.initializeZero();
vec9OuterProduct(ddetF_dF, ddetF_dF, outerProduct);
// Scale the outer product by lambda and add to Hessian
outerProduct.multiplyBy(lmbd);
for(int i = 0; i < 81; ++i) {
d2E_dF_dF.data[i] += outerProduct.data[i];
}
// Compute the second derivative of detF and add it to the Hessian
Mat9x9Static d2DetF_dF_dF;
d2DetF_dF_dF.initializeZero();
assembleDeterminantHessian(ddetF_dF, d2DetF_dF_dF, F);
// Scale the second derivative by lambda * k and add to Hessian
float k = detF - a;
for(int i = 0; i < 81; ++i) {
d2E_dF_dF.data[i] += d2DetF_dF_dF.data[i] * lmbd * k;
}
// Add mu to the diagonal elements of the Hessian
for (int i = 0; i < 9; ++i) {
d2E_dF_dF(i, i) += miu;
}
// Scale the Hessian by the volume
d2E_dF_dF.multiplyBy(volume);
// Compute the derivative of the deviatoric energy with respect to F
float dPhi_D_dF[9];
vec9Mul(F_array, miu, dPhi_D_dF);
// Compute the derivative of the volumetric energy with respect to F
float scaled_ddetF_dF[9];
vec9Mul(ddetF_dF, lmbd * k, scaled_ddetF_dF);
// Compute the total energy derivative
float dE_dF[9];
vec9Add(dPhi_D_dF, scaled_ddetF_dF, dE_dF);
vec9Mul(dE_dF, volume, dE_dF);
// Extract inverse rest matrix components
float DmInv1_1 = DmInv.columns[0][0];
float DmInv2_1 = DmInv.columns[0][1];
float DmInv3_1 = DmInv.columns[0][2];
float DmInv1_2 = DmInv.columns[1][0];
float DmInv2_2 = DmInv.columns[1][1];
float DmInv3_2 = DmInv.columns[1][2];
float DmInv1_3 = DmInv.columns[2][0];
float DmInv2_3 = DmInv.columns[2][1];
float DmInv3_3 = DmInv.columns[2][2];
// Shape function derivatives for all vertices in the tetrahedron
float ms[4][3] = {
{-DmInv1_1 - DmInv1_2 - DmInv1_3, -DmInv2_1 - DmInv2_2 - DmInv2_3, -DmInv3_1 - DmInv3_2 - DmInv3_3},
{DmInv1_1, DmInv2_1, DmInv3_1},
{DmInv1_2, DmInv2_2, DmInv3_2},
{DmInv1_3, DmInv2_3, DmInv3_3}
};
// Get the shape function derivatives for the current vertex
float m1 = ms[vOrderInTet][0], m2 = ms[vOrderInTet][1], m3 = ms[vOrderInTet][2];
// Assemble the force and Hessian for the current vertex
assembleVertexVForceAndHessian(dE_dF, d2E_dF_dF, m1, m2, m3, force, h);
// Apply damping if needed
if (dampingHydrostatic > 0.f || dampingDeviatoric > 0.f) {
float dampingH[9];
vec9Mul(h, dampingHydrostatic, dampingH);
float tmp = (m1 * m1 + m2 * m2 + m3 * m3) * miu * volume;
h[0] += tmp;
h[4] += tmp;
h[8] += tmp;
tmp *= dampingDeviatoric;
dampingH[0] += tmp;
dampingH[4] += tmp;
dampingH[8] += tmp;
vec9Mul(dampingH, 1 / dt, dampingH);
// Compute the displacement
float3 v = vs[tetVIds[vOrderInTet]];
float3 vPrev = vsPrev[tetVIds[vOrderInTet]];
float3 displacement = vPrev - v;
// Compute the damping force
float3 dampingForce;
dampingForce.x = dot(float3(dampingH[0], dampingH[3], dampingH[6]), displacement);
dampingForce.y = dot(float3(dampingH[1], dampingH[4], dampingH[7]), displacement);
dampingForce.z = dot(float3(dampingH[2], dampingH[5], dampingH[8]), displacement);
force += dampingForce;
// Add damping to the Hessian
for (int i = 0; i < 9; ++i) {
h[i] += dampingH[i];
}
}
}
METAL_FUNC void reduceAndSolveVBD(
uint simdIndex,
uint vertexIndex,
float3 force,
float3x3 hessian,
constant float3* prevPositions,
device float3* positions,
constant float3* preIterPositions,
constant float3* originalPositions,
constant float3* inertias,
float invMass,
StepInfo stepInfo,
float3 p)
{
float3 totalForce = simd_sum(force);
float3 hessianSum0 = simd_sum(hessian.columns[0]);
float3 hessianSum1 = simd_sum(hessian.columns[1]);
float3 hessianSum2 = simd_sum(hessian.columns[2]);
if (simdIndex == 0) {
float3 currentForce = totalForce;
float3x3 currentHessian = float3x3(hessianSum0, hessianSum1, hessianSum2);
p = p.x == FLT_MAX ? preIterPositions[vertexIndex] : p;
const float mass = 1.0 / invMass;
const float dtSqrReciprocal = 1.0 / (stepInfo.dt * stepInfo.dt);
// Newton-Raphson update: x_new = x - H^{-1} * f
// For a 3x3 matrix, we can compute the inverse directly if it's invertible
float3x3 H = currentHessian + mass * dtSqrReciprocal * float3x3(1);
float determinantH = determinant(H);
if (fabs(determinantH) > 1e-6) {
float3x3 invH = inverse(H);
float3 deltaX = -invH * currentForce;
positions[vertexIndex] = p + deltaX;
} else {
// If H is not invertible, skip the update
positions[vertexIndex] = p;
}
}
}
kernel void solveVBDNeoHookean(
device float3 *positions [[buffer(0)]],
constant TetConstraintDescriptorGPU *tetDescriptors [[buffer(1)]],
constant StepInfo &stepInfo [[buffer(2)]],
constant SimulationConfigurationGPU &configuration [[buffer(3)]],
constant float3 *prevPositions [[buffer(4)]],
constant float3 *inertias [[buffer(5)]],
constant float3 *preIterPositions [[buffer(6)]],
constant float3 *originalPositions [[buffer(7)]],
constant uint &descriptorsCount [[buffer(8)]],
constant float *invMasses [[buffer(9)]],
uint gid [[thread_position_in_grid]],
uint simdIndex [[thread_index_in_simdgroup]]
)
{
if (gid >= descriptorsCount) { return; }
const TetConstraintDescriptorGPU descriptor = tetDescriptors[gid];
const uint4 tet = descriptor.indices;
const uint vertexIndex = tet[descriptor.indexInTet];
float3 force = float3(0);
float3x3 hessian = float3x3(0);
float3 p = FLT_MAX;
if (descriptor.indices.w != UINT_MAX) {
p = preIterPositions[int(vertexIndex)];
const float dt = stepInfo.dt;
const float damping = 1e-5;
const float mu = 10000.0; // Shear modulus
const float lambda = 10000.0; // Lamé's first parameter
const float3x3 invRestMat = descriptor.invRestMat;
const uint indexInTet = descriptor.indexInTet;
const float restVolume = 1.0 / descriptor.inverseRestVolume; // Correct usage: inversed back
float h[9] = {0};
evaluateNeoHookeanMaterialForceAndHessian(mu, lambda, restVolume, indexInTet, descriptor.indices, preIterPositions, prevPositions, invRestMat, force, h, damping, damping, dt);
hessian.columns[0] = float3(h[0], h[1], h[2]);
hessian.columns[1] = float3(h[3], h[4], h[5]);
hessian.columns[2] = float3(h[6], h[7], h[8]);
}
reduceAndSolveVBD(simdIndex, vertexIndex, force, hessian,
prevPositions, positions, preIterPositions, originalPositions,
inertias, invMasses[vertexIndex], stepInfo, p);
}
Key Changes and Explanations:
Matrix Indexing: Updated the way you access elements from matrices, considering Metal's column-major order. This affects how you flatten matrices into arrays and how you extract elements like F1_1, F2_1, etc.
assembleDeterminantHessian Function: Modified the function to correctly compute the second derivative of the determinant, using the cofactor matrix.
evaluateNeoHookeanMaterialForceAndHessian: Adjusted the calculations to ensure that all matrix and vector operations correctly account for the storage order and indexing. Extracted the correct components of F for computations.
Volume Correction: In your kernel function, ensured that you're using the correct volume (restVolume = 1.0 / descriptor.inverseRestVolume), since descriptor.inverseRestVolume is an inverse.
Newton-Raphson Update in reduceAndSolveVBD: Implemented a simple Newton-Raphson update for the position, considering that you need to solve H * deltaX = -force. Make sure to handle cases where the Hessian might be singular.
Next Steps:
Testing: After making these changes, test your code with a known scenario to ensure that the simulation behaves as expected.
Debugging: If issues persist, consider adding debugging statements to check intermediate values like F, detF, ddetF_dF, forces, and Hessians.
Validation Against Known Solutions: Compare the results of your Metal implementation with those from your original CUDA code to verify correctness.
By ensuring that the indexing and storage conventions match between your Metal code and the original algorithm, you should achieve the desired functionality.