Skip to content

Instantly share code, notes, and snippets.

@harieamjari
Last active November 8, 2020 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harieamjari/4fb0f876af8e191dd3e7421c5de47712 to your computer and use it in GitHub Desktop.
Save harieamjari/4fb0f876af8e191dd3e7421c5de47712 to your computer and use it in GitHub Desktop.
Simple raytracer in C
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <png.h>
#include <assert.h>
int width, height;
int main(int argc, char *argv[]){
if (argc != 4) {printf("usage: %s Pz c r\n", argv[0]); return 1;}
width = 1000, height = 1000;
FILE *fp = fopen("t.png", "wb");
assert(fp!=NULL);
png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
assert(png);
png_infop info = png_create_info_struct(png);
assert(info);
assert(!setjmp(png_jmpbuf(png)));
png_init_io(png, fp);
png_set_IHDR(
png,
info,
width, height,
8,
PNG_COLOR_TYPE_RGBA,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
png_write_info(png, info);
png_bytep *row = NULL;
row = malloc(sizeof(png_bytep)*height);
assert(row!=NULL);
for (int y = 0; y < height; y++){
row[y] = malloc(sizeof(png_bytep)*width);
assert(row[y]!=NULL);
}
for (int y = 0; y < height; y++){
png_bytep line = row[y];
for (int x = 0; x < width; x++){
double Px = x-500, Py = y-500, Pz = atof(argv[1]), c = atof(argv[2]), r = atof(argv[3]);
double delta = pow(2.0*Pz*c, 2.0)-((Px*Px+Py*Py+Pz*Pz)*(c*c-r*r));
if (delta>0.0)
{*(line+(x*4)+0)=0xFF;*(line+(x*4)+1)=0xFF;*(line+(x*4)+2)=0xFF;*(line+(x*4)+3)=0xFF;}
else if (delta<0.0)
{*(line+(x*4)+0)=0x00;*(line+(x*4)+1)=0x00;*(line+(x*4)+2)=0x00;*(line+(x*4)+3)=0xFF;}
if (delta==0.0)
{*(line+(x*4)+0)=0xFF;*(line+(x*4)+1)=0xFF;*(line+(x*4)+2)=0xFF;*(line+(x*4)+3)=0xFF;}
/*
double t_star_pos = ((2.0*Pz*c)+sqrt(delta))/(2.0*(Px*Px+Py*Py+Pz*Pz));
double t_star_neg = ((2.0*Pz*c)-sqrt(delta))/(2.0*(Px*Px+Py*Py+Pz*Pz));
printf("%lf %lf\n", t_star_pos, t_star_neg);
*/
}
}
png_write_image(png, row);
png_write_end(png, NULL);
for (int y = 0; y < height; y++) free(row[y]);
free(row);
fclose(fp);
png_destroy_write_struct(&png, &info);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment