我的渲染技术进阶之旅GLM使用手册 GLM 0.9.9 Manual

Posted 字节卷动

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我的渲染技术进阶之旅GLM使用手册 GLM 0.9.9 Manual相关的知识,希望对你有一定的参考价值。

转载的原因

OpenGL Mathematics (GLM) 是基于 OpenGL 着色语言 (GLSL) 规范的图形软件的仅头文件 C++ 数学库。

在我之前的博客 【我的OpenGL学习进阶之旅】OpenGL ES开发如何引入GLM(OpenGL Mathematics)库? 有介绍如何引入GLM库。

但是有时候得查一下GLM库的用法,就得去查看【GLM的Manual文档】。因为一些众所周知的原因,有时候这些网站打开比较慢,因此将这篇【GLM的Manual文档】摘抄下来,方便后续查看。

下面是转载的内容


GLM 0.9.9 Manual


Table of Contents


Licenses

The Happy Bunny License (Modified MIT License)

Copyright © 2005 - G-Truc Creation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
“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 “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.

The MIT License

Copyright © 2005 - G-Truc Creation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
“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 “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.


1. Getting started

1.1. Using global headers

GLM is a header-only library, and thus does not need to be compiled. We can use GLM’s implementation of GLSL’s mathematics functionality by including the <glm/glm.hpp> header:

#include <glm/glm.hpp>

To extend the feature set supported by GLM and keeping the library as close to GLSL as possible, new features are implemented as extensions that can be included thought a separated header:

// Include all GLM core / GLSL features
#include <glm/glm.hpp> // vec2, vec3, mat4, radians

// Include all GLM extensions
#include <glm/ext.hpp> // perspective, translate, rotate

glm::mat4 transform(glm::vec2 const& Orientation, glm::vec3 const& Translate, glm::vec3 const& Up)

    glm::mat4 Proj = glm::perspective(glm::radians(45.f), 1.33f, 0.1f, 10.f);
    glm::mat4 ViewTranslate = glm::translate(glm::mat4(1.f), Translate);
    glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, Orientation.y, Up);
    glm::mat4 View = glm::rotate(ViewRotateX, Orientation.x, Up);
    glm::mat4 Model = glm::mat4(1.0f);
    return Proj * View * Model;

Note: Including <glm/glm.hpp> and <glm/ext.hpp> is convenient but pull a lot of code which will significantly increase build time, particularly if these files are included in all source files. We may prefer to use the approaches describe in the two following sections to keep the project build fast.

1.2. Using separated headers

GLM relies on C++ templates heavily, and may significantly increase compilation times for projects that use it. Hence, user projects could only include the features they actually use. Following is the list of all the core features, based on GLSL specification, headers:

#include <glm/vec2.hpp>               // vec2, bvec2, dvec2, ivec2 and uvec2
#include <glm/vec3.hpp>               // vec3, bvec3, dvec3, ivec3 and uvec3
#include <glm/vec4.hpp>               // vec4, bvec4, dvec4, ivec4 and uvec4
#include <glm/mat2x2.hpp>             // mat2, dmat2
#include <glm/mat2x3.hpp>             // mat2x3, dmat2x3
#include <glm/mat2x4.hpp>             // mat2x4, dmat2x4
#include <glm/mat3x2.hpp>             // mat3x2, dmat3x2
#include <glm/mat3x3.hpp>             // mat3, dmat3
#include <glm/mat3x4.hpp>             // mat3x4, dmat2
#include <glm/mat4x2.hpp>             // mat4x2, dmat4x2
#include <glm/mat4x3.hpp>             // mat4x3, dmat4x3
#include <glm/mat4x4.hpp>             // mat4, dmat4
#include <glm/common.hpp>             // all the GLSL common functions: abs, min, mix, isnan, fma, etc.
#include <glm/exponential.hpp>        // all the GLSL exponential functions: pow, log, exp2, sqrt, etc.
#include <glm/geometric.hpp>          // all the GLSL geometry functions: dot, cross, reflect, etc.
#include <glm/integer.hpp>            // all the GLSL integer functions: findMSB, bitfieldExtract, etc.
#include <glm/matrix.hpp>             // all the GLSL matrix functions: transpose, inverse, etc.
#include <glm/packing.hpp>            // all the GLSL packing functions: packUnorm4x8, unpackHalf2x16, etc.
#include <glm/trigonometric.hpp>      // all the GLSL trigonometric functions: radians, cos, asin, etc.
#include <glm/vector_relational.hpp>  // all the GLSL vector relational functions: equal, less, etc.

The following is a code sample using separated core headers and an extension:

// Include GLM core features
#include <glm/vec2.hpp>           // vec2
#include <glm/vec3.hpp>           // vec3
#include <glm/mat4x4.hpp>         // mat4
#include <glm/trigonometric.hpp>  //radians

// Include GLM extension
#include <glm/ext/matrix_transform.hpp> // perspective, translate, rotate

glm::mat4 transform(glm::vec2 const& Orientation, glm::vec3 const& Translate, glm::vec3 const& Up)

    glm::mat4 Proj = glm::perspective(glm::radians(45.f), 1.33f, 0.1f, 10.f);
    glm::mat4 ViewTranslate = glm::translate(glm::mat4(1.f), Translate);
    glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, Orientation.y, Up);
    glm::mat4 View = glm::rotate(ViewRotateX, Orientation.x, Up);
    glm::mat4 Model = glm::mat4(1.0f);
    return Proj * View * Model;

1.3. Using extension headers

Using GLM through split headers to minimize the project build time:

// Include GLM vector extensions:
#include <glm/ext/vector_float2.hpp>                // vec2
#include <glm/ext/vector_float3.hpp>                // vec3
#include <glm/ext/vector_trigonometric.hpp>         // radians

// Include GLM matrix extensions:
#include <glm/ext/matrix_float4x4.hpp>              // mat4
#include <glm/ext/matrix_transform.hpp>             // perspective, translate, rotate

glm::mat4 transform(glm::vec2 const& Orientation, glm::vec3 const& Translate, glm::vec3 const& Up)

    glm::mat4 Proj = glm::perspective(glm::radians(45.f), 1.33f, 0.1f, 10.f);
    glm::mat4 ViewTranslate = glm::translate(glm::mat4(1.f), Translate);
    glm::mat4 ViewRotateX = glm::rotate(ViewTranslate, Orientation.y, Up);
    glm::mat4 View = glm::rotate(ViewRotateX, Orientation.x, Up);
    glm::mat4 Model = glm::mat4(1.0f);
    return Proj * View * Model;

1.4. Dependencies

GLM does not depend on external libraries or headers such as <GL/gl.h>, <GL/glcorearb.h>, <GLES3/gl3.h>, <GL/glu.h>, or <windows.h>.

1.5. Finding GLM with CMake

When installed, GLM provides the CMake package configuration files glmConfig.cmake and glmConfigVersion.cmake.

To use these configurations files, you may need to set the glm_DIR variable to the directory containing the configuration files <installation prefix>/lib/cmake/glm/.

Use the find_package CMake command to load the configurations into your project. Lastly, either link your executable against the glm::glm target or add $GLM_INCLUDE_DIRS to your target’s include directories:

set(glm_DIR <installation prefix>/lib/cmake/glm) # if necessary
find_package(glm REQUIRED)
target_link_libraries(<your executable> glm::glm)

To use GLM as a submodule in a project instead, use add_subdirectory to expose the same target, or add the directory to your target’s

add_subdirectory(glm)
target_link_libraries(<your executable> glm::glm)
# or
target_include_directories(<your executable> glm)

2. Preprocessor configurations

2.1. GLM_FORCE_MESSAGES: Platform auto detection and default configuration

When included, GLM will first automatically detect the compiler used, the C++ standard supported, the compiler arguments used to configure itself matching the build environment.

For example, if the compiler arguments request AVX code generation, GLM will rely on its code path providing AVX optimizations when available.

We can change GLM configuration using specific C++ preprocessor defines that must be declared before including any GLM headers.

Using GLM_FORCE_MESSAGES, GLM will report the configuration as part of the build log.

#define GLM_FORCE_MESSAGES // Or defined when building (e.g. -DGLM_FORCE_SWIZZLE)
#include <glm/glm.hpp>

Example of configuration log generated by GLM_FORCE_MESSAGES:

GLM: version 0.9.9.1
GLM: C++ 17 with extensions
GLM: Clang compiler detected
GLM: x86 64 bits with AVX instruction set build target
GLM: Linux platform detected
GLM: GLM_FORCE_SWIZZLE is undefined. swizzling functions or operators are disabled.
GLM: GLM_FORCE_SIZE_T_LENGTH is undefined. .length() returns a glm::length_t, a typedef of int following GLSL.
GLM: GLM_FORCE_UNRESTRICTED_GENTYPE is undefined. Follows strictly GLSL on valid function genTypes.
GLM: GLM_FORCE_DEPTH_ZERO_TO_ONE is undefined. Using negative one to one depth clip space.
GLM: GLM_FORCE_LEFT_HANDED is undefined. Using right handed coordinate system.

The following subsections describe each configurations and defines.

2.2. GLM_FORCE_PLATFORM_UNKNOWN: Force GLM to no detect the build platform

GLM_FORCE_PLATFORM_UNKNOWN prevents GLM from detecting the build platform.

2.3. GLM_FORCE_COMPILER_UNKNOWN: Force GLM to no detect the C++ compiler

GLM_FORCE_COMPILER_UNKNOWN prevents GLM from detecting the C++ compiler.

2.4. GLM_FORCE_ARCH_UNKNOWN: Force GLM to no detect the build architecture

GLM_FORCE_ARCH_UNKNOWN prevents GLM from detecting the build target architecture.

2.5. GLM_FORCE_CXX_UNKNOWN: Force GLM to no detect the C++ standard

GLM_FORCE_CSS_UNKNOWN prevents GLM from detecting the C++ compiler standard support.

2.6. GLM_FORCE_CXX**: C++ language detection

GLM will automatically take advantage of compilers’ language extensions when enabled. To increase cross platform compatibility and to avoid compiler extensions, a programmer can define GLM_FORCE_CXX98 before
any inclusion of <glm/glm.hpp> to restrict the language feature set C++98:

#define GLM_FORCE_CXX98
#include <glm/glm.hpp>

For C++11, C++14, and C++17 equivalent defines are available:

  • GLM_FORCE_CXX11
  • GLM_FORCE_CXX14
  • GLM_FORCE_CXX17
#define GLM_FORCE_CXX11
#include <glm/glm.hpp>

// If the compiler doesn’t support C++11, compiler errors will happen.

GLM_FORCE_CXX17 overrides GLM_FORCE_CXX14; GLM_FORCE_CXX14 overrides GLM_FORCE_CXX11; and GLM_FORCE_CXX11 overrides GLM_FORCE_CXX98 defines.

2.7. GLM_FORCE_EXPLICIT_CTOR: Requiring explicit conversions

GLSL supports implicit conversions of vector and matrix types. For example, an ivec4 can be implicitly converted into vec4.

Often, this behaviour is not desirable but following the spirit of the library, this is the default behavior in GLM. However, GLM 0.9.6 introduced the define GLM_FORCE_EXPLICIT_CTOR to require explicit conversion for GLM types.

#include <glm/glm.hpp>

void foo()

    glm::ivec4 a;
    ...

    glm::vec4 b(a); // Explicit conversion, OK
    glm::vec4 c = a; // Implicit conversion, OK
    ...

With GLM_FORCE_EXPLICIT_CTOR define, implicit conversions are not allowed:

#define GLM_FORCE_EXPLICIT_CTOR
#include <glm/glm.hpp>

void foo()

    glm::ivec4 a;
    
        glm::vec4 b(a); // Explicit conversion, OK
        glm::vec4 c = a; // Implicit conversion, ERROR
        ...

2.8. GLM_FORCE_INLINE: Force inline

To push further the software performance, a programmer can define GLM_FORCE_INLINE before any inclusion of <glm/glm.hpp> to force the compiler to inline GLM code.

#define GLM_FORCE_INLINE
#include <glm/glm.hpp>

2.9. GLM_FORCE_ALIGNED_GENTYPES: Force GLM to enable aligned types

Every object type has the property called alignment requirement, which is an integer value (of type std::size_t, always a power of 2) representing the number of bytes between successive addresses at which objects of this type can be allocated. The alignment requirement of a type can be queried with alignof or std::alignment_of. The pointer alignment function std::align can be used to obtain a suitably-aligned pointer within some buffer, and std::aligned_storage can be used to obtain suitably-aligned storage.

Each object type imposes its alignment requirement on every object of that type; stricter alignment (with larger alignment requirement) can be requested using C++11 alignas.

In order to satisfy alignment requirements of all non-static members of a class, padding may be inserted after some of its members.

GLM supports both packed and aligned types. Packed types allow filling data structure without inserting extra padding. Aligned GLM types align addresses based on the size of the value type of a GLM type.

#define GLM_FORCE_ALIGNED_GENTYPES
#include <glm/glm.hpp>
#include <glm/gtc/type_aligned.hpp>

typedef glm::aligned_vec4 vec4a;
typedef glm::packed_vec4 vec4p;

2.10. GLM_FORCE_DEFAULT_ALIGNED_GENTYPES: Force GLM to use aligned types by default

GLM allows using aligned types by default for vector types using GLM_FORCE_DEFAULT_ALIGNED_GENTYPES:

#define GLM_FORCE_DEFAULT_ALIGNED_GENTYPES
#include <glm/glm.hpp>

struct MyStruct

    glm::vec4 a;
    float b;
    glm::vec3 c;
;

void foo()

    printf("MyStruct requires memory padding: %d bytes\\n", sizeof(MyStruct));


>>> MyStruct requires memory padding: 48 bytes
#include <glm/glm.hpp>

struct MyStruct

    glm::vec4 a;
    float b;
    glm::vec3 c;
;

void foo()

    printf("MyStruct is tightly packed: %d bytes\\n", sizeof(MyStruct));


>>> MyStruct is tightly packed: 32 bytes

Note: GLM SIMD optimizations require the use of aligned types

2.11. GLM_FORCE_INTRINSICS: Using SIMD optimizations

GLM provides some SIMD optimizations based on compiler intrinsics.
These optimizations will be automatically thanks to compiler arguments when GLM_FORCE_INTRINSICS is defined before including GLM files.
For example, if a program is compiled with Visual Studio using /arch:AVX, GLM will detect this argument and generate code using AVX instructions automatically when available.

It’s possible to avoid the instruction set detection by forcing the use of a specific instruction set with one of the fallowing define:
GLM_FORCE_SSE2, GLM_FORCE_SSE3, GLM_FORCE_SSSE3, GLM_FORCE_SSE41, GLM_FORCE_SSE42, GLM_FORCE_AVX, GLM_FORCE_AVX2 or GLM_FORCE_AVX512.

The use of intrinsic functions by GLM implementation can be avoided using the define GLM_FORCE_PURE before any inclusion of GLM headers. This can be particularly useful if we want to rely on C++14 constexpr.

#define GLM_FORCE_PURE
#include <glm/glm.hpp>

static_assert(glm::vec4::length() == 4, "Using GLM C++ 14 constexpr support for compile time tests");

// GLM code will be compiled using pure C++ code without any intrinsics
#define GLM_FORCE_SIMD_AVX2
#include <glm/glm.hpp>

// If the compiler doesn’t support AVX2 instrinsics, compiler errors will happen.

Additionally, GLM provides a low level SIMD API in glm/simd directory for users who are really interested in writing fast algorithms.

2.12. GLM_FORCE_PRECISION_**: Default precision

C++ does not provide a way to implement GLSL default precision selection (as defined in GLSL 4.10 specification section 4.5.3) with GLSL-like syntax.

precision mediump int;
precision highp float;

To use the default precision functionality, GLM provides some defines that need to added before any include of glm.hpp:

#define GLM_FORCE_PRECISION_MEDIUMP_INT
#define GLM_FORCE_PRECISION_HIGHP_FLOAT
#include <glm/glm.hpp>

Available defines for floating point types (glm::vec\\*, glm::mat\\*):

  • GLM_FORCE_PRECISION_LOWP_FLOAT: Low precision
  • GLM_FORCE_PRECISION_MEDIUMP_FLOAT: Medium precision
  • GLM_FORCE_PRECISION_HIGHP_FLOAT: High precision (default)

Available defines for floating point types (glm::dvec\\*, glm::dmat\\*):

  • GLM_FORCE_PRECISION_LOWP_DOUBLE: Low precision
  • GLM_FORCE_PRECISION_MEDIUMP_DOUBLE: Medium precision
  • GLM_FORCE_PRECISION_HIGHP_DOUBLE: High precision (default)

Available defines for signed integer types (glm::ivec\\*):

  • GLM_FORCE_PRECISION_LOWP_INT: Low precision
  • GLM_FORCE_PRECISION_MEDIUMP_INT: Medium precision
  • GLM_FORCE_PRECISION_HIGHP_INT: High precision (default)

Available defines for unsigned integer types (glm::uvec\\*):

  • GLM_FORCE_PRECISION_LOWP_UINT: Low precision
  • GLM_FORCE_PRECISION_MEDIUMP_UINT: Medium precision
  • GLM_FORCE_PRECISION_HIGHP_UINT: High precision (default)

2.13. GLM_FORCE_SINGLE_ONLY: Removed explicit 64-bits floating point types

Some platforms (Dreamcast) doesn’t support double precision floating point values. To compile on such platforms, GCC has the --m4-single-only build argument. When defining GLM_FORCE_SINGLE_ONLY before including GLM headers, GLM releases the requirement of double precision floating point values support. Effectivement, all the float64 types are no longer defined and double behaves like float.

2.14. GLM_FORCE_SWIZZLE: Enable swizzle operators

Shader languages like GLSL often feature so-called swizzle expressions, which may be used to freely select and arrange a vector’s components. For example, variable.x, variable.xzy and 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 xyzw (usually for positions), rgba (usually for colors), and stpq (usually for texture coordinates).

vec4 A;
vec2 B;

B.yx = A.wy;
B = A.xx;
vec3 C = A.bgr;
vec3 D = B.rsz; // Invalid, won't compile

GLM supports some of this functionality. Swizzling can be enabled by defining GLM_FORCE_SWIZZLE.

Note: Enabling swizzle expressions will massively increase the size of your binaries and the time it takes to compile them!

GLM has two levels of swizzling support described in the following subsections.

2.14.1. Swizzle functions for standard C++ 98

When compiling GLM as C++98, R-value swizzle expressions are simulated through member functions of each vector type.

#define GLM_FORCE_SWIZZLE // Or defined when building (e.g. -DGLM_FORCE_SWIZZLE)
#include <glm/glm.hpp>

void foo()

    glm::vec4 const ColorRGBA = glm::vec4(1.0f, 0.5f, 0.0f, 1.0f);
    glm::vec3 const ColorBGR = ColorRGBA.bgr();

    glm::vec3 const PositionA = glm::vec3(1.0f, 0.5f, 0.0f);
    glm::vec3 const PositionB = PositionXYZ.xyz() * 2.0f;

    glm::vec2 const TexcoordST = glm::vec2(1.0f, 0.5f);
    glm::vec4 const TexcoordSTPQ = TexcoordST.stst();

Swizzle operators return a copy of the component values, and thus can’t be used as L-values to change a vector’s values.

#define GLM_FORCE_SWIZZLE
#include <glm/glm.hpp>

void foo()

  glm::vec3 const A = glm::vec3(1.0f, 0.5f, 0.0f);

  // No compiler error, but A is not modified.
  // An anonymous copy is being modified (and then discarded).
  A.bgr(我的OpenGL学习进阶之旅OpenGL ES开发如何引入GLM(OpenGL Mathematics)库?

我的OpenGL学习进阶之旅OpenGL ES开发如何引入GLM(OpenGL Mathematics)库?以及#include< >和#include“ ”的区别

我的C语言学习进阶之旅什么是.hpp文件?

使用 GLM 正交投影矩阵将三角形顶点放在错误的位置

OpenGL/GLFW/GLM - 键盘输入无响应

如何使用 glm::lookAt() 旋转对象?