MathUtils

Engine/source/math/mathUtils.cpp

Miscellaneous math utility functions.

More...

Classes:

class

Used by mTriangleDistance() to pass along collision info.

class

A simple helper struct to define a line.

class

A simple helper struct to define a line segment.

class

A simple helper struct to define a clockwise winding quad.

Public Typedefs

Ray 

A ray is also a line.

Public Variables

sGFXProjRotMatrix (EulerF((M_PI_F/2.0f), 0.0f, 0.0f))

This is the special rotation matrix applied to projection matricies for GFX.

sgRandom (0xdeadbeef)

Our random number generator.

Public Functions

buildMatrix(const VectorF * rvec, const VectorF * fvec, const VectorF * uvec, const VectorF * pos, MatrixF * outMat)

WORK IN PROGRESS.

bool
capsuleCapsuleOverlap(const Point3F & a1, const Point3F & b1, F32 radius1, const Point3F & a2, const Point3F & b2, F32 radius2)

Collide two capsules (sphere swept lines) against each other, reporting only if they intersect or not.

bool

Return capsule-sphere overlap.

bool
clipFrustumByPolygon(const Point3F * points, U32 numPoints, const RectI & viewport, const MatrixF & world, const MatrixF & projection, const Frustum & inFrustum, const Frustum & rootFrustum, Frustum & outFrustum)

Clip inFrustum by the given polygon.

Creates orientation matrix from a direction vector. Assumes ( 0 0 1 ) is up.

bool
edgeFaceIntersect(const Point3F & edgeA, const Point3F & edgeB, const Point3F & faceA, const Point3F & faceB, const Point3F & faceC, const Point3F & faceD, Point3F * intersection)

Find the intersection of the line going from edgeA to edgeB with the triangle given by faceA, faceB, and faceC.

extrudePolygonEdges(const Point3F * vertices, U32 numVertices, const Point3F & direction, PlaneF * outPlanes)

Extrude the given polygon along the given direction.

extrudePolygonEdgesFromPoint(const Point3F * vertices, U32 numVertices, const Point3F & fromPoint, PlaneF * outPlanes)

Extrude the edges of the given polygon away from fromPoint by constructing a set of planes that each go through fromPoint and a pair of vertices.

Returns the angle between two given vectors.

getAnglesFromVector(const VectorF & vec, F32 & yawAng, F32 & pitchAng)

Returns yaw and pitch angles from a given vector.

Creates an orthonormal basis matrix with the unit length input vector in column 1 (forward vector).

Creates an orthonormal basis matrix with the unit length input vector in column 2 (up vector).

Returns the angle between two given vectors, utilizing a normal vector to discertain the angle's sign.

getVectorFromAngles(VectorF & vec, F32 yawAng, F32 pitchAng)

Returns vector from given yaw and pitch angles.

getZBiasProjectionMatrix(F32 bias, const Frustum & frustum, MatrixF * outMat, bool rotate)

Generates a projection matrix with the near plane moved forward by the bias amount.

Returns the greatest common divisor of two positive integers.

bool
isConvexPolygon(const Point3F * vertices, U32 numVertices)

Find out whether the given polygon is convex.

bool
isPlanarPolygon(const Point3F * vertices, U32 numVertices)

Find out whether the given polygon is planar.

makeFovPortFrustum(Frustum * outFrustum, bool isOrtho, F32 nearDist, F32 farDist, const FovPort & inPort, const MatrixF & transform)
makeFrustum(F32 * outLeft, F32 * outRight, F32 * outTop, F32 * outBottom, F32 fovYInRadians, F32 aspectRatio, F32 nearPlane)

Build the frustum near plane dimensions from the parameters.

makeOrthoProjection(MatrixF * outMatrix, F32 left, F32 right, F32 top, F32 bottom, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build an orthographic projection matrix from the frustum near plane dimensions including the optional rotation required by GFX.

makeProjection(MatrixF * outMatrix, F32 fovYInRadians, F32 aspectRatio, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build a GFX projection matrix from the frustum parameters including the optional rotation required by GFX.

makeProjection(MatrixF * outMatrix, F32 left, F32 right, F32 top, F32 bottom, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build a projection matrix from the frustum near plane dimensions including the optional rotation required by GFX.

mBuildHull2D(const Vector< Point2F > _inPoints, Vector< Point2F > & hullPoints)

Build a convex hull from a cloud of 2D points, first and last hull point are the same.

Returns the closest point on the segment defined by points a, b to the point p.

bool
mLineTriangleCollide(const Point3F & p1, const Point3F & p2, const Point3F & t1, const Point3F & t2, const Point3F & t3, Point3F * outUVW, F32 * outT)

Returns the barycentric coordinates and time of intersection between a line segment and a triangle.

mProjectScreenToWorld(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & world, const MatrixF & projection, F32 zfar, F32 znear)
bool
mProjectWorldToScreen(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & world, const MatrixF & projection)
bool
mProjectWorldToScreen(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & worldProjection)
bool
mRayQuadCollide(const Quad & quad, const Ray & ray, Point2F * outUV, F32 * outT)

Returns the uv coords and time of intersection between a ray and a quad.

mShortestSegmentBetweenLines(const Line & line0, const Line & line1, LineSegment * outSegment)

Calculates the shortest line segment between two lines.

Returns the distance between a point and triangle 'abc'.

Returns the normal of the passed triangle 'abc'.

bool
pointInPolygon(const Point2F * verts, U32 vertCount, const Point2F & testPt)

Returns true if the test point is within the polygon.

randomDir(const Point3F & axis, F32 thetaAngleMin, F32 thetaAngleMax, F32 phiAngleMin, F32 phiAngleMax)

Creates random direction given angle parameters similar to the particle system.

Returns a random 2D point within a circle of the specified radius centered at the origin.

Returns a random 3D point within a sphere of the specified radius centered at the origin.

bool
reduceFrustum(const Frustum & frustum, const RectI & viewport, const RectF & area, Frustum & outFrustum)
reflect(Point3F & inVec, Point3F & norm)

Simple reflection equation - pass in a vector and a normal to reflect off of.

removeShortPolygonEdges(const Point3F * verts, U32 vertCount, F32 epsilon)

Remove all edges from the given polygon that have a total length shorter than epsilon.

Intersect two line segments (p1,q1) and (p2,q2), returning points on lines (c1 & c2) and line parameters (s,t).

sortQuadWindingOrder(bool clockwise, const Point3F * verts, U32 * vertMap, U32 count)

Same as above except we assume that the passed verts ( Point3F ) are already transformed into 'quad space'.

sortQuadWindingOrder(const MatrixF & quadMat, bool clockwise, const Point3F * verts, U32 * vertMap, U32 count)

Sort the passed verts ( Point3F ) in a clockwise or counter-clockwise winding order.

Transform bounding box making sure to keep original box entirely contained.

vectorRotateZAxis(F32 radians, Point3F * vectors, U32 count)
vectorRotateZAxis(Point3F & vector, F32 radians)

Rotate the passed vector around the world-z axis by the passed radians.

Detailed Description

Miscellaneous math utility functions.

Public Typedefs

typedef Line Ray 

A ray is also a line.

Public Variables

const MatrixF sGFXProjRotMatrix (EulerF((M_PI_F/2.0f), 0.0f, 0.0f))

This is the special rotation matrix applied to projection matricies for GFX.

It is a wart of the OGL to DX change over.

MRandomLCG sgRandom (0xdeadbeef)

Our random number generator.

Public Functions

buildMatrix(const VectorF * rvec, const VectorF * fvec, const VectorF * uvec, const VectorF * pos, MatrixF * outMat)

WORK IN PROGRESS.

Creates an orthonormal basis matrix from one, two, or three unit length input vectors. If more than one input vector is provided they must be mutually perpendicular.

Parameters:

rvec

Optional unit length right vector.

fvec

Optional unit length forward vector.

uvec

Optional unit length up vector.

pos

Optional position to initialize the matrix.

outMat

The output matrix which must be initialized prior to the call.

capsuleCapsuleOverlap(const Point3F & a1, const Point3F & b1, F32 radius1, const Point3F & a2, const Point3F & b2, F32 radius2)

Collide two capsules (sphere swept lines) against each other, reporting only if they intersect or not.

Based on routine from "Real Time Collision Detection" by Christer Ericson pp 114.

capsuleSphereNearestOverlap(const Point3F & A0, const Point3F A1, F32 radA, const Point3F & B, F32 radB, F32 & t)

Return capsule-sphere overlap.

Returns time of first overlap, where time is viewed as a sphere of radius radA moving from point A0 to A1.

clipFrustumByPolygon(const Point3F * points, U32 numPoints, const RectI & viewport, const MatrixF & world, const MatrixF & projection, const Frustum & inFrustum, const Frustum & rootFrustum, Frustum & outFrustum)

Clip inFrustum by the given polygon.

note:

The input polygon is limited to 58 vertices.

Parameters:
points

Polygon vertices.

numPoints

Number of vertices in points.

viewport

Screen viewport. Note that this corresponds to the root frustum and not necessarily to inFrustum.

world

World->view transform.

projection

Projection matrix.

inFrustum

Frustum to clip.

rootFrustum

Frustum corresponding to viewport.

outFrustum

Resulting clipped frustum.

return:

True if the frustum was successfully clipped and outFrustum is valid, false otherwise (if, for example, the input polygon is completely outside inFrustum).

cmpAngleAscending(const void * a, const void * b)

cmpAngleDescending(const void * a, const void * b)

createOrientFromDir(const Point3F & direction)

Creates orientation matrix from a direction vector. Assumes ( 0 0 1 ) is up.

edgeFaceIntersect(const Point3F & edgeA, const Point3F & edgeB, const Point3F & faceA, const Point3F & faceB, const Point3F & faceC, const Point3F & faceD, Point3F * intersection)

Find the intersection of the line going from edgeA to edgeB with the triangle given by faceA, faceB, and faceC.

Parameters:

edgeA

Starting point of edge.

edgeB

End point of edge.

faceA

First vertex of triangle.

faceB

Second vertex of triangle.

faceC

Third vertex of triangle.

intersection

If there is an intersection, the point of intersection on the triangle's face is stored here.

True

if there is an intersection, false otherwise.

extrudePolygonEdges(const Point3F * vertices, U32 numVertices, const Point3F & direction, PlaneF * outPlanes)

Extrude the given polygon along the given direction.

extrudePolygonEdgesFromPoint(const Point3F * vertices, U32 numVertices, const Point3F & fromPoint, PlaneF * outPlanes)

Extrude the edges of the given polygon away from fromPoint by constructing a set of planes that each go through fromPoint and a pair of vertices.

The resulting planes are in the same order as the vertices and have their normals facing inwards, i.e. the resulting volume will enclose the polygon's interior space.

Parameters:

vertices

Vertices of the polygon in CCW or CW order (both are acceptable).

numVertices

Number of vertices in vertices.

fromPoint

outPlanes

Array in which the resulting planes are stored. Must have room for at least as many planes are there are edges in the polygon.

return:

note:

The input polygon does not necessarily need to be planar but it must be convex.

getAngleBetweenVectors(VectorF vecA, VectorF vecB)

Returns the angle between two given vectors.

Angles is in RADIANS

getAnglesFromVector(const VectorF & vec, F32 & yawAng, F32 & pitchAng)

Returns yaw and pitch angles from a given vector.

Angles are in RADIANS.

Assumes north is (0.0, 1.0, 0.0), the degrees move upwards clockwise.

The range of yaw is 0 - 2PI. The range of pitch is -PI/2 - PI/2.

ASSUMES Z AXIS IS UP

getMatrixFromForwardVector(const VectorF & forward, MatrixF * outMat)

Creates an orthonormal basis matrix with the unit length input vector in column 1 (forward vector).

Parameters:

forward

The non-zero unit length forward vector.

outMat

The output matrix which must be initialized prior to the call.

getMatrixFromUpVector(const VectorF & up, MatrixF * outMat)

Creates an orthonormal basis matrix with the unit length input vector in column 2 (up vector).

Parameters:

up

The non-zero unit length up vector.

outMat

The output matrix which must be initialized prior to the call.

getSignedAngleBetweenVectors(VectorF vecA, VectorF vecB, VectorF norm)

Returns the angle between two given vectors, utilizing a normal vector to discertain the angle's sign.

Angles is in RADIANS

getVectorFromAngles(VectorF & vec, F32 yawAng, F32 pitchAng)

Returns vector from given yaw and pitch angles.

Angles are in RADIANS.

Assumes north is (0.0, 1.0, 0.0), the degrees move upwards clockwise.

The range of yaw is 0 - 2PI. The range of pitch is -PI/2 - PI/2.

ASSUMES Z AXIS IS UP

getZBiasProjectionMatrix(F32 bias, const Frustum & frustum, MatrixF * outMat, bool rotate)

Generates a projection matrix with the near plane moved forward by the bias amount.

This function is a helper primarily for working around z-fighting issues.

Parameters:

bias

The amount to move the near plane forward.

frustum

The frustum to generate the new projection matrix from.

outMat

The resulting z-biased projection matrix. Note: It must be initialized before the call.

rotate

Optional parameter specifying whether to rotate the projection matrix similarly to GFXDevice.

greatestCommonDivisor(U32 u, U32 v)

Returns the greatest common divisor of two positive integers.

isConvexPolygon(const Point3F * vertices, U32 numVertices)

Find out whether the given polygon is convex.

Parameters:

vertices

Array of vertices of the polygon.

numVertices

Number of vertices in vertices.

return:

True if the polygon is convex, false otherwise.

isPlanarPolygon(const Point3F * vertices, U32 numVertices)

Find out whether the given polygon is planar.

Parameters:

vertices

Array of vertices of the polygon.

numVertices

Number of vertices in vertices.

return:

True if the polygon is planar, false otherwise.

makeFovPortFrustum(Frustum * outFrustum, bool isOrtho, F32 nearDist, F32 farDist, const FovPort & inPort, const MatrixF & transform)

makeFrustum(F32 * outLeft, F32 * outRight, F32 * outTop, F32 * outBottom, F32 fovYInRadians, F32 aspectRatio, F32 nearPlane)

Build the frustum near plane dimensions from the parameters.

makeOrthoProjection(MatrixF * outMatrix, F32 left, F32 right, F32 top, F32 bottom, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build an orthographic projection matrix from the frustum near plane dimensions including the optional rotation required by GFX.

makeProjection(MatrixF * outMatrix, F32 fovYInRadians, F32 aspectRatio, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build a GFX projection matrix from the frustum parameters including the optional rotation required by GFX.

makeProjection(MatrixF * outMatrix, F32 left, F32 right, F32 top, F32 bottom, F32 nearPlane, F32 farPlane, bool gfxRotate)

Build a projection matrix from the frustum near plane dimensions including the optional rotation required by GFX.

mBuildHull2D(const Vector< Point2F > _inPoints, Vector< Point2F > & hullPoints)

Build a convex hull from a cloud of 2D points, first and last hull point are the same.

mClosestPointOnSegment(const Point3F & a, const Point3F & b, const Point3F & p)

Returns the closest point on the segment defined by points a, b to the point p.


mLineTriangleCollide(const Point3F & p1, const Point3F & p2, const Point3F & t1, const Point3F & t2, const Point3F & t3, Point3F * outUVW, F32 * outT)

Returns the barycentric coordinates and time of intersection between a line segment and a triangle.

Parameters:

p1

The first point of the line segment.

p2

The second point of the line segment.

t1

The first point of the triangle.

t2

The second point of the triangle.

t2

The third point of the triangle.

outUVW

The optional output barycentric coords.

outT

The optional output time of intersection.

return:

Returns true if a collision occurs.

mProjectScreenToWorld(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & world, const MatrixF & projection, F32 zfar, F32 znear)

mProjectWorldToScreen(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & world, const MatrixF & projection)

mProjectWorldToScreen(const Point3F & in, Point3F * out, const RectI & view, const MatrixF & worldProjection)

mRayQuadCollide(const Quad & quad, const Ray & ray, Point2F * outUV, F32 * outT)

Returns the uv coords and time of intersection between a ray and a quad.

Parameters:

quad

The quad.

ray

The ray.

outUV

The optional output UV coords of the intersection.

outT

The optional output time of intersection.

return:

Returns true if a collision occurs.

mShortestSegmentBetweenLines(const Line & line0, const Line & line1, LineSegment * outSegment)

Calculates the shortest line segment between two lines.

Parameters:

outSegment

The result where .p0 is the point on line0 and .p1 is the point on line1.

mTriangleDistance(const Point3F & A, const Point3F & B, const Point3F & C, const Point3F & P, IntersectInfo * info)

Returns the distance between a point and triangle 'abc'.

mTriangleNormal(const Point3F & a, const Point3F & b, const Point3F & c)

Returns the normal of the passed triangle 'abc'.

If we assume counter-clockwise triangle culling, normal will point out from the 'solid' side of the triangle.

pointInPolygon(const Point2F * verts, U32 vertCount, const Point2F & testPt)

Returns true if the test point is within the polygon.

Parameters:

verts

The array of points which forms the polygon.

vertCount

The number of points in the polygon.

testPt

The point to test.

randomDir(const Point3F & axis, F32 thetaAngleMin, F32 thetaAngleMax, F32 phiAngleMin, F32 phiAngleMax)

Creates random direction given angle parameters similar to the particle system.

The angles are relative to the specified axis. Both phi and theta are in degrees.

randomPointInCircle(F32 radius)

Returns a random 2D point within a circle of the specified radius centered at the origin.

randomPointInSphere(F32 radius)

Returns a random 3D point within a sphere of the specified radius centered at the origin.

reduceFrustum(const Frustum & frustum, const RectI & viewport, const RectF & area, Frustum & outFrustum)

reflect(Point3F & inVec, Point3F & norm)

Simple reflection equation - pass in a vector and a normal to reflect off of.

removeShortPolygonEdges(const Point3F * verts, U32 vertCount, F32 epsilon)

Remove all edges from the given polygon that have a total length shorter than epsilon.

segmentSegmentNearest(const Point3F & p1, const Point3F & q1, const Point3F & p2, const Point3F & q2, F32 & s, F32 & t, Point3F & c1, Point3F & c2)

Intersect two line segments (p1,q1) and (p2,q2), returning points on lines (c1 & c2) and line parameters (s,t).

Based on routine from "Real Time Collision Detection" by Christer Ericson pp 149.

sortQuadWindingOrder(bool clockwise, const Point3F * verts, U32 * vertMap, U32 count)

Same as above except we assume that the passed verts ( Point3F ) are already transformed into 'quad space'.

If this was done correctly and the points are coplanar this means their z components will all be zero.

sortQuadWindingOrder(const MatrixF & quadMat, bool clockwise, const Point3F * verts, U32 * vertMap, U32 count)

Sort the passed verts ( Point3F ) in a clockwise or counter-clockwise winding order.

Verts must be co-planar and non-collinear.

Parameters:

quadMat

Transform matrix from vert space to quad space.

clockwise

Sort clockwise or counter-clockwise

verts

Array of Point3F verts.

vertMap

Output - Array of vert element ids sorted by winding order.

count

Element count of the verts and vertMap arrays which must be allocated prior to this call.

transformBoundingBox(const Box3F & sbox, const MatrixF & mat, const Point3F scale, Box3F & dbox)

Transform bounding box making sure to keep original box entirely contained.

vectorRotateZAxis(F32 radians, Point3F * vectors, U32 count)

vectorRotateZAxis(Point3F & vector, F32 radians)

Rotate the passed vector around the world-z axis by the passed radians.