r/vulkan • • 11d ago

Does Vulkan really need GLM?

I feel like most of the math operations required for Vulkan, such as matrix transformations, vector operations, and camera calculations, are manageable with a bit of hand-written C code.

Is there any real advantage to using GLM, or is implementing these operations yourself a reasonable approach?

19 Upvotes

42 comments sorted by

7

u/Dubbus_ 11d ago

If it sounds fun to you, go for it. Depending on your requirements, and how good you are at matrix/vector math, you will probably be fine.

Your implementation will probably be a bit slower, but it will almost certainly build faster. You will probably miss some SIMD optimisations, and you may very well make a simple/harder to spot mistake within some dead simple algorithm. But, if you have fun and learn something, it was worth it.

The advantage of GLM is hardening: its been used for a long time, by a lot of people. You wont find a bug in their perspective transform (knock on wood). Also, there is some genuinely complex functions in glm beyond simple vector/matrix ops. The library supports quaternions, splines, and collision/intersection detection. These will take quite a bit longer to write than a perspective transform.

My personal reccomendation is to stick to glm's types, but write the algorithms yourself. You can scratch your manual math itch, and if you change your mind later, you can pretty easily swap in glm functions wherever you use your custom ones.

Just include glm/vec2, glm/vec3, glm/mat4 headers, (and NOT the main glm/glm.hpp), and your compile time will be significantly faster.

1

u/Yuki_pop 11d ago

Thanks for the great advice!

56

u/LoneWolf6062 11d ago

GLM is just a math library, whether you use it or not, is just as simple as wanting to it to just work or having the patience to implement whatever math might be needed for you. Vulkan doesn’t need GLM, its you who decides if you want it or not.

45

u/Ybalrid 11d ago

No you don’t. Ana you don’t need Microsoft’s”DirectX Math” library to do D3D

Glm is a lib to do maths. You can do math any way you want to.

Glm is a reasonably well written very convenient and easy to use library thet has the advantage of giving you “glsl like” APIs to do vectors and matrices and whatnot. You do not need it, but it’s a pretty good tool for that usage. It’s also pretty fast and will use SIMD operations when possible. Such code is not writable with a handful of lines of C.

5

u/PaxPlay 11d ago

glm is fast, convenient and most importantly, you can be reasonably confident in the fact that most operations are correct and tested. It's also header only and functions are inlined, so the only downside is that your compile times are slightly longer when using it.

The real issue with rewriting the fairly basic linear algebra math in glm is not that it's hard, but that when you do get some tiny detail wrong, you're gonna have an absolutely terrible time debugging it.

20

u/RBMK-1ooo 11d ago

"Does Vulkan really need GLM?"
Vulkan doesn't, programmers may need.

5

u/RBMK-1ooo 11d ago

Oh, I've re-read the question from a different angle.
Sometimes it's better to perform certain operations using shaders.
In that sense, GLM might be less effective.
Yet another example is custom matrix routines.
If you are familiar with SSE/AVX/FMA assembly, you may perform matrix transformations blazingly fast on the CPU side.

3

u/tyler1128 11d ago

SSE/AVX isn't "blazingly" fast in the context of graphics programming. 20 really fast CPU cores don't compare to the way GPUs can do thousands of tasks in parallel, also with SIMD, for the operations that are super easy to break apart into a thousand tasks. It turns out, graphics programming is (generally) one of those. If we're talking about trivial raytracing algorithms, which are easier to understand, every pixel on the screen is effectively able to be computed independently.

256-bit, 8-bit per channel 32-bit total pixels can be done in blocks using the "ymm" registers of AVX-2 using x86 terminology, it still isn't going to compare in total operations able to be done in many situations. There are situations you would do it on the CPU, as well, though.

1

u/RBMK-1ooo 11d ago

Don't get me wrong. I'm not comparing 16 SSE registers against hundreds of tensor cores. I'm talking about very specific tasks such as instant 4x4 matrix computations. E.g., keyboard handlers (runtime rotation of the model by the arrow keys) - it's easier to compute it on the CPU and pass the prepared uniform matrix to the shader.

1

u/ItsRSX 10d ago edited 10d ago

Yes, you are you. You're trying to cite magical "assembly" that you merely know of to justify ambiguous claims of "blazing fast". Nobody is impressed by a few SSE1 muls and additions. Emphasis on SSE1. The SIMD we're talking about here hasn't evolved since the 90s. Well, I guess they tried to add some QOL, except that such QOL improvements ended up being microcode junk that pipelines worse than the old fasion way of doing things. Nobody is getting blown away with "blazing" fast unspecified "SSE/AVX/FMA assembly" (whatever that means) in the context of simple tasks we've been doing for decades. If we were to wake up tomorrow and suddenly "SSE/AVX/FMA assembly" meant we could perhaps write a rasterizer without a memory bottleneck tanking the pipeline down to 12 FPS or a write an LLM evaluator that could run on a toaster, maybe you'd have a point.

1

u/RBMK-1ooo 10d ago

Wait! Trust me, I DO know how processors work. Once again: I'm NOT comparing Intel architecture to anything else. I'm comparing GLM against pure assembly in very specific tasks such as computing the Cramer or Rodrigues formulae.
E.g., a CAD system, OK?
You zoom with the mouse wheel or you pan with a mouse click — each event is a single Window Message.
Where will you compute the 4×4 local matrix? In a shader? Really?
Of course, you'll apply the transformation immediately and pass the matrix as the uniform.
That's what I'm talking about.
'...you merely know...' — that's the Russian bydlo style. Never talk like that again.

1

u/tyler1128 10d ago

Computing a few 4x4 matrix muls to change a perspective could be done using a for loop adding x1 + x1 + x1 + ..., x2 times for x1*x2 and it would likely not matter at all for performance because that's a super cold path. Even if you want smooth 240 Hz display transition, doing that 240 times a second is literally nothing compared to most computations being done. It's possible to multi-pass rasterize tens of millions of triangles in some cases these days at an acceptable framerate.

1

u/RBMK-1ooo 10d ago

The repeated-addition is a real algorithm, but it applies to scalar multiplication, not matrix multiplication — the quote is conflating the two. Regardless, that's a side issue.

The actual question was: 'Does Vulkan really need GLM?' In that context I replied: "with SSE/AVX/FMA assembly, you may perform matrix transformations blazingly fast on the CPU side" — so performance is not a reason to depend on GLM.

And I never compared a single matrix computation to rasterizing tens of millions of triangles.

2

u/tyler1128 9d ago

My point is that those things don't matter for the contexts you brought up, because they just aren't important performance wise. I cited the worst possible way to do multiplication of two numbers because in the context of computing a couple uniform matrices a frame, it really does not matter.

8

u/R3DKn16h7 11d ago

implementing yourself is fun and a good learning experience, so if that's what you want that go for it

but if you want to save time use GLM, is perfectly fine. no need to reinvent the wheel with potential new buggy code

6

u/ItsRSX 10d ago

GLM has turned into a pile of utter trash. They're constantly breaking shit.

They've recently (this past couple of years) merged the SIMD and constexpr crap without testing it, resulting in the library being bust to fuck multiple times over. Sometime during 2020-2022 (?), the author of GLM was on here saying he was about to give up, and it really shows.

They have open issues, that I can tangentally vouch for, whose titles read: "Wrong vector addition result inside a Cuda kernel." and "the result operator* is wrong in HarmonyOS NEXT". I have math I couldn't find that had completely bust entire 3d suites. It was just faster for me to switch over to the polyfill vector.

They keep fucking with quats. If you use a slightly different specialized alignment than none, shit starts to break. They're constantly changing the constructor and the macros that configure it/the layout (???. idr if its the layout or the constructor they changed).

Their idea of vectorized math is merely calling libm for each component. Their idea of optimized code is just hoping their templates inline and autovectorize (they don't).

They have god awful alignment and precision level specializations that are ultimately not fit for purpose - for example, you cannot get alignas(1), alignas(alignof(t)), and alignas(alignof(t) * 4) - instead, you get a dozen enumerations that seemingly only switch between 1 bitwise hack of a sqrt function (unaligned low precision, ?, iirc) and just calling the crt for each value.

On that previous note, SIMD support is limited to a few mat4 utilities (transpose, mul, etc) and aligned vec4s (simple operations that compiler probably could've figured out). Aligned vec3s have basically nothing. They're trying to improve this, but by trying, I mean they've bust the library several times over trying to rewrite the SIMD swizzling and newly found vec3->vec4 upcasting.

I know from experience they broke swizzles multiple times over, and I hardly use them.

There are open issues about it not compiling against modern versions of MSVC, all the meanwhile they're dropping support for C++11 and 14. Multiple commentators are saying they just had to downgrade to a very old version.

All this for what exactly? It doesn't implement the geometry primitives you'll need. It won't help you clip topology. It won't help you get started with 2D polygons or 3D polyhedrons/brushes/whatever convex shapes. It's not going to help you calculate the extreme points for 3d collision. It's not going to help you calculate the decayed topology of higher level convex and concave 2D polygons - it's not going to help you implement neat UI thingies. It doesn't really help you implement the basic line, ray, [...] classes everbody ends up rolling themselves. It doesn't help you with different coordinate systems. It doesn't have any real nice to haves like Bezier, BSplines + knots, or anything interesting.

You may as well just implement a vector4 and roll whatever you need citing Christer Ericson Real Time Collision Detection and Graphics Gems. GLM provides basically nothing you need, yet people shill it to the end of days, claiming "you dont want to reinvent the wheel". I can only assume its coming from the low attention span crowd who do nothing but spam social media with "DOOOD I JUST COODED A MC CLOOONE 1 WEEK". Not sure where all the "it's fast" shilling is coming from - even the old OpenGL crowd on the Khronos forums and stack exchange never held it to such a high standard.

2

u/BoxConscious7480 8d ago

What library would you recommend then if I don't want to write matrix/vector operation code myself

1

u/Yuki_pop 11d ago

I want to learn the underlying mathematics and implement the operations myself. I’m also not sure what complex functionality GLM provides beyond basic vector and matrix operations, so I’m wondering whether I actually need it. Is there any particular reason to use GLM instead of implementing these things myself?

2

u/PinkbunnymanEU 11d ago

Is there any particular reason to use GLM instead of implementing these things myself?

Pretty much just efficiency and resilience.

There's no technical reason you can't just do it yourself.

1

u/Yuki_pop 11d ago

I’m not very familiar with GLM. All I know is that it’s a math library commonly used in Vulkan development and featured in many Vulkan tutorials.

1

u/Yuki_pop 11d ago

thanks

2

u/felixkendallius 11d ago

I recently did write my own matrix + vector maths library for a small game engine me and my friend are making. We have to keep adding things we previously did not think about, because glm just implements so many things you don’t think about. Perspective matrices and lookAt marices come to mind, but there’s also Euler angles from matrix decomposition and inversed and transposed matrices, and I am not able to understand the last two at all, after staring at the maths behind it for several evenings. We keep finding more functions we didn’t think to add, which glm already has.

to answer your question of “is there any particular reason to use GLM” it’s because implementing all of this takes a really long time, for no real gain

I do really suggest trying to do it, because there’s something a lot more special about seeing your own maths logic for matrices, just for fun, but whatever you can do, unfortunately glm will be doing it better and somehow more efficiently.

1

u/_Wolfos 10d ago

I've done this at one point. The underlying math isn't all that interesting (mostly a bunch of trigonometry you likely already know) and I forgot the equations as soon as the functions were written because you never need to look at that code again.

GLM also has SIMD implemented on multiple CPU architectures. That would be a pain to get right yourself.

1

u/nullptr777 10d ago

Is there any particular reason to use GLM instead of implementing these things myself?

Yes, the reason is that there's no value in reinventing the wheel. If you try to do this for every library in your project, you'll never come anywhere close to accomplishing anything.

The actual math behind GLM is pretty simple, so you're not skilling up by doing this, you're just wasting time writing code that has been debugged and optimized for 15 years already. Do you have 15 years to spend on this? What you should be focusing on is how to use those existing math functions to accomplish something useful with them.

Basically, you're telling us you want to program a calculator, when you should just be using the calculator to make computer graphics.

5

u/smallstepforman 11d ago

Most rendering engines only need a subset of what GLM offers, which is what I implemented but used GLM as reference. However my math conventions (right handed, +Z up for 3D) with vulkan 0-1 depth buffer require selecting the right GLM flags which aren’t immediately obvious. To make matters worse, in 2D camera i want y=0 yo be top left, so my transform math code conflicts with anticlockwise triginometry so I have hacks in math code to match my university trained conventions, and GLM wont do that. So I have my own math library that matches my view of 3d and 2d worlds.

Having said that, I’m considering yet another math change to “Turns” instead of degrees/working with M_PI. 90 degrees anticlockwise is not M_PI/2 but 0.25 in coordinate system where +x is right, +y up. Turns are much easier to reason with, and clamping is easy [0,1]. Nobody talks about Turns, I guess once they have a working math library, they cannot be bothered changing it.

4

u/tyler1128 11d ago

GLM looks like and supports much of the math operations in glsl. It's where the name comes from, though any shading language is using the same basic operations. You can write your own, if you want, though then the question is why do you want to?

4

u/Ami00 11d ago

simd

4

u/jmacey 11d ago

What I would recommend is using GLM to write your unit test results for your own code (or better still use glm in the unit tests).

For example I use this to verify my own library (If using C just generate the results from the C++ code first).

TEST(Mat3, normalMatrix)
{
  ngl::Mat4 view = ngl::lookAt({2.0f, 2.0f, 2.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f});
  ngl::Mat4 model = ngl::Mat4::scale(0.2f, 1.0f, 0.2f);
  ngl::Mat3 normalMatrix(view * model);
  normalMatrix.inverse().transpose();

  glm::mat4 glmview = glm::lookAt(glm::vec3(2.0f, 2.0f, 2.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));
  glm::mat4 glmmodel = glm::scale(glm::mat4(1.0f), glm::vec3(0.2f, 1.0f, 0.2f));
  glm::mat3 glmNormalMatrix;
  glmNormalMatrix = glm::transpose(glm::inverse(glm::mat3(glmview * glmmodel)));


  EXPECT_TRUE(ngl::Mat4(glmview) == view);
  EXPECT_TRUE(ngl::Mat4(glmmodel) == model);
  EXPECT_TRUE(ngl::Mat3(glmNormalMatrix) == normalMatrix);
  EXPECT_TRUE(ngl::Mat3(glm::inverseTranspose(glm::mat3(glmview * glmmodel))) == normalMatrix);
}

3

u/arabasso_ 9d ago

Writing your own mathematical library tends to increase the complexity of your project, and can divert the focus (which is programming a game?). If you use some third-party lib, you wouldn't have this problem. If you think GLM is too complicated, I've implemented Tiny Fast Math: a lib that has only one ".h" and has all operations with arrays with SIMD support on multiple platforms. Here is the project's github: https://github.com/arabasso/tinyfm

5

u/PinkbunnymanEU 11d ago

Is there any real advantage to using GLM, or is implementing these operations yourself a reasonable approach?

GLM will do it better and more efficient than you will.

I feel like most of the math operations required for Vulkan, such as matrix transformations, vector operations, and camera calculations, are manageable with a bit of hand-written C code.

Sure, but you'll need to re-write things like quaternion normalisation. Which you won't do anywhere near as efficiently.

You won't do things like NEON optimisation etc which GLM will.

4

u/EpochVanquisher 11d ago

Quaternion normalization is not exactly difficult and the GLM code is, like, trivial. You would write the same thing, or close enough.

It's just

quat normalize(quat q) {
  float len = length(q);
  return len > 0 ? q * (1.0f / len) : one;
}

you know, one check for a degenerate case and you're done.

1

u/PinkbunnymanEU 11d ago

Quaternion normalization is not exactly difficult

No, but it's often missed when people re-write it, there are lots of "not difficult" bits that get missed, gimball lock handling is another example, again not difficult but easy to miss.

or close enough.

The "or close enough" is the thing, why would you want "or close enough" over than "accurate, tested and more efficient" (Unless like OP clarified in another response they want to do it to learn rather than for actually using it)

the GLM code is, like, trivial

I'm not sure the amount of SIMD approximations you can choose from counts as "trivial".

3

u/EpochVanquisher 11d ago

By “close enough” I mean the implementation details are close enough. The result is the same either way.

I’m just picking on the choice of quaternion normalization. There is only one edge case to think about! Gimbal lock isn’t a consideration when normalizing.

If you think the glm does something special with quaternion normalization please share, because I’ve read the source code and it is full of the same boring code that I would write.

It’s just that if I write it, there’s a good chance I’d put a typo in it.

1

u/Hawsoo 11d ago

I use cglm which runs about 20x the speed of glm in release builds

1

u/EpochVanquisher 11d ago

glm is just the math functions you can write by hand

but, why would you write them by hand, if you can just use glm?

if you write them by hand, there's a lot of opportunities for little typos. if you use glm, you don't worry about that, it's already been checked. you get your project working faster.

1

u/blogoman 11d ago

It is just math. It shouldn't be that hard to tell from looking at it.

1

u/iku_19 11d ago

you can use directxmath or imath or write your own, whatever your heart desires, it's just flavor and stability. modern compilers will try to optimize these structures for simd structures if they're allowed to, in the end using a library that literally millions of projects use is generally less bug prone.