Changing object position deforms its tangent/normals

  c++, glm, glm-math, normals

I’m calculating tangents & normals per-vertex and it works perfectly when the mesh’s position is set to (0, 0, 0), but when I try to add to the position and recalculate the tangents/normals the object gets deformed in a weird way.

this is the mesh when its position is set to (0, 0, 0) which is fine

this is the mesh when its position is set to something like (10,0,10)

here’s the code which calculates the vertex tangents & normals:

glm::vec3 GetUnitNormal(const glm::vec2& p1, const glm::vec2& p2, const float s)
    // get a point near to p1
    const glm::vec2 p3 = p1 + ( (p2 - p1) * s );

    // calculate tangent slope
    const float m = (p3.y - p1.y) / (p3.x - p1.x);

    // calculate Y-intercept
    const float c = p1.y - m * p1.x;

    // calculate the tangent line's Y component
    const float y = (m * p1.x) + c;

    // tangent line's vector
    const glm::vec2 tangent = glm::normalize(glm::vec2(p1.x, y));

    // normal vector
    glm::vec3 normal = glm::vec3(-tangent.y, 0, tangent.x);

    return glm::normalize(normal);

and this is how the function is used:

    glm::vec3 n = GetUnitNormal
        glm::vec2(v1->position.x, v1->position.z),
        glm::vec2(v2->position.x, v2->position.z),

Source: Windows Questions C++