Advertisement
nbonneel

template class Vector

Jan 5th, 2022
1,163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <vector>
  3.  
  4. #define STB_IMAGE_WRITE_IMPLEMENTATION
  5. #include "stb_image_write.h"
  6.  
  7. #define STB_IMAGE_IMPLEMENTATION
  8. #include "stb_image.h"
  9.  
  10. class Vector {
  11. public:
  12.     explicit Vector(double x = 0, double y = 0, double z = 0) {
  13.         data[0] = x;
  14.         data[1] = y;
  15.         data[2] = z;
  16.     }
  17.     double norm2() const {
  18.         return data[0] * data[0] + data[1] * data[1] + data[2] * data[2];
  19.     }
  20.     double norm() const {
  21.         return sqrt(norm2());
  22.     }
  23.     void normalize() {
  24.         double n = norm();
  25.         data[0] /= n;
  26.         data[1] /= n;
  27.         data[2] /= n;
  28.     }
  29.     double operator[](int i) const { return data[i]; };
  30.     double& operator[](int i) { return data[i]; };
  31.     double data[3];
  32. };
  33.  
  34. Vector operator+(const Vector& a, const Vector& b) {
  35.     return Vector(a[0] + b[0], a[1] + b[1], a[2] + b[2]);
  36. }
  37. Vector operator-(const Vector& a, const Vector& b) {
  38.     return Vector(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
  39. }
  40. Vector operator*(const double a, const Vector& b) {
  41.     return Vector(a*b[0], a*b[1], a*b[2]);
  42. }
  43. Vector operator*(const Vector& a, const double b) {
  44.     return Vector(a[0]*b, a[1]*b, a[2]*b);
  45. }
  46. Vector operator/(const Vector& a, const double b) {
  47.     return Vector(a[0] / b, a[1] / b, a[2] / b);
  48. }
  49. double dot(const Vector& a, const Vector& b) {
  50.     return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  51. }
  52. Vector cross(const Vector& a, const Vector& b) {
  53.     return Vector(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]);
  54. }
  55.  
  56. class Sphere {
  57. public:
  58.     // ...
  59. };
  60.  
  61. class Ray {
  62. public:
  63.     // ...
  64. };
  65.  
  66. int main() {
  67.     int W = 512;
  68.     int H = 512;
  69.  
  70.     std::vector<unsigned char> image(W * H * 3, 0);
  71.     for (int i = 0; i < H; i++) {
  72.         for (int j = 0; j < W; j++) {
  73.  
  74.             image[(i * W + j) * 3 + 0] = 255;
  75.             image[(i * W + j) * 3 + 1] = 0;
  76.             image[(i * W + j) * 3 + 2] = 0;
  77.         }
  78.     }
  79.     stbi_write_png("image.png", W, H, 3, &image[0], 0);
  80.  
  81.     return 0;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement