- Home /
IntVector2 Struct useful?
Hey guys,
I'm developing a game and I'm trying to optimize it.
Because I have a terrain (minecraft like), I don't need Float Vectors to store the positions.
What I've done now is something like this
public struct IntVector2 {
public int x, y;
public IntVector2(int x, int y) {
this.x = x;
this.y = y;
}
public static IntVector2 operator +(IntVector2 a, IntVector2 b) {
return new IntVector2(a.x + b.x, a.y + b.y);
}
public static IntVector2 operator +(IntVector2 a, Vector2 b) {
return new IntVector2(a.x + (int)b.x, a.y + (int)b.y);
}
public static IntVector2 operator -(IntVector2 a, IntVector2 b) {
return new IntVector2(a.x - b.x, a.y - b.y);
}
public static IntVector2 operator -(IntVector2 a, Vector2 b) {
return new IntVector2(a.x - (int)b.x, a.y - (int)b.y);
}
public static IntVector2 operator *(IntVector2 a, int b) {
return new IntVector2(a.x * b, a.y * b);
}
}
The Problem is that meshes need Vector3's as vertices. This means I have to cast everything back to Vector3's. And that seems very ineffective. Now I wanted to ask how you would solve something like this? Any suggestions?
Thanks!
Since gpu uses 32 bits floating points as the vertex positions, you don't need to implement integer vector, it won't make performance advantages. I think.
Answer by Owen-Reynolds · Oct 09, 2014 at 04:52 PM
This is an "it depends" no-correct-answer time vs. space optimization problem. Yes, sometimes using a lot less space, but being a little slower to use it (converting to float) will be a big gain. Merely using less space will speed up a program (but do phones also have L1 caches?) Yes, that is the sort of data structure built for real programs. But it depends.
How long are floats and ints on the target platform? Can you use short int
instead? short unsigned int
? Just how large is the terrain and how much are you saving (if it shrinks from 100K to 50K, who cares?) Does your game run too slowly now?
Can you make an even more efficient data structure (similar to a heightmap)? What operations will you be performing most (so you can organize to make them run faster)?
Then, you could probably make a quick test in an hour ("play with" each position over and over, using both methods, and time it.)
I think the most common solution is to go with the simplest method (Vector3s,) but do the usual bit of putting a wrapper around it. In other words, everyone calls Vector3 getHeight(x,y)
instead of reading straight from H[x,y]
. Standard encapsulation. Then, if you really need to redo how terrain words, it won't be too bad.
But I use Vector3's even when I know y is always 0, just because it's easier and runs fast enough.
Floats are always 4 bytes and ints are always 4 bytes, on all platforms.