@javismiles you may know some of this but lets take things step by step anyway.
The gradient of a line in 2D space is a single scalar number. A gradient in 3D space is a 2D vector.
To find the gradient of a 3D surface at a point you take the plane tangent to the surface at that point, find the line of greatest slope on the tangent plane, along which lie 3D vectors and you find the gradient for that vector.
You need to remember that in Babylon.js the y axis is vertical and the x and z axes horizontal.
Take vector G to be on the line of greatest slope on a plane P, then there exists a vector R = (xR, yR, 0) and a vector S = (0, yS, zS) such that G = R + S
Now the 2D vector Rxy = (xR, yR) is in the XY plane and has a gradient gR in that plane. The 2D vector Syz = (yS, zS) is in the YZ plane and has a gradient gS in that plane.
The gradient of G is given by the vector (gR, gS)
For a surface given by the function y = f(x, z) you find the gradient at a point using partial derivatives.
As you said in Babylon.js the surface of a mesh is represented by a network of triangles. Take one of these triangles, once you have the equation for the plane the triangle lies in you can find the gradient of the plane. Since it is a plane the gradient at any point within the triangle will be a constant 2D vector.
The equation of any plane has the form ax + by + cz + d = 0; its gradient is given by (∂y / ∂x , ∂y / ∂z ) as y is vertical
Taking partial derivative w.r.t x gives a + b * ∂y / ∂x = 0 and so
∂y / ∂x = - a / b
Taking partial derivative w.r.t z gives b * ∂y / ∂z + c = 0 and so
∂y / ∂z = - c / b
Given the equation of a plane as ax + by + cz + d = 0 its gradient is (-a / b, -c / b)
Now all you need to do is find a, b, c, and d.
Let P be the position vector of a point on the plane, and N the normal vector of the plane then
const plane = BABYLON.Plane.FromPositionAndNormal(P, N)
will construct the plane and from this you can use
plane.asArray(); // to give you [a, b, c, d]
and the equation of the plane is ax + by +cz + d = 0.
and you can now find the gradient of the plane which is the gradient at point P.
As of yet I have not tested this out in practice.