export tree functions to a class

This commit is contained in:
Nikola Petrov
2024-03-03 21:06:06 +01:00
parent 7e693bb73f
commit cccafdda37
4 changed files with 173 additions and 135 deletions

103
src/Tree.cpp Normal file
View File

@@ -0,0 +1,103 @@
#include "Tree.hpp"
#include "raylib.h"
#include "raymath.h"
#include "Math.hpp"
#include <cmath>
Tree::Tree(int size)
{
this->size = size;
target = LoadRenderTexture(size, size);
start.x = size / 2;
start.y = size;
tree.assign(11, {0});
}
Tree::~Tree()
{
UnloadRenderTexture(target);
}
void Tree::Draw(Rectangle dest)
{
Rectangle source = {0, 0, (float)target.texture.width, (float)-target.texture.height};
Vector2 origin = {0.0f, 0.0f};
DrawTexturePro(target.texture, source, dest, origin, 0.0f, WHITE);
}
Vector2 Tree::draw_line(Vector2 start, float angleDeg, float lenghth, int dep)
{
angleDeg += 180.0f;
float angle = (angleDeg * PI) / 180.0f;
float nx = lenghth * std::sin(angle);
float ny = lenghth * std::cos(angle);
Vector2 end = {start.x + nx, start.y + ny};
float thick = 2.0;
float fstep = 1.0 / ((lenghth / thick) * 1.5);
for (float i = 0; i < 1; i += fstep)
{
Vector2 point = Vector2Lerp(start, end, i);
Color color = ColorLerp(tree[dep - 1].color, tree[dep].color, i);
DrawCircleV(point, thick, color);
}
return end;
}
void Tree::draw_branch(draw_args arg)
{
if (arg.dep >= MAX_DEPTH)
return;
Vector2 next = draw_line(arg.start, arg.angleDeg, arg.lenghth, arg.dep);
float next_len = tree[arg.dep].lenghthRatio;
float sectors = tree[arg.dep].numOfBranches + 1;
float degres = 180.0f / sectors;
for (size_t i = 0; i < tree[arg.dep].numOfBranches; i++)
{
float newAngle = arg.angleDeg - 90 + (degres * (i + 1));
draw_calls.push_back((draw_args){next, newAngle, arg.lenghth * next_len, arg.dep + 1});
}
}
void Tree::draw_tree(draw_args first)
{
draw_calls.push_back(first);
while (!draw_calls.empty())
{
draw_branch(draw_calls.front());
draw_calls.pop_front();
}
}
void Tree::generate_tree()
{
for (size_t i = 0; i < MAX_DEPTH; i++)
{
uint8_t r = GetRandomValue(0, 255);
uint8_t g = GetRandomValue(0, 255);
uint8_t b = GetRandomValue(0, 255);
tree[i].color = (Color){r, g, b, 255};
tree[i].numOfBranches = GetRandomValue(1, 3);
tree[i].lenghthRatio = ((float)GetRandomValue(600, 700)) / 1000.0f;
}
tree[0].color = tree[1].color;
}
void Tree::new_tree()
{
generate_tree();
BeginTextureMode(target);
ClearBackground(WHITE);
draw_tree((draw_args){start, 0, size / 4, 1});
EndTextureMode();
}