I'm following the book Ray Tracing in on Weekend in which the author produces a small Ray Tracer using plain C++ and the result is a PPM image.
The author's code
Which produces this PPM image.
So the author suggests as an exercise to make it so the program produces a JPG image via the stb_image library. So far I tried by changing the original code like this :
#include <fstream>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
struct RGB{
unsigned char R;
unsigned char G;
unsigned char B;
};
int main(){
int nx = 200;
int ny = 100;
struct RGB data[nx][ny];
for(int j = ny - 1 ; j >= 0 ; j-- ){
for(int i = 0; i < nx ; i++){
float r = float(i) / float(nx);
float g = float(j) / float(ny);
float b = 0.2;
int ir = int(255.99 * r);
int ig = int(255.99 * g);
int ib = int(255.99 * b);
data[i][j].R = ir;
data[i][j].G = ig;
data[i][j].B = ib;
}
}
stbi_write_jpg("image.jpg", nx, ny, 3, data, 100);
}
And this is the result:
As you can see my result is slightly different and I don't know why. The main problems are:
That the black color shows at the top left of the screen, and in general the colors don't show in the correct order left to right, top to bottom.
The image is "split" in half and the result is actually the original image of the author but produced in a pair ????
Probably I'm misunderstanding something about the way STB_IMAGE_WRITE is supposed to be used so if anyone experienced with this library can tell me what's going on I would be grateful.
EDIT 1 I implemented the changes suggested by @1201ProgramAlarm in comments plus I changed struct RGB data[nx][ny]
to struct RGB data[ny][nx]
,so the result now is this.
The library should be working as intended. The problem is how you give the data and what you should do is invert the y axis. So, when you are at index 4 from the start, you should give the color of the index 4 from the end.
Taking the result from your edit, just change the line:
float g = float(j) / float(ny);
to
float g = float(ny - 1 - j) / float(ny);