2/24/2019 1 PA199 Advanced Game Design Lecture 2 Mathematics for Game Design Dr. Fotis Liarokapis 25th February 2019 Basis and Coordinate Systems • In any scene, we need a way to be able to position and orientate points, vectors, objects, etc: – We do this be defining a basis • The basis is defined by an origin and a number of basis vectors – Can think of the basis as a ‘starting point’ • We employ a Cartesian basis Basis and Coordinate Systems . • The basis vectors are mutually orthogonal and unit length – Unit length: • Have a length of 1 – Mutually Orthogonal: • Each vector is at a right angle to the others • Basis vectors for 3 dimensions – Use ‘x’ and ‘y’ for 2 dimensions – Position in Cartesian coordinates specified by (x, y, z) Left-handed vs. Right-Handed Y X Z X Y Z left handed right handed Z axis goes "into" the page Z axis goes "out" of the page OpenGL is right handed in object space and world space But in window space (screen space) left handed Local Coordinate System • Preferred system for construction of object parts • 3D Cartesian system • Object vertices centered about the local origin Y X Z 3D World Coordinate System • 3D Cartesian coordinate system • Arbitrary centre, handedness and orientation • Used in the construction stage Y X Z Y X Z Y X Z 2/24/2019 2 Camera Coordinate System • Used to define the view onto the 3D world that the user will see on the screen • Centre (0,0,0) is located at the Imaginary User’s eye • Axes oriented such that: – One indicates the direction in which the user looks – The second indicates roughly the ‘up’ direction – The third indicates the handedness Example of Camera Coordinate System Y X Z U V N DIRECTION VECTOR { 0, 0, 0} UP VECTOROpenGL: see gluLookAt https://www.opengl.org/sdk/docs/man2/xhtml/gluLookAt.xml 3D Camera Viewing • Note that the following scenes should produce the same image • In ‘Scene 2’, relative position of objects and camera remain constant but the actually scene has been changed – It has been transformed SCENE 2SCENE 1 Notation: Scalars, Vectors, Matrices • Scalar – Lower case, italic • Vector – Lower case, bold • Matrix – Upper case, bold a  naaa ...21a            333231 232221 131211 aaa aaa aaa A Vectors • A quantity characterized by a magnitude and direction – Can be represented by an arrow, where magnitude is the length of the arrow and the direction is given by slope of the line        1 2 v 2 1 Y X A vector in 2D 2 2 2 Y X Z            2 2 2 v A vector in 3D Vectors in 3D Co-ordinates                        5.0 7.0 5.0 5.0 7.0 5.0 v RHS LHS 2/24/2019 3 Vector Subtraction u -v u -v -v Can be seen as an addition of u + (-1v) vuvu                    2 4 2 5 4 1 Vector Magnitude • The magnitude or “norm” of a vector of dimension n is given by the standard Euclidean distance metric: 222 21 n vvv  v Vectors for Direction • Vectors represent – Direction – Magnitude • In games can be used for representing: – Position – Velocity – Forces / impulses Example Vectors for Direction • Describing velocity (direction and speed) of roller coaster and ball at different points in time Other Vectors DRAG THRUST LIFT GRAVITY Vertices and Points • Vectors can however communicate a position • Referred to as a point or vertex • A vertex is actually represented by its displacement from the origin { 0, 0, 0 }              y x y x v v v v Pv both vectors equal With the origin O, we can use this to represent a unique position in space 2/24/2019 4 Unit Vectors • Vectors of length 1 are often termed unit vectors – Normalised vectors • When we only wish to describe direction we use normalised vectors – Often to avoid redundancy • For this (and other reasons), we often need to normalise a vector: v v v v 222 21 1 ˆ n vvv    Dot Product Definition • Dot product (inner product) is defined as:  i iivuvu 332211 3 2 1 3 2 1 vuvuvu v v v u u u                      vu 2211 2 1 2 1 vuvu v v u u             vu Dot Product Magnitude • Therefore we can redefine magnitude in terms of the dot-product operator: • Note that the dot product operator is commutative and associative – Changing the order of the operands does not change the result – (x * y) * z = x * (y * z) 22 3 2 2 2 1 uuu  uuu uuu  Dot Product Using Angle • The Dot Product can also be obtained from the following equation: • where q is the angle between the two vectors u qqcosvuvu  Angle Between Two Vectors • So, if we know the vectors u and v, then the dot product is useful for finding the angle between two vectors: • Note that if we had already normalised the vectors u and v then it would simply be:            vu vu vuvu 1 coscos qq  vu ˆˆcos 1   q Dot Product Special Case • If both vectors are normal, the dot product defines the cosine of the angle between the vectors:             vu vu vuvu 1 cos cos q q qcosvu But in general: if q > 90 then the dot product is negative 2/24/2019 5 Projection Using Dot Product • Can find length of projection of u onto v • As lines become perpendicular: qcosvuvu  u v q qcosuv vu u  qcos Cross Product • Used for defining orientation and constructing co-ordinate axes • Cross product defined as: • The result is a vector, perpendicular to the plane defined by u and v:                                     1221 3113 2332 3 2 1 3 2 1 vuvu vuvu vuvu v v v u u u vu qsinvuwvu  Cross Product Examples Right Handed Coordinate System Cross Product Properties • Cross product is anti-commutative: • It is not associative: • Direction of resulting vector defined by operand order:  uvvu      wvuwvu  Vector Class class TVector { public: double _x, _y, _z; // Constructors TVector(double x, double y, double z, TStatus s) : _x(x), _y(y), _z(z), _Status(s) {} TVector(double x, double y, double z) : _x(x), _y(y), _z(z), _Status(DEFAULT) {} // Functions here }; #endif Vector Subtraction Example TVector &TVector::subtract(const TVector &v1, const TVector &v2, TVector &result) { if (v1.isValid() && v2.isValid()) { result._x = v1._x - v2._x; result._y = v1._y - v2._y; result._z = v1._z - v2._z; result._Status = DEFAULT; } else result = TVector(); return result; } 2/24/2019 6 What is a Matrix? • A matrix is a set of elements, organized into rows (m) and columns (n)             mnmmm n n aaaa aaaa aaaa    321 2232221 1131211 Columns, j = 1, …, n Rows, i = 1, …, m Why Use Matrices? • Variety of engineering problems lead to the need to solve systems of linear equations bAx              mnmmm n n aaaa aaaa aaaa    321 2232221 1131211 A              mb b b  2 1 b              nx x x  2 1 x matrix column vectors Row and Column Matrices (vectors) • Row matrix (or row vector) is a matrix with one row • Column vector is a matrix with only one column  nrrrr 321r              mc c c  2 1 c Square Matrix • When the row and column dimensions of a matrix are equal (m = n) then the matrix is called square              nnnn n n aaa aaa aaa    21 22221 11211 A Matrix Transpose • The transpose of the (m x n) matrix A is the (n x m) matrix formed by interchanging the rows and columns such that row i becomes column i of the transposed matrix              mnnn m m T aaa aaa aaa    21 22212 12111 A              mnmm n n aaa aaa aaa    21 22221 11211 A Matrix Equality • Two (m x n) matrices A and B are equal if and only if each of their elements are equal • That is when: – A = B • If and only if: – aij = bij – For i = 1,...,m & j = 1,...,n 2/24/2019 7 Matrix Addition General Format                                                 mnmnmmmm nn nn mnmm n n mnmm n n bababa bababa bababa bbb bbb bbb aaa aaa aaa          2211 2222222121 1112121111 21 22221 11211 21 22221 11211 BA Scalar Matrix Multiplication • Multiplication of a matrix A by a scalar is defined as:              mnmm n n aaa aaa aaa        21 22221 11211 A Matrix Multiplication with Matrix General Format                                                pnmpnmpmpmpmpm pnpnpppp pnpnpppp pnpp n n mpmm p p babababababa babababababa babababababa bbb bbb bbb aaa aaa aaa =           1121211111 2121221221121121 1111211211111111 21 12221 11211 21 12221 11211 ABC kj p k ikij bac  1 Diagonal Matrices • Simple diagonal Matrix              nna a a 000 000 000 000 22 11  A Identity Matrix • The identity matrix has the property that if A is a square matrix, then: AAIIA               1000 0100 0010 0001 I Matrix Inverse • If A is an (n x n) square matrix and there is a matrix X with the property that: • X is defined to be the inverse of A and is denoted A-1 IAX  IAA 1  IAA 1  2/24/2019 8 Matrix Class class TMatrix33 { public: double _Mx[3][3]; // Constructors TMatrix33(); TMatrix33(double Phi, double Theta, double Psi); TMatrix33(TVector& Axis,double Psi); // Functions here }; #endif Matrix Addition TMatrix33 &TMatrix33::add(const TMatrix33 &m1, const TMatrix33 &m2, TMatrix33 &result) { result._Mx[0][0] = m1._Mx[0][0] + m2._Mx[0][0]; result._Mx[0][1] = m1._Mx[0][1] + m2._Mx[0][1]; result._Mx[0][2] = m1._Mx[0][2] + m2._Mx[0][2]; result._Mx[1][0] = m1._Mx[1][0] + m2._Mx[1][0]; result._Mx[1][1] = m1._Mx[1][1] + m2._Mx[1][1]; result._Mx[1][2] = m1._Mx[1][2] + m2._Mx[1][2]; result._Mx[2][0] = m1._Mx[2][0] + m2._Mx[2][0]; result._Mx[2][1] = m1._Mx[2][1] + m2._Mx[2][1]; result._Mx[2][2] = m1._Mx[2][2] + m2._Mx[2][2]; return result; } Transformations • Allow us to move, orientate and change the primitives in our scene – Move, Rotate, Stretch, Squash, Shear • Represented as matrices, such as: – We can store a translation and a rotation in a matrix – When we apply this matrix to an object, it will be translated and rotated as specified by the matrix • Two ways of understanding a transformation: – Object Transformation – Coordinate Transformation Object vs Coordinate Transformations • Object Transformation – Alters the coordinates of each point according to some rule – The underlying coordinate system remains unchanged • Coordinate Transformation – Produces a different coordinate system – Then represents all original points in this new system Examples {1,1} {.4, 2} {1,1} {1,1} Object Transformation Coordinate Transformation Affine Transformations Definition • An affine transformation is any transformation that preserves: – Collinearity • i.e. All points lying on a line initially still lie on a line after transformation – Ratios of distances • i.e. The midpoint of a line segment remains the midpoint after transformation 2/24/2019 9 Elementary Transformations Translation Scaling Rotation Shearing Homogeneous Coordinates • Introduced in mathematics: – For projections and drawings – Used in artillery, architecture – Used to be classified material (in the 1850s) • Add a third coordinate, w • A 2D point is a 3 coordinates vector: x y w           Homogeneous Coordinates . • Two points are equal if and only if: – x’/w’ = x/w and y’/w’= y/w • w=0: points at infinity – Useful for projections and curve drawing • Homogenize = divide by w • Homogenized points: x y 1           Translations with Homogeneous x y w            1 0 tx 0 1 ty 0 0 1           x y w           x y w        x  wtx y wty w x w y w   x w tx y w ty    Scaling with Homogeneous x y w            sx 0 0 0 sy 0 0 0 1           x y w           x y w        sxx syy w x w y w   sx x w sy y w    Rotation with Homogeneous x y w            cosq sinq 0 sinq cosq 0 0 0 1           x y w           x y w        cosqx sinqy sinqx cosqy w x w y w   cosq x w sinq y w sinq x w cosq y w    2/24/2019 10 Composition of Transformations • To compose transformations, multiply the matrices: – Composition of a rotation and a translation: M = RT • All transformations can be expressed as matrices – Even transformations that are not translations, rotations and scaling Rotation Around a Point Q • Rotation about a point Q: – translate Q to origin (TQ), – rotate about origin (RQ) – translate back to Q (- TQ). P’=(-TQ)RQTQ P Beware! • Matrix multiplication is not commutative • The order of the transformations is vital – Rotation followed by translation is very different from translation followed by rotation – Careful with the order of the matrices! • Small commutativity: – Rotation commute with rotation, translation with translation… Matrices in OpenGL • To initialise a matrix in OpenGL: – glLoadIdentity() – This clears the currently selected OpenGL matrix to the identity matrix • To select a matrix as the current matrix: – glMatrixMode(mode) • GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE How do we do this ? • OpenGL does most of it for us ! – OpenGL keeps a current matrix that allows us to orientate our primitives • This is known as the model-view matrix – All primitives placed are altered by the transformation stored in the model-view matrix – Model-view matrix acts as a state parameter; once set it remains until altered • Use calls such as glTranslate() to modify the current model-view matrix Translation • Think of translations as ‘moving’ without rotating • Translation only applies to points – Doesn’t apply to vectors, since vectors are just directions • The translation displacement is written in the 12th, 13th, and 14th positions of our OpenGL matrix • These correspond to the displacements in the x, y and z directions – So 12th position is the translation in the x direction Translate along y axis 2/24/2019 11 The Translation Matrix • Example: Translate the point (x,y,z) by a displacement (a,b,c): – Gives us our translated point (x+a, y+b, z+c) • glTranslate(dx, dy, dz) – Translates by a displacement (dx, dy, dz) – Calling glTranslate() concatenates the specified translation to the current model-view matrix – Any primitives drawn after this will be modified by the specified translation Rotation • Change the orientation of a primitive, without affecting its position • Rotation applies to both points and vectors – Rotating a vector will change its direction • Rotations are conducted anti-clockwise about the origin rotation of 45o about the Z axis Rotation • Remember: Sin a = Opp / Hyp Cos a = Adj / Hyp Tan a = Opp / Adj Rotation • Derivation: • Expanding (a + b) from log tables: – Rotated x = r cos a cos b – r sin a sin b – Rotated y = r cos a sin b + r sin a cos b • But: – Original x = r cos a – Original y = r sin a • So: – Rotated x = original x cos b – original y sin b – Rotated y = original x sin b + original y cos b • Elements 0, 1, 2, 4, 5, 6, 8, 9, 10 define any rotations in our transformation matrix The Rotation Matrix • Rotations around the: x-axis (Rx), y-axis (Ry) and z-axis (Rz) • glRotatef(angle, vx, vy, vz) – Rotates around the axis (vx, vy, vz) by angle degrees – Calling glRotate() concatenates the specified rotate to the current model-view matrix – Any primitives drawn after this will be modified by the specified rotation Scaling • Allows us to make primitives larger and smaller, without changing the vertex positions of the original • Elements 1, 6, 11 define scales in our transformation matrix: • glScalef(sx, sy, sz) – Scale a scene by sx in the y axis, sy in the y axis and sz in the z axis – The default value for sx,sy,sz is (1.0,1.0,1.0), which doesn’t scale a scene at all – Any primitives drawn after this will be modified by the specified scaling Original scale all axes scale Y axis 2/24/2019 12 OpenGL Perspective Projection • The call glFrustum(l, r, b, t, n, f) generates R, where: • R is defined as long as l x r, t x b, and n x f OpenGL Orthographic Projection • The call glOrtho(l, r, b, t, n, f ) generates R, where: • R is defined as long as l x r, t x b, and n x f 2D and 3D Lines • In 2D, two different lines can either be – Parallel, meaning they never meet – May intersect at one and only one point • In 3D (or more dimensions), lines may also be skew (meaning they don't meet) but also don't define a plane • Two distinct planes intersect in at most one line • Three or more points that lie on the same line are called collinear 2D Line Equation • Lines in a Cartesian plane can be described algebraically by – Linear equations and functions • In 2D the characteristic equation is often given by the slopeintercept form: y = mx + b • where: – m is the slope of the line – b is the y-intercept of the line – x is the independent variable of the function y Slope Definition • Slope is often used to describe the measurement of the steepness, incline, gradient, or grade of a straight line – A higher slope value indicates a steeper incline • The slope is defined as the ratio of the altitude change to the horizontal distance between any two points on the line – Using calculus, one can calculate the slope of the tangent to a curve at a point Slope Calculation • Slope is defined as the change in the y coordinate divided by the corresponding change in the x coordinate, between two distinct points on the line • Given two points (x1, y1) and (x2, y2), the change in x from one to the other is x2 - x1, while the change in y is y2 - y1 2/24/2019 13 Slope Special Cases • The larger the absolute value of a slope, the steeper the line – A horizontal line has slope 0 • Note that a vertical line's slope is undefined – A 45° rising line has a slope of +1 – A 45° falling line has a slope of -1 • The angle θ a line makes with the positive x axis is closely related to the slope m via the tangent function: Slope Special Cases . • Two lines are parallel if and only if – Their slopes are equal and they are not coincident or if – They both are vertical and therefore have undefined slopes • Two lines are perpendicular if and only if – The product of their slopes is -1 or – One has a slope of 0 (a horizontal line) and the other has an undefined slope (a vertical line) Derivative • By moving the two points closer together Δy and Δx decreases – The line more closely approximates a tangent line to the curve – The slope of the secant approaches that of the tangent • If y is dependent on x, then it is sufficient to take the limit where only Δx approaches zero • Therefore, the slope of the tangent is the limit of Δy/Δx as Δx approaches zero Differentiation and the Derivative • Differentiation is a method to compute the rate at which a quantity, y, changes with respect to the change in another quantity, x, upon which it is dependent • This rate of change is called the derivative of y with respect to x • In more precise language, the dependency of y on x means that y is a function of x • If x and y are real numbers, and if the graph of y is plotted against x, the derivative measures the slope of this graph at each point Differentiation and the Derivative . • This functional relationship is often denoted y = f(x), where f denotes the function • The simplest case is when y is a linear function of x, meaning that the graph of y against x is a straight line • In this case, y = f(x) = m x + c, for real numbers m and c, and the slope m is given by • where the symbol Δ is an abbreviation for ‘change in’ Differentiation and the Derivative .. • It follows that Δy = m Δx – This gives an exact value for the slope of a straight line • If the function f is not linear, then the change in y divided by the change in x varies – Differentiation is a method to find an exact value for this rate of change at any given value of x • In Leibniz's notation, such an infinitesimal change in x is denoted by dx, and the derivative of y with respect to x is written: 2/24/2019 14 3D Line Parametric Equations • In 3D a line is often described by parametric equations: x = x0 + at y = y0 + bt z = z0 + ct • where: – x, y, and z are all functions of the independent variable t – x0, y0, and z0 are the initial values of each respective variable – a, b, and c are related to the slope of the line, such that the vector (a, b, c) is a parallel to the line Ray • In Euclidean geometry, a ray, or half-line, given two distinct points A (the origin) and B on the ray, is the set of points C on the line containing points A and B such that A is not strictly between C and B • In geometry, a ray starts at one point, then goes on forever in one direction Example Class Tray.h class TRay { private: TVector _P; // Any point on the line TVector _V; // Direction of the line public: // Constructor TRay() {} // Line betwen two points OR point and a direction TRay(const TVector &point1, const TVector &point2); // Adjacent points on both lines bool adjacentPoints(const TRay &ray, TVector &point1, TVector &point2) const; // Distances double dist(const TRay &ray) const; double dist(const TVector &point) const; // More functions here }; #endif Plane Definition • A plane can be uniquely determined by any of the following (sets of) objects: – Three non-collinear points • i.e. not lying on the same line – A line and a point not on the line – Two lines with one point of intersection – Two parallel lines Plane Properties • Two planes are either parallel or they intersect in a line • A line is either parallel to a plane or intersects it at a single point or is contained in the plane • Two lines normal (perpendicular) to the same plane must be parallel to each other • Two planes normal to the same line must be parallel to each other Standard Plane Equation • The standard equation of a plane in 3 space is: Ax + By + Cz + D = 0 • The normal to the plane is the vector (A,B,C) 2/24/2019 15 Plane Definition with a Point and a Normal Vector • In a 3D space, another important way of defining a plane is by specifying a point and a normal vector to the plane • Let p be the point we wish to lie in the plane, and let n be a nonzero normal vector to the plane • The desired plane is the set of all points r such that: Plane Definition with a Point and a Normal Vector . • If we write • and d as the dot product • then the plane Π is determined by the condition • where a, b, c and d are real numbers and a, b, and c are not all zero Define a Plane using three Points • The plane passing through three points p1=(x1, y1, z1), p2=(x2, y2, z2) and p3=(x3, y3, z3) can be defined as the set of all points (x, y, z) that satisfy the following determinant equations: Determinant • A determinant is a function depending on n that associates a scalar, det(A), to every n×n square matrix A • The determinant of a matrix A is also sometimes denoted by |A| Dihedral Angle • Given two intersecting planes described by and • the dihedral angle between them is defined to be the angle α between their normal directions Minimum Distance between a Point and a Line • Find the shortest distance from a point to a line or line segment • The equation of a line defined through two points P1 (x1, y1) and P2 (x2, y2) is: P = P1 + u (P2 - P1) P 2/24/2019 16 Minimum Distance between a Point and a Line . • The point P3 (x3, y3) is closest to the line at the tangent to the line which passes through P3, that is, the dot product of the tangent and line is equal to zero, thus: (P3 - P)●(P2 - P1) = 0 • Substituting the equation of the line gives: [P3 - P1 - u(P2 - P1)]●(P2 - P1) = 0 Minimum Distance between a Point and a Line .. • Solving this gives the value of u • Substituting this into the equation of the line gives the point of intersection (x, y) of the tangent as x = x1 + u (x2 - x1) y = y1 + u (y2 - y1) • The distance therefore between the point P3 and the line is the distance between (x, y) above and P3 Minimum Distance between a Point and a Line … • Notes – The only special testing for a software implementation is to ensure that P1 and P2 are not coincident (denominator in the equation for u is 0) – If the distance of the point to a line segment is required then it is only necessary to test that u lies between 0 and 1 – The solution is similar in higher dimensions Minimum Distance between a Point and a Plane • Let Pa = (xa, ya, za) be the point in question • A plane can be defined by its normal n = (A, B, C) and any point on the plane Pb = (xb, yb, zb) • Any point P = (x, y, z) lies on the plane if it satisfies the following A x + B y + C z + D = 0 Minimum Distance between a Point and a Plane . • Consider the projection of the line (Pa - Pb) onto the normal of the plane n, that is just ||Pa - Pb|| cosθ – Where θ is the angle between (Pa - Pb) and the normal n • This projection is the minimum distance (D) of Pa to the plane and can be written in terms of the dot product: D = (Pa - Pb) ● n / ||n|| • That is: D = (A (xa - xb) + B (ya - yb) + C (za - zb)) / sqrt(A2 + B2 + C2) Minimum Distance between a Point and a Plane .. • Since point (xb, yb, zb) is a point on the plane Axb + Byb + Czb + D = 0 • Substituting gives: (Axa + Bya + Cza + D) / sqrt(A2 + B2 + C2) 2/24/2019 17 Point inside a Triangle • Consider a triangle T defined by 3 points p1(x1, y1), p2(x2, y2), p3(x3, y3) and a single point p(x, y) • Four solutions: – Barycentric solution – Parametric solution – Dot product solution – Cross product solution p2 (x2, y2) p1 (x1, y1) p3 (x3, y3) .p (x, y) Barycentric Solution • Barycentric coordinate allows to express new p coordinates as a linear combination of p1, p2, p3 • More precisely, it defines 3 scalars a, b, c such that : – x = a * x1 + b * x2 + c * x3 – y = a * y1 + b * y2 + c * y3 – a + b + c = 1 http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html p2 (x2, y2) p1 (x1, y1) p3 (x3, y3) .p (x, y) Barycentric Solution . • The way to compute a, b, c is not difficult : – a = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / ((y2 - y3)*(x1 x3) + (x3 - x2)*(y1 - y3)) – b = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / ((y2 - y3)*(x1 x3) + (x3 - x2)*(y1 - y3)) – c = 1 - a - b • Then p lies in T if and only if: – 0 <= a <= 1 and 0 <= b <= 1 and 0 <= c <= 1 http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html Barycentric Code Sample function pointInTriangle(x1, y1, x2, y2, x3, y3, x, y: Number): Boolean { var denominator:Number = ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3)); var a:Number = ((y2 - y3)*(x - x3) + (x3 - x2)*(y - y3)) / denominator; var b:Number = ((y3 - y1)*(x - x3) + (x1 - x3)*(y - y3)) / denominator; var c:Number = 1 - a - b; return 0 <= a && a <= 1 && 0 <= b && b <= 1 && 0 <= c && c <= 1; } http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html Parametric Solution • Consider the parametric expressions of the 2 edges [p1, p2] and [p1, p3] in T : – x(t1) = t1*(x2 - x1) – y(t1) = t1*(y2 - y1) – x(t2) = t2*(x3 - x1) – y(t2) = t2*(y3 - y1) • Then express p(x, y) as a linear combination of them: – x = x1 + x(t1) + x(t2) – y = y1 + y(t1) + y(t2) http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html p2 (x2, y2) p1 (x1, y1) p3 (x3, y3) .p (x, y) Parametric Solution . • Solving the system: – t1 = (x*(y3 - y1) + y*(x1 - x3) - x1*y3 + y1*x3) / (x1*(y2 y3) + y1*(x3 - x2) + x2*y3 - y2*x3) – t2 = (x*(y2 - y1) + y*(x1 - x2) - x1*y2 + y1*x2) / -(x1*(y2 - y3) + y1*(x3 - x2) + x2*y3 - y2*x3) • Then p lies in T if and only if: – 0 <= t1 <= 1 and 0 <= t2 <= 1 and t1 + t2 <= 1 http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html 2/24/2019 18 Parametric Code Sample function pointInTriangle(x1, y1, x2, y2, x3, y3, x, y: Number): Boolean { var denominator:Number = (x1*(y2 - y3) + y1*(x3 - x2) + x2*y3 - y2*x3); var t1:Number = (x*(y3 - y1) + y*(x1 - x3) - x1*y3 + y1*x3) / denominator; var t2:Number = (x*(y2 - y1) + y*(x1 - x2) - x1*y2 + y1*x2) / - denominator; var s:Number = t1 + t2; return 0 <= t1 && t1 <= 1 && 0 <= t2 && t2 <= 1 && s <= 1; } http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html Dot Product Solution • Assume that p1, p2, p3 are ordered in counterclockwise and check if p lies at left of the 3 oriented edges – [p1, p2], [p2, p3], [p3, p1] • First consider the 3 vectors v1, v2 and v3 that are leftorthogonal to [p1, p2], [p2, p3] and [p3, p1] : – v1 = – v2 = – v3 = • Then we get the 3 following vectors : – v1' = – v2' = – v3' = p2 (x2, y2) p1 (x1, y1) p3 (x3, y3) .p (x, y) http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html v1 v3 v2 Dot Product Solution . • Compute the 3 dot products: – dot1 = v1 . v1' = (y2 - y1)*(x - x1) + (-x2 + x1)*(y - y1) – dot2 = v1 . v2' = (y3 - y2)*(x - x2) + (-x3 + x2)*(y - y2) – dot3 = v3 . v3' = (y1 - y3)*(x - x3) + (-x1 + x3)*(y - y3) • Check if p lies in T if and only if – 0 <= dot1 and 0 <= dot2 and 0 <= dot3 http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html Dot Product Sample Code function side(x1, y1, x2, y2, x, y:Number):Number { return (y2 - y1)*(x - x1) + (-x2 + x1)*(y - y1); } function pointInTriangle(x1, y1, x2, y2, x3, y3, x, y: Number): Boolean { var checkSide1:Boolean = side(x1, y1, x2, y2, x, y) >= 0; var checkSide2:Boolean = side(x2, y2, x3, y3, x, y) >= 0; var checkSide3:Boolean = side(x3, y3, x1, y1, x, y) >= 0; return checkSide1 && checkSide2 && checkSide3; } http://totologic.blogspot.fr/2014/01/accurate-point-in-triangle-test.html Cross Product Solution • Calculate: – c1 = p1 x p – c2 = p2 x p – c3 = p3 x p • P is inside triangle if: – Clockwise order if • c1> 0 && c2> 0 && c3 > 0 – Counterclockwise if • c1< 0 && c2< 0 && c3 < 0 – No information if • (c1> 0 && c2> 0 && c3 > 0) || (c1< 0 && c2< 0 && c3 < 0) http://www.sunshine2k.de/coding/java/PointInTriangle/PointInTriangle.html Conic Sections • A conic section is a curve obtained as the intersection of a cone (more precisely, a right circular conical surface) with a plane 2/24/2019 19 Circle • The circumference of a circle means the length of the circle • The interior of the circle is called a disk • An arc is any continuous portion of a circle • A diameter is a straight line through the center and terminating in both directions on the circumference Equation of a Circle • In an x-y coordinate system, the circle with centre (a, b) and radius r is the set of all points (x, y) such that: • The equation of the circle follows from the Pythagorean theorem applied to any point on the circle Circle at Origin • If the circle is centred at the origin (0, 0), then the above formula can be simplified: • and its tangent will be: • where x1, y1 are the coordinates of the common point Tangent and Secant Lines • A line is tangent to a curve, at some point, if both line and curve pass through the point with the same direction – This is called the tangent line – Tangent line is the best straightline approximation to the curve at that point • The slope of a tangent line can be approximated by a secant line – It is a mistake to think of tangents as lines which intersect a curve at only one single point Circle Parametric Equations • When expressed in parametric equations (x, y) can be written using the trigonometric functions sine and cosine as: x = a + r cost y = b + r sint • where t is a parametric variable – Understood as the angle the ray to (x, y) makes with the x-axis Definition of π • π symbolizes the ratio – The relationship with respect to relative size of the circumference of circle to its diameter, whatever that relationship might be – So when we say that π ≈ 3.14, we mean that the circumference of circle is a little more than three times longer than the diameter: C / D = π ≈ 3.14 – π indicates the ratio of a curved line to a straight 2/24/2019 20 Circumference of a Circle • Since: C / D = π • Can use that as a formula for calculating the circumference of a circle: C = πD • Or, since D = 2r C = π· 2r = 2πr Calculation of Area Enclosed • The area enclosed by a circle is the radius squared, multiplied by π Calculation of Area Enclosed . • Using a square with side lengths equal to the diameter of the circle, then dividing the square into four squares with side lengths equal to the radius of the circle, take the area of the smaller square and multiply by π – approximately 79% of the circumscribing square Unit Circle • A unit circle is a circle with a unit radius – This is a circle whose radius is 1 • Often, the unit circle is the circle of radius 1 centered at the origin (0, 0) in the Cartesian coordinate system in the Euclidean plane – If (x, y) is a point on the unit circle in the first quadrant, then x and y are the lengths of the legs of a right triangle whose hypotenuse has length 1, then: x2 + y2 = 1 Circle Properties • The circle is the shape with the highest area for a given length of perimeter • The circle is a highly symmetric shape – Every line through the centre forms a line of reflection symmetry and it has rotational symmetry around the centre for every angle • All circles are similar: – A circle's circumference and radius are proportional – The area enclosed and the square of its radius are proportional – The constants of proportionality are 2π and π, respectively Calculate x, y of Segment d = 2sqrt(r2-x2) x z 2/24/2019 21 Calculate x, y of Segment . d = 2sqrt(r2-x2) → z = sqrt(r2 - x2) → z = sqrt(r2 - r2/(1 + tanθ2) → z = r sqrt(1 - 1 / (1 + tanθ2) z = sqrt(r2-x2) → z2 = r2-x2 But tanθ = z/x, so: x2tanθ2 = r2-x2 → x2(1+ tanθ2) = r2 → x = r/sqrt(1 + tanθ2) Ground Implementation in C++ • TGround Class – Variables • Define 37 points in the surface of the ground • Define the normal of the ground – Functions • Ground Constructor • Draw Ground TGround Class class TGround { public: TVector _points[37]; // points in the surface of the ground TVector _normal; // normal of the ground public: // Default constructor TGround(); // Function that draws the ground void DrawGround(); }; Constructor for(i=0; i<=36; i++) { // Transform degrees in rads rad_angle=(pi*angle)/180.0; // Calculate the x and z co-ordinates of a circle ground x = radius/(sqrt(1.0 + tan(rad_angle)*tan(rad_angle))); z = radius*(sqrt(1.0 - (1.0/(1.0 + tan(rad_angle)*tan(rad_angle))))); angle+= 10; // Check the co-ordinates in all the quadrants of the circle ground if ((i>=0) && (i<10)) // First quadrant { if (i==9) { _points[i] = TVector(0.0, 0.0, 1.0); } _points[i] = TVector(x, y, z); } if ((i>=10) && (i<19)) // Second quadrant { _points[i] = TVector(-x, y, z); } if ((i>=19) && (i<28)) // Third quadrant { if (i==27) { _points[i] = TVector(0.0, 0.0, -1.0); } _points[i] = TVector(-x, y, -z); } if ((i>=27) && (i<=36)) // Fourth quadrant { _points[i] = TVector(x, y, -z); } } // Construct the vector for the normal of the ground _normal = TVector(0.0, 1.0, 0.0); Draw Ground Function void TGround::DrawGround() { int i=0.0; glPushMatrix(); glPushAttrib(GL_ENABLE_BIT); glCallList(50); glBegin(GL_POLYGON); for(i=0; i<=36; i++) { glNormal3f(0.0, 1.0, 0.0); glVertex3f(_points[i].X(), _points[i].Y(), _points[i].Z()); } glEnd(); glPopAttrib(); glPopMatrix(); } Ellipse • An ellipse is a curve on a plane surrounding two focal points such that the sum of the distances to the two focal points is constant for every point on the curve • You can think of an ellipse as an oval 2/24/2019 22 Parabola • The standard form of a parabola's equation is generally expressed: – y = ax2 + bx + c • The role of 'a‘ – If a> 0, the parabola opens upwards – If a< 0, it opens downwards • The axis of symmetry – The axis of symmetry is the line x = -b/2a http://www.mathwarehouse.com/geometry/parabola/standard-and-vertex-form.php Vertex Form of Parabola • The vertex form of a parabola's equation is generally expressed as: – y = a(x-h)2+k where (h,k) is the vertex • If a is + then the parabola opens upwards like a regular "U" • If a is - then the graph opens downwards like an upside down "U" • If |a| < 1, the graph of the parabola widens • If |a| > 1, the graph of the graph becomes narrower – The effect is the opposite of |a| < 1 http://www.mathwarehouse.com/geometry/parabola/standard-and-vertex-form.php Hyperbola • The equation of the hyperbola can be written as: • If c is the distance from the center to either focus, then: a2+b2 = c2 Parametric surfaces • A torus with major radius R and minor radius r may be defined parametrically as x = cos(t)(R + r cos(u)) y = sin(t)(R + r cos(u)) z = r sin(u) • where the two parameters t and u both vary between 0 and 2π Equation of a Sphere • Pythagoras theorem generalises to 3D giving: – a2 + b2 + c2 = d2 • Based on that we can easily prove that the general equation of a sphere is: – (x- xc)2 + (y- yc)2 + (z- zc)2 = r2 • and at origin: – x2 + y2 + z2 = r2 Ray-Sphere Intersection Ray: P = P0 + tV Sphere: (x - cx)2 + (y - cy)2 + (z - cz)2 = r 2 or |P - C|2 - r 2 = 0 Substituting for P, we get: |P0 + tV - C|2 - r 2 = 0 Solve quadratic equation: at2 + bt + c = 0 where: a = |V|2 = 1 b = 2 V • (P0 - C) c = |P0 - C|2 - r 2 P = P0 + tV P0 V C P r P’ 2/24/2019 23 Advanced Methods of Rotation • Different advanced methods exist including: – Euler angles – Quaternions Euler Angles • In many fields Euler angles are used to represent rotations • Any rotation can be broken down into a series of three rotations about the major axes Euler Angles . • We can simulate any arbitrary rotation with one rotation about the x-axis, one about the y-axis, and then one about the z-axis – i.e. consider an airplane pointing along the x-axis with the z-axis pointing up Roll, Pitch, Yaw • Can represent any pose as a vector (roll, pitch, yaw) – The "roll" about the x-axis along the plane – The "pitch" about the yaxis which extends along the wings of the plane – The "yaw" or "heading" about the z-axis Disadvantages • No universal standard for Euler rotations – Different fields use different sequences • i.e. some use z-y-z as opposed to the x-y-z system • Although any rotation can be represented by either a set of Euler angles or a matrix – Computing the required angles is expensive and can introduce errors • Interpolation does not work well! Standard Rotations 2/24/2019 24 Angles to Axis • Can combine the separate axis rotations into one matrix by multiplying standard rotational matrices together – Multiplication of matrices is not commutative • Different order of matrix multiplication results in a different outcome • 6 different combinations are possible; – RxRyRz, RxRzRy, RyRxRz, RyRzRx, RzRxRy and RzRyRx RxRyRz & RxRzRy Rotations RyRxRz & RyRzRx Rotations RzRxRy & RzRyRx Rotations Code Example void anglesToAxes(const Vector3 angles, Vector3& left, Vector3& up, Vector3& forward) { const float DEG2RAD = 3.141593f / 180; float sx, sy, sz, cx, cy, cz, theta; // rotation angle about X-axis (pitch) theta = angles.x * DEG2RAD; sx = sinf(theta); cx = cosf(theta); // rotation angle about Y-axis (yaw) theta = angles.y * DEG2RAD; sy = sinf(theta); cy = cosf(theta); // rotation angle about Z-axis (roll) theta = angles.z * DEG2RAD; sz = sinf(theta); cz = cosf(theta); } Code Example . left.x = cy*cz; left.y = sx*sy*cz + cx*sz; determine left axis left.z = -cx*sy*cz + sx*sz; up.x = -cy*sz; up.y = -sx*sy*sz + cx*cz; determine up axis up.z = cx*sy*sz + sx*cz; forward.x = sy; forward.y = -sx*cy; determine forward axis forward.z = cx*cy; 2/24/2019 25 Rotation About Arbitrary Axis • In addition to the set of three Euler angles and the rotation matrix, a rotation can also be represented by a vector specifying the rotation axis and the angle of rotation around this axis • The problem of rotation about an arbitrary axis in three dimensions arises in many fields including computer graphics and computer games 3x3 Matrix Representing Axis • We can express the 3×3 rotation matrix in terms of a 3×3 matrix representing the axis: – [R] = [I] + s*[~axis] + t*[~axis]2 • or equivalently: – [R] = c*[I] + s*[~axis] + t*([~axis]2 + [I]) Matrix Expansion t*x*x + c t*x*y - z*s t*x*z + y*s [R] = t*x*y + z*s t*y*y + c t*y*z - x*s t*x*z - y*s t*y*z + x*s t*z*z + c • where: – c = cos(angle) – s = sin(angle) – t = 1 - c – x = normalised axis x coordinate – y = normalised axis y coordinate – z = normalised axis z coordinate Code Example public void matrixFromAxisAngle(AxisAngle4da1) { double c = Math.cos(a1.angle); double s = Math.sin(a1.angle); double t = 1.0 - c; m00 = c + a1.x*a1.x*t; m11 = c + a1.y*a1.y*t; m22 = c + a1.z*a1.z*t; double tmp1 = a1.x*a1.y*t; double tmp2 = a1.z*s; m10 = tmp1 + tmp2; m01 = tmp1 - tmp2; tmp1 = a1.x*a1.z*t; tmp2 = a1.y*s; m20 = tmp1 - tmp2; m02 = tmp1 + tmp2; tmp1 = a1.y*a1.z*t; tmp2 = a1.x*s; m21 = tmp1 + tmp2; m12 = tmp1 - tmp2; } Quaternions • Complex numbers were discovered in 1800’s and had the characteristic property to be defined in terms of i, where i is the square root of –1 • In 1843, sir William Rowan Hamilton discovered a number called the quaternion, which has a very similar form to complex numbers Quaternion Definition • A quaternion is based on three different numbers that are all square roots of –1 and are labeled i, j and k, where: 2/24/2019 26 Quaternion Properties Quaternion Rotations Quaternion Representation • Defined like complex numbers but with 4 coordinates – q[w, (x, y, z)] also written q[w, v] where v = (x, y, z) – q = w + xi + yj + zk • Here, w is real part, and (x,y,z) are imaginary parts • Think of w as angle in an angle-axis representation • Think of (x, y, z) as axis in an axis-angle representation • Based on three different roots of -1: – i2 = j2 = k2 = -1 Quaternion Representation . • For a right-hand rotation of q radians about unit vector v, quaternion is: q = (cos(q/2); v sin(q/2)) – Note how the 3 imaginary coordinates are noted as a vector – Only unit quaternions represent rotations • Such a quaternion describes a point on the 4D unit hyper-sphere – Important note: q and –q represent the exact same orientation Quaternion Toolbox • Addition – q1 + q2 = [w1 + w2, v1 + v2] • Multiplication – q1q2 = [w1w2 – v1.v2, v1 x v2 + w1v2 + w2v1] (note: q1q2 != q2q1) • Magnitude – | q | = sqrt(w2 + x2 + y2 + z2) • Normalisation – N(q) = q / | q | • Conjugate – q* = [w , -v] • Inverse – q-1 = q* / | q | 2 • Unit quternion – q is unit if | q | = 1 and q-1 = q* • Identity – qIdentity = [1,(0,0,0)] for multiplication, qIdentity = [0,(0,0,0)] for addition Transforming a Point or Vector • To transform a vector P by the rotation specified by the quaternion q, there are two options: – Multiply conj(q) by (0, Px, Py, Pz) • See next slide – Convert q to matrix and use matrix transformation 2/24/2019 27 First Method • Rotate vector P angle q around unit axis R: – Form the quaternion representing the vector P • q1 = (0,Px,Py,Pz) – Form the rotation quaternion from the axis R and angle q • q2 = (cos(q /2),Rx sin(q /2),Ry sin(q /2),Rz sin(q /2)) – The rotated vector is given by v entry of the quaternion: • q3 = q2 q1 q2* – q2 must be of unit magnitude for this to work properly Quaternion and Axis-Angle • From axis-angle to quaternion: – q = (cos(q/2); v sin(q/2)) – where: • v is the axis • q is the angle • From quaternion to axis-angle: – Axis v = (x, y, z) / sqrt(x2 + y2 + z2) – Angle q = acos(w) * 2 Quaternion to Matrix • From quaternion to a 3x3 rotation matrix: Euler Angles to Quaternion • From Euler angles (pitch, yaw, roll) – Create three quaternions – One for each of pitch, roll, yaw – Then multiply them together • Here, P = pitch/2, Y = yaw/2, R = roll/2 – w = cos(R)*cos(P)*cos(Y) + sin(R)*sin(P)*sin(Y) – x = sin(R)*cos(P)*cos(Y) – cos(R)*sin(P)*sin(Y) – y = cos(R)*sin(P)*cos(Y) + sin(R)*cos(P)*sin(Y) – z = cos(R)*cos(P)*sin(Y) – sin(R)*sin(P)*cos(Y) Quaternion Code Example • Three functions: – Convert an axis and angle rotation to a quaternion – Convert a quaternion to a rotation matrix – Rotate the quaternion Convert an axis and angle rotation to a quaternion void Tquaternion::CreateFromAxisAngle(float X, float Y, float Z, float degree) { float angle = float((degree / 180.0f) * PI); float result = (float)sin( angle / 2.0f ); w = (float)cos( angle / 2.0f ); x = float(X * result); y = float(Y * result); z = float(Z * result); } 2/24/2019 28 Convert a quaternion to a rotation matrix void Tquaternion::CreateMatrix(float*pMatrix) { pMatrix[ 0] = 1.0f - 2.0f * ( y * y + z * z ); pMatrix[ 1] = 2.0f * (x * y + z * w); pMatrix[ 2] = 2.0f * (x * z - y * w); pMatrix[ 3] = 0.0f; pMatrix[ 4] = 2.0f * ( x * y - z * w ); pMatrix[ 5] = 1.0f - 2.0f * ( x * x + z * z ); pMatrix[ 6] = 2.0f * (z * y + x * w ); pMatrix[ 7] = 0.0f; pMatrix[ 8] = 2.0f * ( x * z + y * w ); pMatrix[ 9] = 2.0f * ( y * z - x * w ); pMatrix[10] = 1.0f - 2.0f * ( x * x + y * y ); pMatrix[11] = 0.0f; pMatrix[12] = 0; pMatrix[13] = 0; pMatrix[14] = 0; pMatrix[15] = 1.0f; } Rotate the Quaternion void Tquaternion::quaternionRotation(double x, double y, double z) { float matrixX[16], matrixY[16], matrixZ[16]; static float rotation = 0; Tquaternion qRotationX; Tquaternion qRotationY; Tquaternion qRotationZ; qRotationX.CreateFromAxisAngle(1, 0, 0, x); qRotationY.CreateFromAxisAngle(0, 1, 0, y); qRotationZ.CreateFromAxisAngle(0, 0, 1, z); qRotationX.CreateMatrix(matrixX); qRotationY.CreateMatrix(matrixY); qRotationZ.CreateMatrix(matrixZ); glMultMatrixf(matrixX); glMultMatrixf(matrixY); glMultMatrixf(matrixZ); } Quaternion Interpolation • One of the most important reasons for using quaternions is that they are very good at representing rotations in space • Quaternions overcome the issues that plague other methods of rotating points in 3D space such as Gimbal lock – An issue when you represent your rotation with Euler angles Quaternion Interpolation Methods • Using quaternions can define several methods that represents a rotational interpolation in 3D space: – SLERP • Used to smoothly interpolate a point between two orientations – SQAD (extension of SLERP) • Used to interpolate through a sequence of orientations that define a path Examples SLERP • SLERP provides a method to smoothly interpolate a point about two orientations – SLERP stands for Spherical Linear Interpolation • Represent the first orientation as q1 and the second orientation as q2 • The point that is interpolated will be represented by P and the interpolated point will be represented by P’ • The interpolation parameter t will interpolate P from q1 when t=0 to q2 when t=1 2/24/2019 29 SLERP Interpolation • The standard linear interpolation formula is: p’ = p1 + t(p2 – p1) • The general steps to apply this equation are: – Compute the difference between p1 and p2 – Take the fractional part of that difference – Adjust the original value by the fractional difference between the two points • Can use the same principle to interpolate between two quaternion orientations SQAD • SQUAD (Spherical and Quadrangle) can be used to smoothly interpolate over a path of rotations – Just as a SLERP can be used to compute an interpolation between two quaternions • If we have the sequence of quaternions: SQAD Representation • And we also define the “helper” quaternion (si) which we can consider an intermediate control point: SQAD Orientation • Then the orientation along the sub-curve defined by: • at time t is given by: Quaternion Advantages • Quaternion interpolation using SLERP and SQUAD provide a way to interpolate smoothly between orientations in space • Rotation concatenation using quaternions is faster than combining rotations expressed in matrix form • Converting quaternions to matrices is slightly faster than for Euler angles • Quaternions only require 4 numbers – 3 if they are normalized – The Real part can be computed at run-time • To represent a rotation where a matrix requires at least 9 values Quaternion Disadvantages • Very hard to understand • Can become invalid because of floating-point round-off error – This can be resolved by re-normalizing the quaternion 2/24/2019 30 References • http://www.songho.ca/opengl/gl_anglestoaxes.html • http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ • http://www.euclideanspace.com/maths/geometry/rotations/conversi ons/angleToMatrix/ • http://en.wikipedia.org/wiki/Euler_angles • http://en.wikipedia.org/wiki/Line_(mathematics) • http://en.wikipedia.org/wiki/Plane_(mathematics) • http://inst.eecs.berkeley.edu/~cs283/sp13/lectures/283-lecture18.pdf • http://www.gamedev.net/page/resources/_/technical/math-and- physics/quaternion-powers-r1095 • http://www.gamasutra.com/view/feature/3278/ • http://3dgep.com/?p=1815 Programming Links • http://pages.cs.wisc.edu/~cs368- 2/CppTutorial/NOTES/CLASSES-INTRO.html • http://www.quantstart.com/articles/Matrix-Classes-in-C- The-Header-File • http://www.programiz.com/article/c%2B%2B- programming-pattern • http://stackoverflow.com/questions/564877/point-and- line-class-in-c • http://www.seasite.niu.edu/CS240/Old_CPP_Notes/lines _class_cpp_program.htm • http://www.linuxfocus.org/English/March1998/article28. html • http://www.cs.stanford.edu/~acoates/quaternion.h Questions