dilevin / computer-graphics-shader-pipeline

Computer Graphics Assignment about the Shader Pipeline
2 stars 5 forks source link

Rejection sampling in random_direction #55

Closed MstrPikachu closed 8 months ago

MstrPikachu commented 8 months ago

For sphere point picking I decided to use the Marsaglia (1972) method as described below: https://mathworld.wolfram.com/SpherePointPicking.html

It starts with picking a random point in the unit circle by rejection sampling.

I started it with a loop that continues while the point is outside the circle:

vec3 a = vec3(0, 0, 0);
float n = 0;
  do {
    a = random2(seed) * 2 - vec2(1, 1);
    n = a[0] * a[0] + a[1] * a[1];
  } while(n >= 1);

However, I find that this causes the GPU to hang and the program crashes. When I comment out the loop, everything works as normal. Is there a reason why this loop causes the GPU to hang? It shouldn't be an infinite loop as there is a $\frac{\pi}{4}$ chance for a random point to be in the circle, which is more than 75%.

wenzhi-guo commented 8 months ago

One thing you can try is to implement this short piece somewhere else where you can get the output of each iteration can see if you what you get. It's also possible to implement the sampling function without a loop (as certain loops could cause issues in shaders).

MstrPikachu commented 8 months ago

Is it possible to test it out in glsl? I tried it in other programming languages and it seems to work fine. If not I will do it without a loop.

MstrPikachu commented 8 months ago

I realized that random2 does not actually generate a sequence of random numbers based on a seed, it is more like a hash function. I tried a basic way of perturbing the seed every loop iteration but it isn't very robust and the GPU will hang sometimes. I recommend others to not use rejection sampling.