Files
UwUGL/primatives/line.cpp
T
2026-07-20 02:04:17 -07:00

101 lines
2.6 KiB
C++

#pragma once
#include <stdint.h>
#include "../datatypes.cpp"
#include "../helpers.cpp"
#include "../buffer.cpp"
#include "../shaders/shaders.h"
namespace UwU {
// line
class Line {
private:
// plot lines if m <= 1
template <class ShaderT>
void lineLow(int16_t ix0, int16_t iy0, int16_t ix1, int16_t iy1, Buffer buffer, ShaderBase<ShaderT>& shader) {
int16_t dx = ix1 - ix0;
int16_t dy = iy1 - iy0;
int16_t yi = 1;
if (dy < 0) {
yi = -1;
dy = -dy;
}
int16_t d = (2 * dy) - dx;
int16_t y = iy0;
for (int16_t x = ix0; x < ix1; x++) {
buffer.drawPixel((uint16_t)x, (uint16_t)y, shader.shade(x, y));
if (d > 0) {
y += yi;
d += (2 * (dy - dx));
} else {
d += (2 * dy);
}
}
return;
}
// plot lines if m >1
template <class ShaderT>
void lineHigh(int16_t ix0, int16_t iy0, int16_t ix1, int16_t iy1, Buffer buffer, ShaderBase<ShaderT>& shader) {
int16_t dx = ix1 - ix0;
int16_t dy = iy1 - iy0;
int16_t xi = 1;
if (dx < 0) {
xi = -1;
dx = -dx;
}
int16_t d = (2 * dx) - dy;
int16_t x = ix0;
for (int16_t y = iy0; y < iy1; y++) {
buffer.drawPixel((uint16_t)x, (uint16_t)y, shader.shade(x, y));
if (d > 0) {
x += xi;
d += (2 * (dx - dy));
} else {
d += (2 * dx);
}
}
return;
}
public:
Line(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1) {
this->x0 = x0;
this->y0 = y0;
this->x1 = x1;
this->y1 = y1;
}
Line() {}
uint16_t x0;
uint16_t y0;
uint16_t x1;
uint16_t y1;
// Uses Bresenham's line algorithm to draw line of any slope
template <class ShaderT>
void draw (Buffer buffer, ShaderBase<ShaderT>& shader) {
if (x0 > buffer.width || y0 > buffer.height || x1 > buffer.width || y1 > buffer.height) {return;};
int16_t ix0 = x0;
int16_t iy0 = y0;
int16_t ix1 = x1;
int16_t iy1 = y1;
if (abs(iy1 - iy0) < abs(ix1 - ix0)) {
if (ix0 > ix1) {
lineLow(ix1, iy1, ix0, iy0, buffer, shader);
} else {
lineLow(ix0, iy0, ix1, iy1, buffer, shader);
}
} else {
if (iy0 > iy1) {
lineHigh(ix1, iy1, ix0, iy0, buffer, shader);
} else {
lineHigh(ix0, iy0, ix1, iy1, buffer, shader);
}
}
return;
}
};
}