1 /*
2     Inochi2D Math helpers
3 
4     Copyright © 2020, Inochi2D Project
5     Distributed under the 2-Clause BSD License, see LICENSE file.
6     
7     Authors: Luna Nielsen
8 */
9 module inochi2d.math;
10 import gl3n.util;
11 public import gl3n.linalg;
12 public import gl3n.math;
13 public import std.math : isNaN;
14 public import gl3n.interpolate;
15 
16 public import inochi2d.math.transform;
17 public import inochi2d.math.camera;
18 
19 // Unsigned int vectors
20 alias vec2u = Vector!(uint, 2); /// ditto
21 alias vec3u = Vector!(uint, 3); /// ditto
22 alias vec4u = Vector!(uint, 4); /// ditto
23 
24 // Unsigned short vectors
25 alias vec2us = Vector!(ushort, 2); /// ditto
26 alias vec3us = Vector!(ushort, 3); /// ditto
27 alias vec4us = Vector!(ushort, 4); /// ditto
28 
29 /**
30     Smoothly dampens from a position to a target
31 */
32 V dampen(V)(V pos, V target, double delta, double speed = 1) if(is_vector!V) {
33     return (pos - target) * pow(0.001, delta*speed) + target;
34 }
35 
36 /**
37     Smoothly dampens from a position to a target
38 */
39 float dampen(float pos, float target, double delta, double speed = 1) {
40     return (pos - target) * pow(0.001, delta*speed) + target;
41 }
42 
43 /**
44     Gets whether a point is within an axis aligned rectangle
45 */
46 bool contains(vec4 a, vec2 b) {
47     return  b.x >= a.x && 
48             b.y >= a.y &&
49             b.x <= a.x+a.z &&
50             b.y <= a.y+a.w;
51 }
52 
53 /**
54     Checks if 2 lines segments are intersecting
55 */
56 bool areLineSegmentsIntersecting(vec2 p1, vec2 p2, vec2 p3, vec2 p4) {
57     float epsilon = 0.00001f;
58     float demoninator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
59     if (demoninator == 0) return false;
60 
61     float uA = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / demoninator;
62     float uB = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / demoninator;
63     return (uA > 0+epsilon && uA < 1-epsilon && uB > 0+epsilon && uB < 1-epsilon);
64 }