Advertisement
Guest User

Untitled

a guest
Feb 27th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <climits>
  3. #include <bitset>
  4. #include <utility>
  5. #include <vector>
  6. #include <cmath>
  7.  
  8. struct vec3
  9. {
  10.   float x;
  11.   float y;
  12.   float z;
  13. };
  14.  
  15. void normalize(vec3 &vert)
  16. {
  17.   float mag = sqrt(pow(vert.x, 2) + pow(vert.y, 2) + pow(vert.z, 2));
  18.   vert.x = vert.x / mag;
  19.   vert.y = vert.y / mag;
  20.   vert.z = vert.z / mag;
  21. }
  22.  
  23. vec3 cross(const vec3 &a, const vec3 &b)
  24. {
  25.   vec3 res{};
  26.   res.x = a.y * b.z - a.z * b.y;
  27.   res.y = a.z * b.x - a.x * b.z;
  28.   res.z = a.x * b.y - a.y * b.x;
  29.   return res;
  30. }
  31.  
  32. vec3 &operator+=(vec3 &a, const vec3 &b)
  33. {
  34.   a.x += b.x;
  35.   a.y += b.y;
  36.   a.z += b.z;
  37.   return a;
  38. }
  39.  
  40. vec3 operator-(const vec3 &a, const vec3 &b)
  41. {
  42.   return {a.x - b.x, a.y - b.y, a.z - b.z};
  43. }
  44.  
  45. void calc_mesh_normals(vec3 *normals, const vec3 *verts, const int *faces, int nverts, int nfaces)
  46. {
  47.   for (int i = 0; i < nverts; i++)
  48.   {
  49.     normals[i] = {0, 0, 0};
  50.   }
  51.   for (int j = 1; j < nfaces - 1; j++)
  52.   {
  53.     auto p = cross(verts[faces[j - 1]] - verts[faces[j]], verts[faces[j + 1]] - verts[faces[j - 1]]);
  54.     normals[faces[j - 1]] += p;
  55.     normals[faces[j]] += p;
  56.     normals[faces[j + 1]] += p;
  57.   }
  58.   for (int i = 0; i < nverts; i++)
  59.   {
  60.     normalize(normals[i]);
  61.   }
  62. }
  63.  
  64. int main()
  65. {
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement