Generate a random direction within a cone I have a normalized $3D$ vector giving a direction and an angle that forms a cone around it, something like this:

I'd like to generate a random, uniformly distributed normalized vector for a direction within that cone. I would also like to support angles greater than pi (but lower or equal to $2\pi$), at which point the shape becomes more like a sphere from which a cone was removed. How can I proceed?
I thought about the following steps, but my implementation did not seem to work:


*

*Find a vector normal to the cone axis vector (by crossing the cone axis vector with the cardinal axis that corresponds with the cone axis vector component nearest to zero, ex: $[1 0 0]$ for $[-1 5 -10]$)

*Find a second normal vector using a cross product

*Generate a random angle between $[-\pi, \pi]$

*Rotate use the two normal vectors as a $2D$ coordinate system to create a new vector at the angle previously generated

*Generate a random displacement value between $[0, \tan(\theta)]$ and square root it (to normalize distribution like for points in a circle)

*Normalize the sum of the cone axis vector with the random normal vector times the displacement value to get the final direction vector


[edit] After further thinking, I'm not sure that method would work with theta angles greater or equal to pi. Alternative methods are very much welcome.

So you want to uniformly sample on a spherical cap. With the notations of this link, here is some pseudo-code which performs the sampling on the cap displayed in the above link (then it remains to perform a rotation):
stopifnot(h > 0 && h < 2 * R)
xy = uniform_point_in_unit_circle()
k = h * dotproduct(xy)
s = sqrt(h * (2 * R - k))
x = xy[1]
y = xy[2]
return (s * x, s * y, R - k)

I have this code in my archives, unfortunately I don't remember how I got it.
I put the image of the link here, in case it changes:

