Advertisement
cutecoder

Vector macros in C

Sep 12th, 2023
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.77 KB | Source Code | 0 0
  1. #define ASSERT(a, msg) do { if(!(a)) fprintf(stderr, "%s:%s:%d - %s\n", __FILE__, __FUNCTION__, __LINE__, (msg)); } while(0)
  2.  
  3. typedef struct vector2i {
  4.     int32_t x, y;
  5. } Vec2i;
  6.  
  7. typedef struct small_vector2i {
  8.     int16_t x, y;
  9. } sVec2i;
  10.  
  11. typedef struct vector2f {
  12.     float x, y;
  13. } Vec2f;
  14.  
  15. #define vec_neg(a) ({ \
  16.     __auto_type _a = (a); \
  17.     (typeof(_a)) { -_a.x, -_a.y }; \
  18. })
  19.  
  20. #define vec_add(a, b) ({ \
  21.     __auto_type _a = (a); \
  22.     __auto_type _b = (b); \
  23.     (typeof(_a)) { _a.x + _b.x, _a.y + _b.y }; \
  24. })
  25.  
  26. #define vec_sub(a, b) ({ \
  27.     __auto_type _a = (a); \
  28.     __auto_type _b = (b); \
  29.     (typeof(_a)) { _a.x - _b.x, _a.y - _b.y }; \
  30. })
  31.  
  32. #define vec_dot(a, b) ({ \
  33.     __auto_type _a = (a); \
  34.     __auto_type _b = (b); \
  35.     _Generic(_a, \
  36.         sVec2i: (int32_t) _a.x * (int32_t) _b.x + (int32_t) _a.y * (int32_t) _b.y, \
  37.         Vec2i: (int64_t) _a.x * (int64_t) _b.x + (int64_t) _a.y * (int64_t) _b.y, \
  38.         default: _a.x * _b.x + _a.y * _b.y); \
  39. })
  40.  
  41. #define vec_scale(a, f) ({ \
  42.     __auto_type _a = (a); \
  43.     float _f = (f); \
  44.     (typeof(_a)) { (typeof(_a.x)) ((float) _a.x * _f), (typeof(_a.y)) ((float) _a.y * _f) }; \
  45. })
  46.  
  47. #define vec_normalize(a) ({ \
  48.     __auto_type _a = (a); \
  49.     ASSERT(_Generic(_a, \
  50.         Vec2f: 1, \
  51.         default: 0), "bad type for normalize"); \
  52.     const float invSqrt = 1.0f / sqrtf(_a.x * _a.x + _a.y * _a.y); \
  53.     (Vec2f) { _a.x * invSqrt, _a.y * invSqrt }; \
  54. })
  55.  
  56. #define vec_dist_sq(a, b) ({ \
  57.     __auto_type _a = (a); \
  58.     __auto_type _b = (b); \
  59.     typeof(_a) _delta = { _a.x - _b.x, _a.y - _b.y }; \
  60.     _Generic(_delta, \
  61.         sVec2i: (int32_t) _delta.x * (int32_t) _delta.x + (int32_t) _delta.y * (int32_t) _delta.y, \
  62.         Vec2i: (int64_t) _delta.x * (int64_t) _delta.x + (int64_t) _delta.y * (int64_t) _delta.y, \
  63.         default: _delta.x * _delta.x + _delta.y * _delta.y); \
  64. })
  65.  
Tags: math vector
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement