102 lines
2.3 KiB
C++
102 lines
2.3 KiB
C++
/*
|
|
* SpriteRenderer.cpp
|
|
*
|
|
* Created on: Nov 30, 2016
|
|
* Author: tibi
|
|
*/
|
|
|
|
#include <GameState.h>
|
|
#include <model/GameObject.h>
|
|
#include <components/basic/Camera.h>
|
|
#include <graphics/backend/SdlRenderer.h>
|
|
#include <graphics/SpriteRenderer.h>
|
|
#include <utils/Assert.h>
|
|
|
|
#include <iostream>
|
|
|
|
using namespace farmlands::components::basic;
|
|
using namespace farmlands::graphics::backend;
|
|
using namespace farmlands::resources;
|
|
|
|
namespace farmlands {
|
|
namespace graphics {
|
|
|
|
SpriteRenderer::SpriteRenderer()
|
|
: m_context(nullptr),
|
|
m_sprite(nullptr)
|
|
{
|
|
}
|
|
|
|
SpriteRenderer::~SpriteRenderer()
|
|
{
|
|
}
|
|
|
|
model::Component* SpriteRenderer::clone()
|
|
{
|
|
return new SpriteRenderer();
|
|
}
|
|
|
|
void SpriteRenderer::onInitialize()
|
|
{
|
|
m_context = &GameState::current().renderContext;
|
|
m_sprite = gameObject->component<Sprite>();
|
|
}
|
|
|
|
void SpriteRenderer::onRender()
|
|
{
|
|
utils::RectF bounds = m_sprite->boundaries();
|
|
float spriteW = bounds.w * m_context->viewport.pixelsPerUnitX;
|
|
float spriteH = bounds.h * m_context->viewport.pixelsPerUnitY;
|
|
|
|
// Compute destination rectangle
|
|
float scale = m_context->camera()->scale;
|
|
|
|
SDL_Rect dest =
|
|
{
|
|
.x = static_cast<int>(m_context->xToScreen(bounds.x)),
|
|
.y = static_cast<int>(m_context->yToScreen(bounds.y)),
|
|
.w = static_cast<int>(spriteW * scale),
|
|
.h = static_cast<int>(spriteH * scale)
|
|
};
|
|
|
|
if (m_context->visible(dest))
|
|
{
|
|
// Obtain texture
|
|
int texId = m_sprite->currentFrame().tileSetId;
|
|
SDL_Texture* texture = resources::ResourceManager::instance().texture(texId);
|
|
|
|
// Compute source rectangle
|
|
SDL_Rect src;
|
|
getCell(texture, m_sprite->currentFrame().tileSetCell, &src.x, &src.y);
|
|
src.w = spriteW;
|
|
src.h = spriteH;
|
|
|
|
// Draw
|
|
SdlRenderer::instance().renderTexture(texture, &src, &dest);
|
|
}
|
|
}
|
|
|
|
void SpriteRenderer::getCell(SDL_Texture* texture, uint32_t cell, int* outX, int* outY)
|
|
{
|
|
int texWidth, texHeight;
|
|
SdlRenderer::instance().getTextureSize(texture, &texWidth, &texHeight);
|
|
|
|
int ppuX = m_context->viewport.pixelsPerUnitX;
|
|
int ppuY = m_context->viewport.pixelsPerUnitY;
|
|
|
|
// Compute texture coordinates
|
|
*outX = (cell * ppuX) % texWidth;
|
|
*outY = ((cell * ppuX) / texWidth) * ppuY;
|
|
}
|
|
|
|
void SpriteRenderer::dump(unsigned level)
|
|
{
|
|
for (unsigned i = 0; i < level; i++)
|
|
std::cout<<" ";
|
|
|
|
std::cout << " .Component: SpriteRenderer\n";
|
|
}
|
|
|
|
} /* namespace graphics */
|
|
} /* namespace farmlands */
|