Skip to content

Instantly share code, notes, and snippets.

@GunnarKarlsson
Created November 5, 2018 03:57
Show Gist options
  • Save GunnarKarlsson/262a999ef8dfb89ab0061a10b687d6a9 to your computer and use it in GitHub Desktop.
Save GunnarKarlsson/262a999ef8dfb89ab0061a10b687d6a9 to your computer and use it in GitHub Desktop.
lineutil
#ifndef LINEUTIL_H
#define LINEUTIL_H
#include "common.h"
/*
** Draws horizontal line
** hexRgb = e.g. 0xFF0000
*/
void drawHLine(int x1, int x2, int y, GLubyte *data, unsigned long hexRgb, int width, int height)
{
GLubyte red, green, blue;
red = hexRgb >> 16;
green = (hexRgb & 0x00ff00) >> 8;
blue = (hexRgb & 0x0000ff);
//Make sure Y-value is legit
if (y >= 0 && y < height) {
//Make sure x1 < x2
if (x2 < x1) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
//Make sure at least part of the line is inside the height*width area
if (!(x1 < 0 && x2 < 0) && !(x1 > width - 1 && x2 > width - 1)) {
//Clamp right adn left edge values
if (x1 < 0) {
x1 = 0;
}
if (x2 > width-1) {
x2 = width-1;
}
//render the line
GLubyte* ptr = &data[(y * width + x1) * BYTES_PER_COLOR];
GLubyte* end = &data[(y * width + x2 + 1) * BYTES_PER_COLOR];
while (ptr < end) {
*ptr++ = red;
*ptr++ = green;
*ptr++ = blue;
*ptr++ = 0xFF;
}
}
}
}
/*
** Draws vertical line
** hexRgb = e.g. 0xFF0000
*/
void drawVLine(int x1, int y1, int y2, GLubyte *data, unsigned long hexRgb, int width, int height)
{
GLubyte red, green, blue;
red = hexRgb >> 16;
green = (hexRgb & 0x00ff00) >> 8;
blue = (hexRgb & 0x0000ff);
//Make sure the line is legit
if (x1 >= 0 && x1 < width) {
//Make sure y1 < y2
if (y1 > y2) {
int tmp = y1;
y1 = y2;
y2 = tmp;
}
//Make sure part of the line is in the image area
if (!(y1 < 0 && y2 < 0) && !(y1 > height - 1 && y2 > height - 1)) {
//clamp values vertically
if (y1 < 0) {
y1 = 0;
}
if (y2 > height - 1) {
y2 = height - 1;
}
//render
GLubyte *ptr = &data[(y1 * width + x1) * BYTES_PER_COLOR];
int height = y2 - y1 + 1;
for (int i = 0; i < height; i++) {
*ptr++ = red;
*ptr++ = green;
*ptr++ = blue;
*ptr++ = 0xFF;
ptr += (BYTES_PER_COLOR * width - BYTES_PER_COLOR);
}
}
}
}
#endif // LINEUTIL_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment