Advertisement
Guest User

Vec example

a guest
Oct 9th, 2016
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 0.94 KB | None | 0 0
  1. import std.stdio;
  2.  
  3. struct Vec(size_t dim) {
  4.   float[dim] data;
  5.  
  6.   //forward all unsupported operations to data
  7.   alias data this;
  8.  
  9.   //operate over variadic arguments as if they were an array
  10.   //at the same time, restrict the amount of arguments to dim
  11.   this(float[dim] floats...) {
  12.     data[] = floats;
  13.   }
  14.  
  15.   auto crossProduct(ref Vec!dim other) {
  16.     static if (dim == 2) {
  17.       return data[0]*other[1] - data[1]*other[0];
  18.     }
  19.     else static if (dim == 3) {
  20.       return Vec!dim(data[1]*other[2] - data[2]*other[1],
  21.                      data[2]*other[0] - data[0]*other[2],
  22.                      data[0]*other[1] - data[1]*other[0]);
  23.     }
  24.     else static assert (0, "Not implemented");
  25.   }
  26. }
  27.  
  28. void main() {
  29.   Vec!2 xy1 = Vec!2(1, 2),     xy2 = Vec!2(3, 4);
  30.   Vec!3 xyz1 = Vec!3(5, 6, 7), xyz2 = Vec!3(8, 9, 10);
  31.  
  32.   float res1 = xy1.crossProduct(xy2);
  33.   Vec!3 res2 = xyz1.crossProduct(xyz2);
  34.  
  35.   writeln(res1, " | ", res2);
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement