1 module gfm.math.vector;
2 
3 import std.traits,
4        std.math,
5        std.conv,
6        std.array,
7        std..string;
8 
9 import gfm.math.funcs;
10 
11 /**
12  * Generic 1D small vector.
13  * Params:
14  *    N = number of elements
15  *    T = type of elements
16  */
17 struct Vector(T, int N)
18 {
19 nothrow:
20     public
21     {
22         static assert(N >= 1);
23 
24         // fields definition
25         union
26         {
27             T[N] v;
28             struct
29             {
30                 static if (N >= 1)
31                 {
32                     T x;
33                     alias x r;
34                 }
35                 static if (N >= 2)
36                 {
37                     T y;
38                     alias y g;
39                 }
40                 static if (N >= 3)
41                 {
42                     T z;
43                     alias z b;
44                 }
45                 static if (N >= 4)
46                 {
47                     T w;
48                     alias w a;
49                 }
50             }
51         }
52 
53         @nogc this(Args...)(Args args) pure nothrow
54         {
55             static if (args.length == 1)
56             {
57                 // Construct a Vector from a single value.
58                 opAssign!(Args[0])(args[0]);
59             }
60             else
61             {
62                 int argumentCount;
63 
64                 foreach(arg; args)
65                 {
66                     static if(is(typeof(arg._isVector)))
67                         argumentCount += arg._N;
68                     else
69                         argumentCount += 1;
70                 }
71 
72                 assert(argumentCount <= N, "Too many arguments in vector constructor");
73 
74                 int index = 0;
75                 foreach(arg; args)
76                 {
77                     static if (isAssignable!(T, typeof(arg)))
78                     {
79                         v[index] = arg;
80                         index++; // has to be on its own line (DMD 2.068)
81                     }
82                     else static if (is(typeof(arg._isVector)) && isAssignable!(T, arg._T))
83                     {
84                         mixin(generateLoopCode!("v[index + @] = arg[@];", arg._N)());
85                         index += arg._N;
86                     }
87                     else
88                         static assert(false, "Unrecognized argument in Vector constructor");
89                 }
90                 assert(index == N, "Bad arguments in Vector constructor");
91             }
92         }
93 
94         /// Assign a Vector from a compatible type.
95         @nogc ref Vector opAssign(U)(U x) pure nothrow if (isAssignable!(T, U))
96         {
97             mixin(generateLoopCode!("v[@] = x;", N)()); // copy to each component
98             return this;
99         }
100 
101         /// Assign a Vector with a static array type.
102         @nogc ref Vector opAssign(U)(U arr) pure nothrow if ((isStaticArray!(U) && isAssignable!(T, typeof(arr[0])) && (arr.length == N)))
103         {
104             mixin(generateLoopCode!("v[@] = arr[@];", N)());
105             return this;
106         }
107 
108         /// Assign with a dynamic array.
109         /// Size is checked in debug-mode.
110         @nogc ref Vector opAssign(U)(U arr) pure nothrow if (isDynamicArray!(U) && isAssignable!(T, typeof(arr[0])))
111         {
112             assert(arr.length == N);
113             mixin(generateLoopCode!("v[@] = arr[@];", N)());
114             return this;
115         }
116 
117         /// Assign from a samey Vector.
118         @nogc ref Vector opAssign(U)(U u) pure nothrow if (is(U : Vector))
119         {
120             v[] = u.v[];
121             return this;
122         }
123 
124         /// Assign from other vectors types (same size, compatible type).
125         @nogc ref Vector opAssign(U)(U x) pure nothrow if (is(typeof(U._isVector))
126                                                        && isAssignable!(T, U._T)
127                                                        && (!is(U: Vector))
128                                                        && (U._N == _N))
129         {
130             mixin(generateLoopCode!("v[@] = x.v[@];", N)());
131             return this;
132         }
133 
134         /// Returns: a pointer to content.
135         @nogc inout(T)* ptr() pure inout nothrow @property
136         {
137             return v.ptr;
138         }
139 
140         /// Converts to a pretty string.
141         string toString() const nothrow
142         {
143             try
144                 return format("%s", v);
145             catch (Exception e)
146                 assert(false); // should not happen since format is right
147         }
148 
149         @nogc bool opEquals(U)(U other) pure const nothrow
150             if (is(U : Vector))
151         {
152             for (int i = 0; i < N; ++i)
153             {
154                 if (v[i] != other.v[i])
155                 {
156                     return false;
157                 }
158             }
159             return true;
160         }
161 
162         @nogc bool opEquals(U)(U other) pure const nothrow
163             if (isConvertible!U)
164         {
165             Vector conv = other;
166             return opEquals(conv);
167         }
168 
169         @nogc Vector opUnary(string op)() pure const nothrow
170             if (op == "+" || op == "-" || op == "~" || op == "!")
171         {
172             Vector res = void;
173             mixin(generateLoopCode!("res.v[@] = " ~ op ~ " v[@];", N)());
174             return res;
175         }
176 
177         @nogc ref Vector opOpAssign(string op, U)(U operand) pure nothrow
178             if (is(U : Vector))
179         {
180             mixin(generateLoopCode!("v[@] " ~ op ~ "= operand.v[@];", N)());
181             return this;
182         }
183 
184         @nogc ref Vector opOpAssign(string op, U)(U operand) pure nothrow if (isConvertible!U)
185         {
186             Vector conv = operand;
187             return opOpAssign!op(conv);
188         }
189 
190         @nogc Vector opBinary(string op, U)(U operand) pure const nothrow
191             if (is(U: Vector) || (isConvertible!U))
192         {
193             Vector result = void;
194             static if (is(U: T))
195                 mixin(generateLoopCode!("result.v[@] = cast(T)(v[@] " ~ op ~ " operand);", N)());
196             else
197             {
198                 Vector other = operand;
199                 mixin(generateLoopCode!("result.v[@] = cast(T)(v[@] " ~ op ~ " other.v[@]);", N)());
200             }
201             return result;
202         }
203 
204         @nogc Vector opBinaryRight(string op, U)(U operand) pure const nothrow if (isConvertible!U)
205         {
206             Vector result = void;
207             static if (is(U: T))
208                 mixin(generateLoopCode!("result.v[@] = cast(T)(operand " ~ op ~ " v[@]);", N)());
209             else
210             {
211                 Vector other = operand;
212                 mixin(generateLoopCode!("result.v[@] = cast(T)(other.v[@] " ~ op ~ " v[@]);", N)());
213             }
214             return result;
215         }
216 
217         @nogc ref T opIndex(size_t i) pure nothrow
218         {
219             return v[i];
220         }
221 
222         @nogc ref const(T) opIndex(size_t i) pure const nothrow
223         {
224             return v[i];
225         }
226 
227         @nogc T opIndexAssign(U : T)(U x, size_t i) pure nothrow
228         {
229             return v[i] = x;
230         }
231 
232 
233         /// Implements swizzling.
234         ///
235         /// Example:
236         /// ---
237         /// vec4i vi = [4, 1, 83, 10];
238         /// assert(vi.zxxyw == [83, 4, 4, 1, 10]);
239         /// ---
240         @nogc @property auto opDispatch(string op, U = void)() pure const nothrow if (isValidSwizzle!(op))
241         {
242             alias Vector!(T, op.length) returnType;
243             returnType res = void;
244             enum indexTuple = swizzleTuple!op;
245             foreach(i, index; indexTuple)
246                 res.v[i] = v[index];
247             return res;
248         }
249 
250         /// Support swizzling assignment like in shader languages.
251         ///
252         /// Example:
253         /// ---
254         /// vec3f v = [0, 1, 2];
255         /// v.yz = v.zx;
256         /// assert(v == [0, 2, 0]);
257         /// ---
258         @nogc @property void opDispatch(string op, U)(U x) pure
259             if ((op.length >= 2)
260                 && (isValidSwizzleUnique!op)                   // v.xyy will be rejected
261                 && is(typeof(Vector!(T, op.length)(x)))) // can be converted to a small vector of the right size
262         {
263             Vector!(T, op.length) conv = x;
264             enum indexTuple = swizzleTuple!op;
265             foreach(i, index; indexTuple)
266                 v[index] = conv[i];
267         }
268 
269         /// Casting to small vectors of the same size.
270         /// Example:
271         /// ---
272         /// vec4f vf;
273         /// vec4d vd = cast!(vec4d)vf;
274         /// ---
275         @nogc U opCast(U)() pure const nothrow if (is(typeof(U._isVector)) && (U._N == _N))
276         {
277             U res = void;
278             mixin(generateLoopCode!("res.v[@] = cast(U._T)v[@];", N)());
279             return res;
280         }
281 
282         /// Implement slices operator overloading.
283         /// Allows to go back to slice world.
284         /// Returns: length.
285         @nogc int opDollar() pure const nothrow
286         {
287             return N;
288         }
289 
290         /// Returns: a slice which covers the whole Vector.
291         @nogc T[] opSlice() pure nothrow
292         {
293             return v[];
294         }
295 
296         // vec[a..b]
297         @nogc T[] opSlice(int a, int b) pure nothrow
298         {
299             return v[a..b];
300         }
301 
302         /// Returns: squared length.
303         @nogc T squaredLength() pure const nothrow
304         {
305             T sumSquares = 0;
306             mixin(generateLoopCode!("sumSquares += v[@] * v[@];", N)());
307             return sumSquares;
308         }
309 
310         // Returns: squared Euclidean distance.
311         @nogc T squaredDistanceTo(Vector v) pure const nothrow
312         {
313             return (v - this).squaredLength();
314         }
315 
316         static if (isFloatingPoint!T)
317         {
318             /// Returns: Euclidean length
319             @nogc T length() pure const nothrow
320             {
321                 return sqrt(squaredLength());
322             }
323 
324             /// Returns: Inverse of Euclidean length.
325             @nogc T inverseLength() pure const nothrow
326             {
327                 return 1 / sqrt(squaredLength());
328             }
329 
330             /// Faster but less accurate inverse of Euclidean length.
331             /// Returns: Inverse of Euclidean length.
332             @nogc T fastInverseLength() pure const nothrow
333             {
334                 return inverseSqrt(squaredLength());
335             }
336 
337             /// Returns: Euclidean distance between this and other.
338             @nogc T distanceTo(Vector other) pure const nothrow
339             {
340                 return (other - this).length();
341             }
342 
343             /// In-place normalization.
344             @nogc void normalize() pure nothrow
345             {
346                 auto invLength = inverseLength();
347                 mixin(generateLoopCode!("v[@] *= invLength;", N)());
348             }
349 
350             /// Returns: Normalized vector.
351             @nogc Vector normalized() pure const nothrow
352             {
353                 Vector res = this;
354                 res.normalize();
355                 return res;
356             }
357 
358             /// Faster but less accurate in-place normalization.
359             @nogc void fastNormalize() pure nothrow
360             {
361                 auto invLength = fastInverseLength();
362                 mixin(generateLoopCode!("v[@] *= invLength;", N)());
363             }
364 
365             /// Faster but less accurate vector normalization.
366             /// Returns: Normalized vector.
367             @nogc Vector fastNormalized() pure const nothrow
368             {
369                 Vector res = this;
370                 res.fastNormalize();
371                 return res;
372             }
373 
374             static if (N == 3)
375             {
376                 /// Gets an orthogonal vector from a 3-dimensional vector.
377                 /// Doesn’t normalise the output.
378                 /// Authors: Sam Hocevar
379                 /// See_also: Source at $(WEB lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts).
380                 @nogc Vector getOrthogonalVector() pure const nothrow
381                 {
382                     return abs(x) > abs(z) ? Vector(-y, x, 0.0) : Vector(0.0, -z, y);
383                 }
384             }
385         }
386     }
387 
388     private
389     {
390         enum _isVector = true; // do we really need this? I don't know.
391 
392         enum _N = N;
393         alias T _T;
394 
395         // define types that can be converted to this, but are not the same type
396         template isConvertible(T)
397         {
398             enum bool isConvertible = (!is(T : Vector))
399             && is(typeof(
400                 {
401                     T x;
402                     Vector v = x;
403                 }()));
404         }
405 
406         // define types that can't be converted to this
407         template isForeign(T)
408         {
409             enum bool isForeign = (!isConvertible!T) && (!is(T: Vector));
410         }
411 
412         template isValidSwizzle(string op, int lastSwizzleClass = -1)
413         {
414             static if (op.length == 0)
415                 enum bool isValidSwizzle = true;
416             else
417             {
418                 enum len = op.length;
419                 enum int swizzleClass = swizzleClassify!(op[0]);
420                 enum bool swizzleClassValid = (lastSwizzleClass == -1 || (swizzleClass == lastSwizzleClass));
421                 enum bool isValidSwizzle = (swizzleIndex!(op[0]) != -1)
422                                          && swizzleClassValid
423                                          && isValidSwizzle!(op[1..len], swizzleClass);
424             }
425         }
426 
427         template searchElement(char c, string s)
428         {
429             static if (s.length == 0)
430             {
431                 enum bool result = false;
432             }
433             else
434             {
435                 enum string tail = s[1..s.length];
436                 enum bool result = (s[0] == c) || searchElement!(c, tail).result;
437             }
438         }
439 
440         template hasNoDuplicates(string s)
441         {
442             static if (s.length == 1)
443             {
444                 enum bool result = true;
445             }
446             else
447             {
448                 enum tail = s[1..s.length];
449                 enum bool result = !(searchElement!(s[0], tail).result) && hasNoDuplicates!(tail).result;
450             }
451         }
452 
453         // true if the swizzle has at the maximum one time each letter
454         template isValidSwizzleUnique(string op)
455         {
456             static if (isValidSwizzle!op)
457                 enum isValidSwizzleUnique = hasNoDuplicates!op.result;
458             else
459                 enum bool isValidSwizzleUnique = false;
460         }
461 
462         template swizzleIndex(char c)
463         {
464             static if((c == 'x' || c == 'r') && N >= 1)
465                 enum swizzleIndex = 0;
466             else static if((c == 'y' || c == 'g') && N >= 2)
467                 enum swizzleIndex = 1;
468             else static if((c == 'z' || c == 'b') && N >= 3)
469                 enum swizzleIndex = 2;
470             else static if ((c == 'w' || c == 'a') && N >= 4)
471                 enum swizzleIndex = 3;
472             else
473                 enum swizzleIndex = -1;
474         }
475 
476         template swizzleClassify(char c)
477         {
478             static if(c == 'x' || c == 'y' || c == 'z' || c == 'w')
479                 enum swizzleClassify = 0;
480             else static if(c == 'r' || c == 'g' || c == 'b' || c == 'a')
481                 enum swizzleClassify = 1;
482             else
483                 enum swizzleClassify = -1;
484         }
485 
486         template swizzleTuple(string op)
487         {
488             enum opLength = op.length;
489             static if (op.length == 0)
490                 enum swizzleTuple = [];
491             else
492                 enum swizzleTuple = [ swizzleIndex!(op[0]) ] ~ swizzleTuple!(op[1..op.length]);
493         }
494     }
495 }
496 
497 private string definePostfixAliases(string type)
498 {
499     return "alias " ~ type ~ "!byte "   ~ type ~ "b;\n"
500          ~ "alias " ~ type ~ "!ubyte "  ~ type ~ "ub;\n"
501          ~ "alias " ~ type ~ "!short "  ~ type ~ "s;\n"
502          ~ "alias " ~ type ~ "!ushort " ~ type ~ "us;\n"
503          ~ "alias " ~ type ~ "!int "    ~ type ~ "i;\n"
504          ~ "alias " ~ type ~ "!uint "   ~ type ~ "ui;\n"
505          ~ "alias " ~ type ~ "!long "   ~ type ~ "l;\n"
506          ~ "alias " ~ type ~ "!ulong "  ~ type ~ "ul;\n"
507          ~ "alias " ~ type ~ "!float "  ~ type ~ "f;\n"
508          ~ "alias " ~ type ~ "!double " ~ type ~ "d;\n";
509 }
510 
511 template vec2(T) { alias Vector!(T, 2) vec2; }
512 template vec3(T) { alias Vector!(T, 3) vec3; }
513 template vec4(T) { alias Vector!(T, 4) vec4; }
514 
515 mixin(definePostfixAliases("vec2"));
516 mixin(definePostfixAliases("vec3"));
517 mixin(definePostfixAliases("vec4"));
518 
519 
520 private
521 {
522     static string generateLoopCode(string formatString, int N)() pure nothrow
523     {
524         string result;
525         for (int i = 0; i < N; ++i)
526         {
527             string index = ctIntToString(i);
528             // replace all @ by indices
529             result ~= formatString.replace("@", index);
530         }
531         return result;
532     }
533 
534     // Speed-up CTFE conversions
535     static string ctIntToString(int n) pure nothrow
536     {
537         static immutable string[16] table = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
538         if (n < 10)
539             return table[n];
540         else
541             return to!string(n);
542     }
543 }
544 
545 
546 /// Element-wise minimum.
547 deprecated("use minByElem instead") alias min = minByElem;
548 @nogc Vector!(T, N) minByElem(T, int N)(const Vector!(T, N) a, const Vector!(T, N) b) pure nothrow
549 {
550     import std.algorithm: min;
551     Vector!(T, N) res = void;
552     mixin(generateLoopCode!("res.v[@] = min(a.v[@], b.v[@]);", N)());
553     return res;
554 }
555 
556 /// Element-wise maximum.
557 deprecated("use maxByElem instead") alias max = maxByElem;
558 @nogc Vector!(T, N) maxByElem(T, int N)(const Vector!(T, N) a, const Vector!(T, N) b) pure nothrow
559 {
560     import std.algorithm: max;
561     Vector!(T, N) res = void;
562     mixin(generateLoopCode!("res.v[@] = max(a.v[@], b.v[@]);", N)());
563     return res;
564 }
565 
566 /// Returns: Dot product.
567 @nogc T dot(T, int N)(const Vector!(T, N) a, const Vector!(T, N) b) pure nothrow
568 {
569     T sum = 0;
570     mixin(generateLoopCode!("sum += a.v[@] * b.v[@];", N)());
571     return sum;
572 }
573 
574 /// Returns: 3D cross product.
575 /// Thanks to vuaru for corrections.
576 @nogc Vector!(T, 3) cross(T)(const Vector!(T, 3) a, const Vector!(T, 3) b) pure nothrow
577 {
578     return Vector!(T, 3)(a.y * b.z - a.z * b.y,
579                          a.z * b.x - a.x * b.z,
580                          a.x * b.y - a.y * b.x);
581 }
582 
583 /// 3D reflect, like the GLSL function.
584 /// Returns: a reflected by normal b.
585 @nogc Vector!(T, 3) reflect(T)(const Vector!(T, 3) a, const Vector!(T, 3) b) pure nothrow
586 {
587     return a - (2 * dot(b, a)) * b;
588 }
589 
590 
591 /// Returns: angle between vectors.
592 /// See_also: "The Right Way to Calculate Stuff" at $(WEB www.plunk.org/~hatch/rightway.php)
593 @nogc T angleBetween(T, int N)(const Vector!(T, N) a, const Vector!(T, N) b) pure nothrow
594 {
595     auto aN = a.normalized();
596     auto bN = b.normalized();
597     auto dp = dot(aN, bN);
598 
599     if (dp < 0)
600         return PI - 2 * asin((-bN-aN).length / 2);
601     else
602         return 2 * asin((bN-aN).length / 2);
603 }
604 
605 static assert(vec2f.sizeof == 8);
606 static assert(vec3d.sizeof == 24);
607 static assert(vec4i.sizeof == 16);
608 
609 
610 unittest
611 {
612     static assert(vec2i.isValidSwizzle!"xyx");
613     static assert(!vec2i.isValidSwizzle!"xyz");
614     static assert(vec4i.isValidSwizzle!"brra");
615     static assert(!vec4i.isValidSwizzle!"rgyz");
616     static assert(vec2i.isValidSwizzleUnique!"xy");
617     static assert(vec2i.isValidSwizzleUnique!"yx");
618     static assert(!vec2i.isValidSwizzleUnique!"xx");
619 
620     assert(vec2l(0, 1) == vec2i(0, 1));
621 
622     int[2] arr = [0, 1];
623     int[] arr2 = new int[2];
624     arr2[] = arr[];
625     vec2i a = vec2i([0, 1]);
626     vec2i a2 = vec2i(0, 1);
627     immutable vec2i b = vec2i(0);
628     assert(b[0] == 0 && b[1] == 0);
629     vec2i c = arr;
630     vec2l d = arr2;
631     assert(a == a2);
632     assert(a == c);
633     assert(vec2l(a) == vec2l(a));
634     assert(vec2l(a) == d);
635 
636     vec4i x = [4, 5, 6, 7];
637     assert(x == x);
638     --x[0];
639     assert(x[0] == 3);
640     ++x[0];
641     assert(x[0] == 4);
642     x[1] &= 1;
643     x[2] = 77 + x[2];
644     x[3] += 3;
645     assert(x == [4, 1, 83, 10]);
646     assert(x.xxywz == [4, 4, 1, 10, 83]);
647     assert(x.xxxxxxx == [4, 4, 4, 4, 4, 4, 4]);
648     assert(x.abgr == [10, 83, 1, 4]);
649     assert(a != b);
650     x = vec4i(x.xyz, 166);
651     assert(x == [4, 1, 83, 166]);
652 
653     vec2l e = a;
654     vec2l f = a + b;
655     assert(f == vec2l(a));
656 
657     vec3ui g = vec3i(78,9,4);
658     g ^= vec3i(78,9,4);
659     assert(g == vec3ui(0));
660     //g[0..2] = 1u;
661     //assert(g == [2, 1, 0]);
662 
663     assert(vec2i(4, 5) + 1 == vec2i(5,6));
664     assert(vec2i(4, 5) - 1 == vec2i(3,4));
665     assert(1 + vec2i(4, 5) == vec2i(5,6));
666     assert(vec3f(1,1,1) * 0 == 0);
667     assert(1.0 * vec3d(4,5,6) == vec3f(4,5.0f,6.0));
668 
669     auto dx = vec2i(1,2);
670     auto dy = vec2i(4,5);
671     auto dp = dot(dx, dy);
672     assert(dp == 14 );
673 
674     vec3i h = cast(vec3i)(vec3d(0.5, 1.1, -2.2));
675     assert(h == [0, 1, -2]);
676     assert(h[] == [0, 1, -2]);
677     assert(h[1..3] == [1, -2]);
678     assert(h.zyx == [-2, 1, 0]);
679 
680     h.yx = vec2i(5, 2); // swizzle assignment
681 
682     assert(h.xy == [2, 5]);
683     assert(-h[1] == -5);
684     assert(++h[0] == 3);
685 
686     //assert(h == [-2, 1, 0]);
687     assert(!__traits(compiles, h.xx = h.yy));
688     vec4ub j;
689 
690     assert(lerp(vec2f(-10, -1), vec2f(10, 1), 0.5) == vec2f(0, 0));
691 
692     // vectors of user-defined types
693     import gfm.math.half;
694     alias Vector!(half, 2) vec2h;
695     vec2h k = vec2h(1.0f, 2.0f);
696 
697     // larger vectors
698     alias Vector!(float, 5) vec5f;
699     vec5f l = vec5f(1, 2.0f, 3.0, k.x.toFloat(), 5.0L);
700     l = vec5f(l.xyz, vec2i(1, 2));
701 
702     // too many arguments to ctor
703     import core.exception: AssertError;
704     import std.exception: assertThrown;
705     assertThrown!AssertError(vec2f(1, 2, 3));
706     assertThrown!AssertError(vec2f(vec2f(1, 2), 3));
707 }
708