Inaccuracy with screenX / screenY?
in
Programming Questions
•
1 year ago
I've been trying to make a general Ray Marcher in Processing and everything was going just fine until I realized my sketch didn't have perspective. In the code below, I left this (commented out):
- pixels[i+j*width] = (steps<<16)+(steps<<8)+steps;
This is how to draw "flattened" spheres which basically end up having the properties of circles but are shaded. I decided to use screenX / screenY to draw the spheres in 3D space and it almost works. The weird thing is that a sphere that is behind another sphere sometimes gets drawn in front. I can't figure out what's going wrong, at the moment my guess is that I'm either using screenX / screenY wrong or that they are not perfect in flattening 3D space.
One other problem is that the spheres look perfect (no visual artifacts) with "i+j*width" but are noisy with "px+py*width" Any help would be appreciated, here's the code so far:
- float minThreshold = 0.0001;
- int maxDepth = 800;
- void setup() {
- size(800, 600, P3D);
- noLoop();
- }
- void draw() {
- background(0);
- loadPixels();
- for (int i = 0; i < width; i++) {
- for (int j = 0; j < height; j++) {
- float ray = 0;
- int steps = 255;
- while (steps > 0 && ray < maxDepth) {
- float currDist = sqrt(sq(i-400)+sq(j-200)+sq(ray-200))-100;
- float currDist2 = sqrt(sq(i-400)+sq(j-300)+sq(ray-400))-100;
- float smallestDist = currDist;
- if (currDist2 < currDist) smallestDist = currDist2;
- if (smallestDist*0.5 < minThreshold) {
- int px = round(screenX(i, j, -ray));
- int py = round(screenY(i, j, -ray));
- if (px > 0 && px < width && py > 0 && py < height) {
- pixels[px+py*width] = (steps<<16)+(steps<<8)+steps;
- //pixels[i+j*width] = (steps<<16)+(steps<<8)+steps;
- }
- break;
- }
- else {
- ray += smallestDist*0.5;
- steps--;
- }
- }
- }
- }
- updatePixels();
- }
1