2024-12-21 00:20:43 +01:00

69 lines
1.5 KiB
C++

#include <cmath>
#include <raylib.h>
#include <raymath.h>
#include "canvas/Tree.hpp"
#include "Math.hpp"
// Public
void Tree::init(int size)
{
this->size = size;
start.x = size / 2;
start.y = size;
}
void Tree::draw(Dna *dna)
{
m_dna = dna;
draw_calls.push_back({start, 0, (float)size / 4, 1});
while (!draw_calls.empty())
{
drawBranch();
draw_calls.pop_front();
}
}
// Private
Vector2 Tree::drawLine()
{
DrawArgs arg = draw_calls.front();
arg.angleDeg += 180.0f;
float angle = (arg.angleDeg * PI) / 180.0f;
float nx = arg.lenghth * std::sin(angle);
float ny = arg.lenghth * std::cos(angle);
Vector2 end = {arg.start.x + nx, arg.start.y + ny};
float thick = 2.0;
float fstep = 1.0 / ((arg.lenghth / thick) * 1.5);
for (float i = 0; i < 1; i += fstep)
{
Vector2 point = Vector2Lerp(arg.start, end, i);
Color color = ColorLerp(m_dna->branches[arg.dep - 1].color, m_dna->branches[arg.dep].color, i);
DrawCircleV(point, thick, color);
}
return end;
}
void Tree::drawBranch()
{
DrawArgs arg = draw_calls.front();
if (arg.dep >= MAX_DEPTH)
return;
Vector2 next = drawLine();
float next_len = m_dna->branches[arg.dep].lenghthRatio;
float sectors = m_dna->branches[arg.dep].numOfBranches + 1;
float degres = 180.0f / sectors;
for (size_t i = 0; i < m_dna->branches[arg.dep].numOfBranches; i++)
{
float newAngle = arg.angleDeg - 90 + (degres * (i + 1));
draw_calls.push_back({next, newAngle, arg.lenghth * next_len, arg.dep + 1});
}
}