Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \say{Software}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Restrictions: By making use of the Software for military purposes, you choose to make a Bunny unhappy.
THE SOFTWARE IS PROVIDED \say{AS IS}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \say{Software}), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \say{AS IS}, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
OpenGL Mathematics (GLM) is a C++ mathematics library based on the \href{https://www.opengl.org/documentation/glsl/}{OpenGL Shading Language} (GLSL) specification.
GLM provides classes and functions to mimic the conventions and functionality provided by GLSL. An extension system (inspired by OpenGL's) also provides extra capabilities including (but not limited to) matrix transformations, quaternions, data packing, random numbers, and noise.
GLM works perfectly with \href{http://www.opengl.org}{OpenGL}, but is also well-suited for use with any project that demands a simple (yet flexible) mathematics framework such as software rendering (ray-tracing/rasterisation), image processing, and physics simulation.
GLM is written in C++98, but can take advantage of C++11 where support exists. GLM is platform independent, has no dependencies, and supports the following compilers:
The source code and the documentation (including this manual) are licensed under both the \hyperlink{happybunny}{Happy Bunny License (Modified MIT)} and the \hyperlink{mit}{MIT License}.
GLM is a header-only library, and thus does not need to be compiled. To use GLM, merely include the \glmheader{glm} header, which provides GLSL's mathematics functionality.
% TODO: Benchmark explicit extern template instantiations and write something about them if beneficial http://en.cppreference.com/w/cpp/language/class_template
GLM makes heavy use of C++ templates, which may significantly increase the compile time for projects that use GLM. Hence, source files should only include the GLM headers they actually use.
GLM does not depend on external libraries or external headers such as \verb|gl.h|, \href{http://www.opengl.org/registry/api/GL/glcorearb.h}{\texttt{glcorearb.h}}, \verb|gl3.h|, \verb|glu.h| or \verb|windows.h|. However, if \verb|<boost/static_assert.hpp>| is included, then \href{http://www.boost.org/doc/libs/release/libs/static_assert/}{\texttt{Boost.StaticAssert}} will be used to provide compile-time errors. Otherwise, if using a C++11 compiler, the standard \verb|static_assert| will be used instead. If neither is available, GLM will use its own implementation of \verb|static_assert|.
Shader languages like GLSL often feature so-called swizzle operators, which may be used to freely select and arrange a vector's components. For example, \verb|variable.x|, \verb|variable.xzy| and \verb|variable.zxyy| respectively form a scalar, a 3D vector and a 4D vector. The result of a swizzle expression in GLSL can be either an R-value or an L-value. Swizzle expressions can be written with characters from exactly one of \verb|xyzw| (usually for positions), \verb|rgba| (usually for colors), or \verb|stpq| (usually for texture coordinates).
\begin{glslcode}
vec4 A;
vec2 B;
B.yx = A.wy;
B = A.xx;
vec3 C = A.bgr;
vec3 D = B.rsz; // Invalid, won't compile
\end{glslcode}
GLM optionally supports some of this functionality, through the methods described in the following sections. Swizzle operators can be enabled by defining \verb|GLM_SWIZZLE| before including any GLM header files, or as part of your project's build process.
Visual C++ supports, as a \emph{non-standard language extension}, anonymous \verb|struct|s in \verb|union|s. This enables a very powerful implementation of swizzle operators on Windows, which both allows L-value swizzle operators and makes the syntax for it closer to GLSL's. This implementation of the swizzle operators is only enabled when the language extension is enabled and \verb|GLM_SWIZZLE| is defined.
This versions returns implementation-specific objects that \emph{implicitly convert} to their respective vector types. Unfortunately, these extra types can't be directly used by GLM functions; the programmer must instead convert a swizzle-made \say{vector} to a conventional vector type or call the swizzle object's \verb|operator()|.
To enable compile-time messaging, define \verb|GLM_MESSAGES| before any inclusion of \glmheader{glm}. The messages are generated once per build, assuming your compiler supports \verb|#pragma message|.
GLM may implement certain features that require the presence of a minimum C++ standard. A programmer can mandate compatibility with particular revisions of C++ by defining \verb|GLM_FORCE_CXX|** before any inclusion of \glmheader{glm} (where ** is one of \verb|98|, \verb|03|, \verb|11|, and \verb|14|).
GLM provides some SIMD (Single instruction, multiple data) optimizations based on compiler intrinsics, which will be automatically utilized based on compiler's arguments. For example, if a program is compiled in Visual C++ with \verb|/arch:AVX| set, certain GLM functionality will use AVX instructions.
In addition, GLM provides specialized \verb|vec4|, \verb|quat|, and \verb|mat4| implementations through the \verb|GLM_GTX_simd_vec4|, \verb|GLM_GTX_simd_quat|, and \verb|GLM_GTX_simd_mat4| extensions.
A programmer can force GLM to use a particular set of intrinsics with the following defines: \verb|GLM_FORCE_SSE2|, \verb|GLM_FORCE_SSE3|, \verb|GLM_FORCE_SSE4|, \verb|GLM_FORCE_AVX| or \verb|GLM_FORCE_AVX2|.
Intrinsics may also be disabled entirely by defining \verb|GLM_FORCE_PURE| before any inclusion of \glmheader{glm}. If \verb|GLM_FORCE_PURE| is defined, then including any SIMD extension will generate a compiler error.
To gain a bit of performance, a programmer can define \verb|GLM_FORCE_INLINE| before any inclusion of \glmheader{glm} to force the compiler to inline GLM code.
The member function \verb|length()| returns the dimensionality (number of components) of any GLSL matrix or vector type.
\begin{cppcode}
#include <glm/glm.hpp>
void foo(vec4 const & v)
{
int Length = v.length(); // returns 4
}
\end{cppcode}
There are two problems with this function.
First, it returns a \verb|int| (signed) despite typically being used with code that expects a \verb|size_t| (unsigned). To force a \verb|length()| member function to return a \verb|size_t|, define the \verb|GLM_FORCE_SIZE_T_LENGTH| preprocessor option.
GLM also defines the \verb|typedef| \verb|glm::length_t| to identify the returned type of \verb|length()|, regardless of whether \verb|GLM_FORCE_SIZE_T_LENGTH| is set.
\begin{cppcode}
#define GLM_FORCE_SIZE_T_LENGTH
#include <glm/glm.hpp>
void foo(vec4 const & v)
{
glm::size_t Length = v.length();
}
\end{cppcode}
Second, \verb|length()| shares its name with \verb|glm::length(|*\verb|vec|*\verb| const & v)|, which is used to return a vector's Euclidean length. Developers familiar with other vector math libraries may be used to their equivalent of \verb|glm::length(|*\verb|vec|*\verb| const & v)| being defined as a member function, may thus ask for a vector's dimensionality when they intend to ask for its Euclidean length.
As of GLM 0.9.7.0, GLM also provides the \verb|GLM_META_PROG_HELPERS|, which enables \verb|static| members that provide information about vector, matrix, and quaternion types at compile time in a manner suitable for template metaprogramming.
By default, the nullary (zero-argument) constructors of vectors and matrices initialize their components to zero, as demanded by the GLSL specification. Such behavior is reliable and convenient, but sometimes unnecessary. Disable it at compile time by defining \verb|GLM_FORCE_NO_CTOR_INIT|.
To instead require all conversions between GLM types to be explicit (making implicit conversions a compiler error), define \verb|GLM_FORCE_EXPLICIT_CTOR|.
\begin{cppcode}
#define GLM_FORCE_EXPLICIT_CTOR
#include <glm/glm.hpp>
// This function is the same as above.
void foo()
{
glm::ivec4 a;
glm::vec4 b(a); // Explicit conversion, OK
glm::vec4 c = a; // Implicit conversion, ERROR
}
\end{cppcode}
\section{Stable Extensions}
GLM provides additional functionality on top of that provided by GLSL, including (but not limited to) quaternions, matrix transformations, random number generation, and color space conversion.
All additional functionality is part of the \verb|glm| namespace, and can be enabled by including the relevant header file. An included extension will also provide any core headers or other extensions it depends on.
\begin{cppcode}
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using glm::vec3;
using glm::vec4;
using glm::mat4;
void foo()
{
vec4 Position = vec4(vec3(0.0f), 1.0f);
mat4 Model = glm::translate(mat4(1.0f), vec3(1.0f));
vec4 Transformed = Model * Position;
}
\end{cppcode}
Descriptions of the most stable extensions follow.
Define functions that generate common transformation matrices.
The matrices generated by this extension use standard OpenGL fixed-function conventions. For example, the \verb|lookAt| function generates a transform from world space into the specific eye space that the projective matrix functions (\verb|perspective|, \verb|ortho|, etc) are designed to expect. The OpenGL compatibility specifications define the particular layout of this eye space.
Convert scalar and vector types to packed formats. This extension can also unpack packed data to the original format. The use of packing functions will results in precision lost. However, the extension guarantee that packing a value previously unpacked from the same format will be perform losslessly.
Handle the interaction between pointers and vector, matrix types.
This extension defines an overloaded function, \verb|glm::value_ptr|, which takes any of the core template types (\verb|vec3|, \verb|mat4|, etc.). It returns a pointer to the memory layout of the object. Matrix types store their values in column-major order.
This is useful for uploading data to matrices or copying data to buffer objects.
\begin{cppcode}
// GLM_GTC_type_ptr extension provides a safe solution:
Note: It's possible to implement \glfunction{2}{glVertex} and similar functions by defining an implicit cast from GLM types to pointer types. However, you risk triggering undefined behavior by doing so.
Allow the measurement of the accuracy of a function against a reference implementation. This extension works on floating-point data and provides results in \href{http://ljk.imag.fr/membres/Carine.Lucas/TPScilab/JMMuller/ulp-toms.pdf}{ULP}.
Most fixed-function APIs were deprecated in OpenGL 3.1, and removed entirely in OpenGL 3.2. GLM provides substitutes for some of this lost functionality.
The GLSL keyword \verb|not| is also a keyword in C++. To prevent name collisions, ensure cross compiler support and a high API consistency, the GLSL \verb|not| function has been implemented with the name \verb|not_| (note the underscore).
GLM supports GLSL precision qualifiers through prefixes instead of qualifiers. For example, additionally to \verb|vec4|, GLM exposes \verb|lowp_vec4|, \verb|mediump_vec4| and \verb|highp_vec4| types.
Similarly to GLSL, GLM precision qualifiers are used to handle trade-off between performances and precision of operations in term of ULPs.
By default, all the types use high precision.
\begin{glslcode}
// Using precision qualifier in GLSL:
ivec3 foo(in vec4 v)
{
highp vec4 a = v;
mediump vec4 b = a;
lowp ivec3 c = ivec3(b);
returnc;
}
\end{glslcode}
\begin{cppcode}
// Using precision qualifier in GLM:
#include <glm/glm.hpp>
ivec3 foo(const vec4 & v)
{
highp_vec4 a = v;
medium_vec4 b = a;
lowp_ivec3 c = glm::ivec3(b);
returnc;
}
\end{cppcode}
\newpage{}
\section{FAQ}
\subsection{Why does GLM follow the GLSL specification?}
Everyone and their dog has their own idea of what should constitute a math library. The designers of GLSL (the OpenGL ARB) make a living on deciding what should be in its own math library; why not learn from the best and stick to a proven convention?
GTX extensions are considered \emph{experimental}, and may thus introduce breaking changes without warning (though in practice this doesn't happen often). GTC extensions are considered \emph{stable}, and are therefore unlikely to introduce radical changes. Core libraries are based entirely on functionality provided by GLSL, and can safely be relied upon. The GTX and GTC extension system provides a way to experiment with new GLM functionality, in the hopes of eventually promoting it to a GTC extension. OpenGL itself is developed in much the same way.
%\subsection{Where can I ask more questions about GLM??}
%
%A good place is the \href{http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=postlist&Board=10&page=1}{OpenGL Toolkits forum} on \href{http://www.opengl.org/}{OpenGL.org}.
The Doxygen-generated documentation includes a complete list of all extensions available, and can be found right \href{http://glm.g-truc.net/html/index.html}{here}.
\textbf{Absolutely not!} GLM uses many common names, such as \verb|any|, \verb|scale|, and \verb|length|. Haphazardly writing \verb|using namespace glm;| will almost certainly result in name collisions. Instead, either prefix GLM calls with \verb|glm::|, or pull individual types or functions into your namespace with \verb|using glm::|*, where * is some desired name.
GLM is designed for convenience over performance. \emph{That being said}, the most frequently-used operations are optimized to the fullest reasonable extent. Approximations and SIMD-flavored structures are provided as well, in case they're needed.
You should not have any warnings, even in \verb|/W4| mode. However, if you expect such level for you code, then you should ask for the same level to the compiler by at least disabling the Visual C++ language extensions (\verb|/Za|) which generates warnings when used. If these extensions are enabled, then GLM will take advantage of them and the compiler will generate warnings.
Such behavior is the result of a domain error that follows the precedent set by C and C++. For example, it's a domain error to pass a null vector (all zeroes) to glm::normalize, or even to pass a negative number into \verb|std::sqrt|.
\textbf{All angles in GLM are expressed in radians unless otherwise noted.} GLSL does the same thing. GLU uses degrees, however. This used to cause a lot of confusion. For more information, see \href{http://www.g-truc.net/post-0693.html#menu}{here}.
3D planetary engine for seamless planet rendering from space down to the surface. Can use arbitrary resolution of elevation data, refining it to centimeter resolution using fractal algorithms.
\subsubsection{\href{http://www.packtpub.com/opengl-4-0-shading-language-cookbook/book?tag=rk/opengl4-abr1/0811}{OpenGL 4.0 Shading Language Cookbook}}
Leo's Fortune is a platform adventure game where you hunt down the cunning and mysterious thief that stole your gold. Available on PS4, Xbox One, PC, Mac, iOS and Android.
\say{I just returned home to find all my gold has been stolen! For some devious purpose, the thief has dropped pieces of my gold like breadcrumbs through the woods.}
\say{Despite this pickle of a trap, I am left with no choice but to follow the trail.}
\say{Whatever lies ahead, I must recover my fortune.} ---Leopold
\item Ashima Arts and Stefan Gustavson for their work on \href{https://github.com/ashima/webgl-noise}{webgl-noise}, which which is the base of \verb|GLM_GTC_noise|.
\item\href{http://athile.net/library/wiki/index.php?title=Athile_Technologies}{Arthur Winters} for contributing to the swizzle operator implementation.
\item Joshua Smith and Christoph Schied for their contributions to the swizzle operator implementation.
\item Guillaume Chevallereau for providing and maintaining the \href{http://my.cdash.org/index.php?project=GLM}{nightly build system}.
\item Ghenadii Ursachi for \verb|GLM_GTX_matrix_interpolation|.
\item Mathieu Roumillac for providing some implementation ideas.
\item\href{http://www.zeuscmd.com/}{Grant James} for non-square matrix multiplication (e.g. \verb|mat3 * 3x2|)
\item GLM's users! Without you, there is no GLM!
\end{itemize}
\subsection{Quotes from the web}
\say{I am also going to make use of boost for its time framework and the matrix library GLM, a GL Shader-like Math library for C++. A little advertise for the latter which has a nice design and is useful since matrices have been removed from the latest OpenGL versions.}
\say{OpenGL Mathematics Library (GLM): Used for vector classes, quaternion classes, matrix classes and math operations that are suited for OpenGL applications.}
\begin{flushright}
---\href{http://3dgep.com/?p=1116}{Jeremiah van Oosten}
\end{flushright}
\say{Today I ported my code base from my own small linear algebra library to GLM, a GLSL-style vector library for C++. The transition went smoothly.}