Files
Frame/frame/src/render/RenderTarget.cpp
2022-03-03 22:57:03 +01:00

124 lines
3.4 KiB
C++

#include "RenderTarget.hpp"
#include <cmath>
namespace frame::render
{
RenderTarget::RenderTarget(Size size)
: image(size)
{
}
void RenderTarget::DrawPixel(Vector const& position, Color color)
{
if(position.x < 0 || position.y < 0 || position.x >= image.getWidth() || position.y > image.getHeight())
return;
image.at(position.x, position.y) = color;
}
void RenderTarget::DrawLine(Vector const& start,
Vector const& end,
Color color)
{
auto deltaX = std::abs(start.x - end.x);
auto deltaY = std::abs(start.y - end.y);
auto rX = start.x < end.x ? 1 : -1;
auto rY = start.y < end.y ? 1 : -1;
bool swap = false;
if(deltaX < deltaY)
{
swap = true;
std::swap(deltaX, deltaY);
std::swap(rX, rY);
}
auto pos = start;
auto E = 2 * deltaY - deltaX;
DrawPixel(pos, color);
while(pos != end)
{
if(E <= 0)
{
if(!swap)
pos.x += rX;
else
pos.y += rX;
E += 2 * deltaY;
} else
{
if(!swap)
{
pos.x += rX;
pos.y += rY;
} else
{
pos.y += rX;
pos.x += rY;
}
E += 2 * deltaY - 2 * deltaX;
}
if(pos.x < 0 || pos.y < 0 || pos.x >= image.getWidth()
|| pos.y >= image.getHeight())
break;
DrawPixel(pos, color);
}
}
void RenderTarget::DrawCircle(Vector const& center,
int32_t radius,
Color color)
{
int32_t const r_2 = radius * radius;
Vector pos{0, -radius};
DrawPixel(center + pos, color);
DrawPixel(center + Vector{pos.x, pos.y * -1}, color);
DrawPixel(center + Vector{pos.x * -1, pos.y * -1}, color);
DrawPixel(center + Vector{pos.x * -1, pos.y}, color);
DrawPixel(center + Vector{pos.y, pos.x}, color);
DrawPixel(center + Vector{pos.y, pos.x * -1}, color);
DrawPixel(center + Vector{pos.y * -1, pos.x * -1}, color);
DrawPixel(center + Vector{pos.y * -1, pos.x}, color);
while(pos.x <= radius / std::sqrt(2.f))
{
float E = pos.x * pos.x + ((float)pos.y + 0.5f) * ((float)pos.y + 0.5f) - r_2;
if(E <= 0)
{
pos.x += 1;
E += 2 * pos.x + 3;
} else
{
pos.x += 1;
pos.y += 1;
E += 2 * pos.x - 2 * pos.y + 5;
}
DrawPixel(center + pos, color);
DrawPixel(center + Vector{pos.x, pos.y * -1}, color);
DrawPixel(center + Vector{pos.x * -1, pos.y * -1}, color);
DrawPixel(center + Vector{pos.x * -1, pos.y}, color);
DrawPixel(center + Vector{pos.y, pos.x}, color);
DrawPixel(center + Vector{pos.y, pos.x * -1}, color);
DrawPixel(center + Vector{pos.y * -1, pos.x * -1}, color);
DrawPixel(center + Vector{pos.y * -1, pos.x}, color);
}
}
} // namespace frame::render