Skip to content

Instantly share code, notes, and snippets.

@riicchhaarrd
Created February 10, 2021 10:40
Show Gist options
  • Select an option

  • Save riicchhaarrd/6480e09f06073d212cb2423c40f3f38d to your computer and use it in GitHub Desktop.

Select an option

Save riicchhaarrd/6480e09f06073d212cb2423c40f3f38d to your computer and use it in GitHub Desktop.
glow sphere
#include <stdio.h>
#include <math.h>
#include <vector>
#include <stdint.h>
#include <time.h>
typedef uint8_t u8;
struct vec3
{
float x,y,z;
};
float dot(const vec3& a, const vec3& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
vec3 subv(const vec3& a, const vec3& b)
{
return vec3 {
a.x - b.x,
a.y - b.y,
a.z - b.z
};
}
float len(const vec3& v)
{
return sqrtf(dot(v,v));
}
vec3 unit(const vec3& v)
{
float l = len(v);
return vec3 {
v.x / l,
v.y / l,
v.z / l
};
}
float dot_n(const vec3& a, const vec3& b)
{
return dot(a,b) / len(a) * len(b);
}
float dist(const vec3& a, const vec3& b)
{
return len(subv(a,b));
}
float clamp(float v)
{
if(v > 1.f)
return 1.f;
if(v < 0.f)
return 0.f;
return v;
}
//rgb (3 bytes * w * h)
using buffer = std::vector<u8>;
void write_image(const buffer& buf, int w, int h)
{
FILE *fp = fopen("test.ppm", "wb");
if(!fp) return;
fprintf(fp, "P3\n%d %d\n255\n", w, h);
for(int x = 0; x < w; x++)
{
for(int y = 0; y < h; y++)
{
int index = (y * w) + x;
fprintf(fp, "%d %d %d\n", buf[index], buf[index+1], buf[index+2]);
}
}
fclose(fp);
}
int main()
{
srand(time(0));
buffer buf;
vec3 light { 0,1,0 };
int w = 512;
int h = 512;
buf.resize(w*h*3);
vec3 mid { w/2,h/2,0 };
for(int x = 0; x < w; x++)
{
for(int y = 0; y < h; y++)
{
int index = (y * w) + x;
vec3 pos { x, y, 0};
vec3 dir = subv(pos, mid);
float s = 1.f;
s -= (dot(dir, dir) / dot(mid, mid));
//s -= sin(dir.x) * cos(dir.y);
s = pow(s,16);
s *= 255.f;
while(s<0.f)
s+=255.f;
while(s>255.f)
s-=255.f;
//printf("s = %f\n", s);
for(int i = 0; i < 3; ++i)
buf[index + i] = s;
}
}
write_image(buf, w, h);
printf("len = %f\n", len(vec3{1,1,0}));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment