Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //-std=c99 -Wall -Wextra -Wpedantic -Wshadow
- //linker -lm
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdbool.h>
- #include <math.h>
- #include <float.h> //DBL_EPSILON
- typedef struct{
- double x;
- double y;
- double z;
- }Vector3;
- typedef struct{
- double x;
- double y;
- double z;
- }Point3;
- void printVector(Vector3 v)
- {
- printf("%f %f %f\n", v.x, v.y, v.z);
- }
- bool isVectAlmZero(Vector3 v)
- {
- //if(fabs(v.x) > DBL_EPSILON || fabs(v.y) > DBL_EPSILON || fabs(v.z) > DBL_EPSILON) return false;
- //return true;
- return !(fabs(v.x) > DBL_EPSILON || fabs(v.y) > DBL_EPSILON || fabs(v.z) > DBL_EPSILON);
- }
- Vector3 normalizeVec3(Vector3 v)
- {
- Vector3 retVec;
- double length = sqrt((v.x * v.x) + (v.y * v.y) + (v.z * v.z));
- retVec.x = v.x / length;
- retVec.y = v.y / length;
- retVec.z = v.z / length;
- return retVec;
- }
- //normal of triangle surface
- Vector3 triangleSurfaceNormal(Point3 a, Point3 b, Point3 c)
- {
- Vector3 retVec;
- Vector3 edge1;
- Vector3 edge2;
- edge1.x = b.x - a.x;
- edge1.y = b.y - a.y;
- edge1.z = b.z - a.z;
- edge2.x = c.x - a.x;
- edge2.y = c.y - a.y;
- edge2.z = c.z - a.z;
- //cross product
- retVec.x = edge1.y * edge2.z - edge1.z * edge2.y;
- retVec.y = edge1.z * edge2.x - edge1.x * edge2.z;
- retVec.z = edge1.x * edge2.y - edge1.y * edge2.x;
- return retVec;
- }
- int main (int argc, char **argv)
- {
- Point3 tstP1 = {0.0,0.0,0.0};
- Point3 tstP2 = {0.5,0.0,0.0};
- Point3 tstP3 = {0.5,0.5,0.0};
- Vector3 resultV;
- printf("CW: ");
- //CW, clockwise
- resultV = triangleSurfaceNormal(tstP1,tstP2,tstP3);
- printVector(resultV);
- if(isVectAlmZero(resultV))
- {
- printf("error: zero vector cannot be normalized.\n");
- return 1;
- }
- printf("CW (normalized): ");
- printVector(normalizeVec3(resultV));
- printf("CCW: ");
- //CCW, counter-clockwise
- resultV = triangleSurfaceNormal(tstP1,tstP3,tstP2);
- printVector(resultV);
- if(isVectAlmZero(resultV))
- {
- printf("error: zero vector cannot be normalized.\n");
- return 1;
- }
- printf("CCW (normalized): ");
- printVector(normalizeVec3(resultV));
- printf("\n");
- return 0;
- }
- /*
- output:
- CW: 0.000000 0.000000 0.250000
- CW (normalized): 0.000000 0.000000 1.000000
- CCW: 0.000000 0.000000 -0.250000
- CCW (normalized): 0.000000 0.000000 -1.000000
- */
Advertisement
Add Comment
Please, Sign In to add comment