raytracer.c


SUBMITTED BY: okpalan86

DATE: Dec. 28, 2022, 7:14 p.m.

UPDATED: Dec. 28, 2022, 7:25 p.m.

FORMAT: C++

SIZE: 10.1 kB

HITS: 1004

  1. #include <cstdlib>
  2. #include <cstdio>
  3. #include <cmath>
  4. #include <fstream>
  5. #include <vector>
  6. #include <iostream>
  7. #include <cassert>
  8. #if defined __linux__ || defined __APPLE__
  9. // "Compiled for Linux
  10. #else
  11. // Windows doesn't define these values by default, Linux does
  12. #define M_PI 3.141592653589793
  13. #define INFINITY 1e8
  14. #endif
  15. template<typename T>
  16. class Vec3
  17. {
  18. public:
  19. T x, y, z;
  20. Vec3() : x(T(0)), y(T(0)), z(T(0)) {}
  21. Vec3(T xx) : x(xx), y(xx), z(xx) {}
  22. Vec3(T xx, T yy, T zz) : x(xx), y(yy), z(zz) {}
  23. Vec3& normalize()
  24. {
  25. T nor2 = length2();
  26. if (nor2 > 0) {
  27. T invNor = 1 / sqrt(nor2);
  28. x *= invNor, y *= invNor, z *= invNor;
  29. }
  30. return *this;
  31. }
  32. Vec3<T> operator * (const T &f) const { return Vec3<T>(x * f, y * f, z * f); }
  33. Vec3<T> operator * (const Vec3<T> &v) const { return Vec3<T>(x * v.x, y * v.y, z * v.z); }
  34. T dot(const Vec3<T> &v) const { return x * v.x + y * v.y + z * v.z; }
  35. Vec3<T> operator - (const Vec3<T> &v) const { return Vec3<T>(x - v.x, y - v.y, z - v.z); }
  36. Vec3<T> operator + (const Vec3<T> &v) const { return Vec3<T>(x + v.x, y + v.y, z + v.z); }
  37. Vec3<T>& operator += (const Vec3<T> &v) { x += v.x, y += v.y, z += v.z; return *this; }
  38. Vec3<T>& operator *= (const Vec3<T> &v) { x *= v.x, y *= v.y, z *= v.z; return *this; }
  39. Vec3<T> operator - () const { return Vec3<T>(-x, -y, -z); }
  40. T length2() const { return x * x + y * y + z * z; }
  41. T length() const { return sqrt(length2()); }
  42. friend std::ostream & operator << (std::ostream &os, const Vec3<T> &v)
  43. {
  44. os << "[" << v.x << " " << v.y << " " << v.z << "]";
  45. return os;
  46. }
  47. };
  48. typedef Vec3<float> Vec3f;
  49. class Sphere
  50. {
  51. public:
  52. Vec3f center; /// position of the sphere
  53. float radius, radius2; /// sphere radius and radius^2
  54. Vec3f surfaceColor, emissionColor; /// surface color and emission (light)
  55. float transparency, reflection; /// surface transparency and reflectivity
  56. Sphere(
  57. const Vec3f &c,
  58. const float &r,
  59. const Vec3f &sc,
  60. const float &refl = 0,
  61. const float &transp = 0,
  62. const Vec3f &ec = 0) :
  63. center(c), radius(r), radius2(r * r), surfaceColor(sc), emissionColor(ec),
  64. transparency(transp), reflection(refl)
  65. { /* empty */ }
  66. bool intersect(const Vec3f &rayorig, const Vec3f &raydir, float &t0, float &t1) const
  67. {
  68. Vec3f l = center - rayorig;
  69. float tca = l.dot(raydir);
  70. if (tca < 0) return false;
  71. float d2 = l.dot(l) - tca * tca;
  72. if (d2 > radius2) return false;
  73. float thc = sqrt(radius2 - d2);
  74. t0 = tca - thc;
  75. t1 = tca + thc;
  76. return true;
  77. }
  78. };
  79. // control depth recursion
  80. #define MAX_RAY_DEPTH 5
  81. float mix(const float &a, const float &b, const float &mix)
  82. {
  83. return b * mix + a * (1 - mix);
  84. }
  85. //This is the main trace function. It takes a ray as argument (defined by its origin and direction). We test if this ray intersects any of the geometry in the scene. If the ray intersects an object, we compute the intersection point, the normal at the intersection point, and shade this point using this information. Shading depends on the surface property (is it transparent, reflective, diffuse). The function returns a color for the ray. If the ray intersects an object that is the color of the object at the intersection point, otherwise it returns the background color.
  86. Vec3f trace(
  87. const Vec3f &rayorig,
  88. const Vec3f &raydir,
  89. const std::vector<Sphere> &spheres,
  90. const int &depth)
  91. {
  92. //if (raydir.length() != 1) std::cerr << "Error " << raydir << std::endl;
  93. float tnear = INFINITY;
  94. const Sphere* sphere = NULL;
  95. // find intersection of this ray with the sphere in the scene
  96. for (unsigned i = 0; i < spheres.size(); ++i) {
  97. float t0 = INFINITY, t1 = INFINITY;
  98. if (spheres[i].intersect(rayorig, raydir, t0, t1)) {
  99. if (t0 < 0) t0 = t1;
  100. if (t0 < tnear) {
  101. tnear = t0;
  102. sphere = &spheres[i];
  103. }
  104. }
  105. }
  106. // if there's no intersection return black or background color
  107. if (!sphere) return Vec3f(2);
  108. Vec3f surfaceColor = 0; // color of the ray/surfaceof the object intersected by the ray
  109. Vec3f phit = rayorig + raydir * tnear; // point of intersection
  110. Vec3f nhit = phit - sphere->center; // normal at the intersection point
  111. nhit.normalize(); // normalize normal direction
  112. // If the normal and the view direction are not opposite to each other
  113. // reverse the normal direction. That also means we are inside the sphere so set
  114. // the inside bool to true. Finally reverse the sign of IdotN which we want
  115. // positive.
  116. float bias = 1e-4; // add some bias to the point from which we will be tracing
  117. bool inside = false;
  118. if (raydir.dot(nhit) > 0) nhit = -nhit, inside = true;
  119. if ((sphere->transparency > 0 || sphere->reflection > 0) && depth < MAX_RAY_DEPTH) {
  120. float facingratio = -raydir.dot(nhit);
  121. // change the mix value to tweak the effect
  122. float fresneleffect = mix(pow(1 - facingratio, 3), 1, 0.1);
  123. // compute reflection direction (not need to normalize because all vectors
  124. // are already normalized)
  125. Vec3f refldir = raydir - nhit * 2 * raydir.dot(nhit);
  126. refldir.normalize();
  127. Vec3f reflection = trace(phit + nhit * bias, refldir, spheres, depth + 1);
  128. Vec3f refraction = 0;
  129. // if the sphere is also transparent compute refraction ray (transmission)
  130. if (sphere->transparency) {
  131. float ior = 1.1, eta = (inside) ? ior : 1 / ior; // are we inside or outside the surface?
  132. float cosi = -nhit.dot(raydir);
  133. float k = 1 - eta * eta * (1 - cosi * cosi);
  134. Vec3f refrdir = raydir * eta + nhit * (eta * cosi - sqrt(k));
  135. refrdir.normalize();
  136. refraction = trace(phit - nhit * bias, refrdir, spheres, depth + 1);
  137. }
  138. // the result is a mix of reflection and refraction (if the sphere is transparent)
  139. surfaceColor = (
  140. reflection * fresneleffect +
  141. refraction * (1 - fresneleffect) * sphere->transparency) * sphere->surfaceColor;
  142. }
  143. else {
  144. // it's a diffuse object, no need to raytrace any further
  145. for (unsigned i = 0; i < spheres.size(); ++i) {
  146. if (spheres[i].emissionColor.x > 0) {
  147. // this is a light
  148. Vec3f transmission = 1;
  149. Vec3f lightDirection = spheres[i].center - phit;
  150. lightDirection.normalize();
  151. for (unsigned j = 0; j < spheres.size(); ++j) {
  152. if (i != j) {
  153. float t0, t1;
  154. if (spheres[j].intersect(phit + nhit * bias, lightDirection, t0, t1)) {
  155. transmission = 0;
  156. break;
  157. }
  158. }
  159. }
  160. surfaceColor += sphere->surfaceColor * transmission *
  161. std::max(float(0), nhit.dot(lightDirection)) * spheres[i].emissionColor;
  162. }
  163. }
  164. }
  165. return surfaceColor + sphere->emissionColor;
  166. }
  167. void render(const std::vector<Sphere> &spheres)
  168. {
  169. unsigned width = 640, height = 480;
  170. Vec3f *image = new Vec3f[width * height], *pixel = image;
  171. float invWidth = 1 / float(width), invHeight = 1 / float(height);
  172. float fov = 30, aspectratio = width / float(height);
  173. float angle = tan(M_PI * 0.5 * fov / 180.);
  174. // Trace rays
  175. for (unsigned y = 0; y < height; ++y) {
  176. for (unsigned x = 0; x < width; ++x, ++pixel) {
  177. float xx = (2 * ((x + 0.5) * invWidth) - 1) * angle * aspectratio;
  178. float yy = (1 - 2 * ((y + 0.5) * invHeight)) * angle;
  179. Vec3f raydir(xx, yy, -1);
  180. raydir.normalize();
  181. *pixel = trace(Vec3f(0), raydir, spheres, 0);
  182. }
  183. }
  184. // Save result to a PPM image (keep these flags if you compile under Windows)
  185. std::ofstream ofs("./untitled.ppm", std::ios::out | std::ios::binary);
  186. ofs << "P6\n" << width << " " << height << "\n255\n";
  187. for (unsigned i = 0; i < width * height; ++i) {
  188. ofs << (unsigned char)(std::min(float(1), image[i].x) * 255) <<
  189. (unsigned char)(std::min(float(1), image[i].y) * 255) <<
  190. (unsigned char)(std::min(float(1), image[i].z) * 255);
  191. }
  192. ofs.close();
  193. delete [] image;
  194. }
  195. // In the main function, we will create the scene which is composed of 5 spheres and 1 light (which is also a sphere). Then, once the scene description is complete we render that scene, by calling the render() function.
  196. int main(int argc, char **argv)
  197. {
  198. srand48(13);
  199. std::vector<Sphere> spheres;
  200. // position, radius, surface color, reflectivity, transparency, emission color
  201. spheres.push_back(Sphere(Vec3f( 0.0, -10004, -20), 10000, Vec3f(0.20, 0.20, 0.20), 0, 0.0));
  202. spheres.push_back(Sphere(Vec3f( 0.0, 0, -20), 4, Vec3f(1.00, 0.32, 0.36), 1, 0.5));
  203. spheres.push_back(Sphere(Vec3f( 5.0, -1, -15), 2, Vec3f(0.90, 0.76, 0.46), 1, 0.0));
  204. spheres.push_back(Sphere(Vec3f( 5.0, 0, -25), 3, Vec3f(0.65, 0.77, 0.97), 1, 0.0));
  205. spheres.push_back(Sphere(Vec3f(-5.5, 0, -15), 3, Vec3f(0.90, 0.90, 0.90), 1, 0.0));
  206. // light
  207. spheres.push_back(Sphere(Vec3f( 0.0, 20, -30), 3, Vec3f(0.00, 0.00, 0.00), 0, 0.0, Vec3f(3)));
  208. render(spheres);
  209. return 0;
  210. }
  211. // how to compile and run the program
  212. // g++ -O3 -fopenmp -o raytracer raytracer.cpp
  213. // ./raytracer

comments powered by Disqus