I'm trying to make a basic ray tracer in C, and decided to use a .tga
file as the output render file. But for whatever reason, the file that gets created shows as being solid white in every tga file viewer I can find. The start of the hexdump for the file I write to is here, and it seems pretty clear that large swaths of the image should be black.
The loop that writes to the file is:
void raycast(uint16_t width, uint16_t height, FILE* file, Sphere* sphere) {
Vec3* camera = makeVec3(0, 0, 0);
Vec3* light = makeVec3(1, -1, -1);
int count = 0;
double zMax = 1 / cos(toRads(vFOV) / 2.0);
double yMax = 1 / cos(toRads(hFOV) / 2.0);
for (uint16_t i = 0; i < height; i++) {
for (uint16_t j = 0; j < width; j++) {
int16_t zOffset = (height / 2 - i);
double zprop = zOffset / (height / 2.0);
double zCoord = zMax * zprop;
int16_t yOffset = (width / 2 - j);
double yprop = yOffset / (width / 2.0);
double yCoord = yMax * yprop;
Vec3* coord = makeVec3(1, yCoord, zCoord);
normalize(coord);
Ray* ray = makeRay(camera, coord);
Vec3* intersect = sphereIntersect(sphere, ray);
if (intersect == NULL) {
fputc(255, file);
fputc(255, file);
fputc(255, file);
} else {
printf("disp black\n");
fputc(0x00, file);
fputc(0x00, file);
fputc(0x00, file);
count++;
}
}
}
printf("%d\n", count);
}
and I'm seeing disp black
get printed to the console, and count
gets incremented to over 300,000, so there's clearly nothing wrong with writing the zeros to the file. I tried my best to follow the header format that I found here, is there a problem with that?
I also noticed that the image is a solid color of whatever I put in the if
block, as though if
statement is always taken.
EDIT: Code that writes the header
static void writeHeader(FILE* file) {
static uint16_t width = 800;
static uint16_t height = 600;
// 800x600 image, 24 bits per pixel
unsigned char header[18] = {
0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x00, 0x00,
(unsigned char)(width & 0x00FF), (unsigned char)((width & 0xFF00) / 256),
(unsigned char)(height & 0x00FF), (unsigned char)((height & 0xFF00) / 256),
0x08, 0x00
};
fwrite(header, sizeof(char), 18, file);
}