Help me optimize this function
Hallo,
I have this function that gets called for every single frame in my game. It is for drawing a sprite with rotation. Right now it is a lot slower then the function that draws a sprite without rotation. When I started optimizing the function it gave me around 55 fps, not I am up in 95.
Can anyone see something that might make it even faster?
Code:
void Visualisation::drawRotationSprite(int spriteId, float rotation, int xPos, int yPos)
{
// Not sure why I have to do this:
rotation -= 90;
// Create the boundingBox
BoundingBox boundingBox = BoundingBox(0, 0, spriteList[spriteId].getWidth(), spriteList[spriteId].getHeight());
// Rotate
boundingBox.rotate(rotation);
// Move the bounding box
boundingBox.move(xPos, yPos);
// Create a axis alligned box
BoundingBox allignedBox = boundingBox.allignToAxis();
// Convert from radians to degrees. This is the valuse we use to rotate the point back
// to find the right sprite pixel
float cosVal = cos(-(rotation * PI / 180.0));
float sinVal = sin(-(rotation * PI / 180.0));
// For each pixel in the aliignedBox go back to the texture and see if there is a pixel there.
// if it is, copy the color of it
for(int y = allignedBox.getYpos(); y < allignedBox.getYpos() + allignedBox.getHeight(); y++)
{
for(int x = allignedBox.getXpos(); x < allignedBox.getXpos() + allignedBox.getWidth(); x++)
{
vertex point = vertex(x,y);
if(boundingBox.pointIntersection(point))
{
// Rotate the point back to find the right pixel color
int newX = point.x;
int newY = point.y;
int tempX = newX;
int tempY = newY;
newX = (tempX * cosVal - tempY * sinVal);
newY = (tempY * cosVal + tempX * sinVal);
// Find the correct sprite pixel
int pixelIndex = newY * getSprite(spriteId).getWidth() + newX;
// Dont know why I have to do this. Vector out of range without it
if(pixelIndex >= getSprite(spriteId).pixelList.size() - 1)
pixelIndex = getSprite(spriteId).pixelList.size() - 1;
// Draw the point
int offset = 4 * ((x * screenRec.getWidth()) + y);
screenPnt[offset+0] = getSprite(spriteId).pixelList[pixelIndex].b;
screenPnt[offset+1] = getSprite(spriteId).pixelList[pixelIndex].g;
screenPnt[offset+2] = getSprite(spriteId).pixelList[pixelIndex].r;
}
}
}
}
The "boundingBox.pointIntersection(point)" is also very expensive, here is how I do it:
Code:
bool BoundingBox::pointIntersection(vertex &point)
{
point.x -= vertexList[1].x;
point.y -= vertexList[1].y;
Vector2D v0 = Vector2D( point.x, point.y );
Vector2D v1 = Vector2D( (vertexList[0].x - vertexList[1].x), (vertexList[0].y - vertexList[1].y));
int val_1 = Dot(v0,v1);
if(0 <= val_1 && val_1 <= Dot(v1,v1))
{
Vector2D v2 = Vector2D( (vertexList[3].x - vertexList[1].x), (vertexList[3].y - vertexList[1].y));
int val_2 = Dot(v0,v2);
if( 0 <= val_2 && val_2 <= Dot(v2,v2) )
return true;
}
return false;
}
Sorry if this is the wrong forum or an inappropriate question.
Thanks,