C ++向量数学和OpenGL兼容 [英] C++ Vector Math and OpenGL compatible
问题描述
我一直在做很多矢量数学的工作,并为此编写了自己的模板.
I've been doing lots of vector math stuff and wrote my own template for it.
我的要求是很多矢量数学(加法,减法,小数位数,叉积和点积),我还需要能够将我的矢量作为float []传递,以便openGL可以使用它.
My requirements are lots of vector maths (addition, subtraction, scale, cross prod, and dot prod) also I need to be able to pass my vector as a float[] so that openGL can make use of it.
一段时间以来,我一直很开心地使用它,今天一位讲师看到了并and吟.他特别讨厌两件事(我了解其中之一),我对继承的使用,因为继承似乎没有遵循is a
样式.而我的演员(T*)this
,当然,他没有太多解决方案.
I've been using this quite happily for sometime, today a lecturer saw it and groaned. There was two things he particularly hated (one of which I understand), my use of inheritance because it didn't seem to follow an is a
style. And my casting (T*)this
, of course he didn't have much in the way of a solution.
第一: 继承,我需要能够将vec2运用到vec4,因此我设计了这样的向量.
First: The inheritance, I need to be able to make use of vec2 to vec4's so I designed my vectors like this.
template<typename T>
Vector2D
{
public:
getX(), getY(), setX(), setY() ....
};
template<typename T>
Vector3D : public Vector2D<T>
{
public:
getZ(), setZ() ...
}
template<typename T>
Vector4D : public Vector3D<T>
{
public:
getW(), setW() ...
}
为什么这样不好?而且我看不到如何改进它.我需要(想要)能够定义类型并具有某种类型的getter和setter方法.如果我像这样重新安排
Why is this bad? and tbh I can't see how to improve it. I need(want) to be able to define type and have getters and setters of some sort. If I rearranged it like
template<typename T, int _size>
VectorT
我放开了.getX()
,.setX()
的内容,不得不将其替换为.at()
或[]
之类的东西. tbh我更喜欢.getX()
的可读性,尽管它会使操作员定义更容易.
I'd loose my .getX()
, .setX()
stuff and have to replace it with something like .at()
or []
. tbh I prefer the readability of .getX()
, although it would make operator definitions easier.
第二: 我可以看到为什么这很不好,但是要做到这一点,以便可以将这些向量传递到openGL的方法中,该方法希望使用float数组,但我已经使splat运算符重载了.
Second: I can see why this is bad, but to make it so I can pass these vectors into openGL's method that expect a float array I've overloaded the splat operator
// Defined in Vector2D<T>
operator*() { return (T*)this; }
据我了解,不能保证编译器会将成员变量x,y,z,w放在类的开头,如果不小心,我可能最终会通过v表.但是我必须承认,到目前为止我还没有遇到任何问题.
As I understand it, there is no guarantee that the compiler will put the member variables x,y,z,w at the beginning of the class, and if not careful I might end up passing the v-table instead. However I must admit I've had no problems so far.
我能看到的唯一方法是维护一个返回的数组.我想如果改变它们的方式会更容易,因为我一开始就处理矢量.
The only way I can see around this is to maintain an array that gets returned. Which I suppose would be easier if I changed they way I deal with vectors in the first place.
推荐答案
您可能要考虑使用 GLM 代替.它可以完成您描述的所有内容(尽管我发现缺少文档),包括与OpenGL的集成.
You may want to consider using GLM instead. It does all that you've described (though I found the documentation lacking) including integration with OpenGL.
这篇关于C ++向量数学和OpenGL兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!