Now, there are various ways for drawing lines in OpenGL, I will be using the classical algorithms - Digital Differential Analyzer (DDA) and Bresenham Line Drawing Algorithms.
Digital Differential Analyzer (DDA) Line Drawing Algorithm
#include <iostream>
using namespace std;
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
void dda(float x1, float x2, float y1, float y2){
float delX = x2 - x1;
float delY = y2 - y1;
float maxDiff = fmax(fabs(delX), fabs(delY));
float minSteps = maxDiff / 0.00125f;
float dx = delX / minSteps;
float dy = delY / minSteps;
glColor3f(0.078f, 0.75f, 0.078f);
glPointSize(5.0f);
glBegin(GL_POINTS);
for (int i=0; i<ceil(minSteps); i++){
float x= x1 + i*dx;
float y= y1 + i*dy;
glVertex2f(x, y);
}
glEnd();
}
int main()
{
GLFWwindow* window;
if (!glfwInit()){
return -1;
}
window = glfwCreateWindow(640, 480, "DDA", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
dda(-1.0f, 1.0f, -1.0f, 1.0f);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
Bresenham Line Drawing Algorithm
#include <iostream>
using namespace std;
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
void bresenham(float x1, float x2, float y1, float y2){
float delX = x2 - x1;
float delY = y2 - y1;
float pixelX = x1 < x2 ? 0.01f : -0.01f;
float pixelY = y1 < y2 ? 0.01f : -0.01f;
float pixel = delX - delY;
glColor3f(0.078f, 0.75f, 0.078f);
glPointSize(5.0f);
glBegin(GL_POINTS);
while(true){
glVertex2f(x1, y1);
if(x1>=x2 && y1>=y2){
break;
}
float nextPixel = 2 * pixel;
if(nextPixel > -delY){
pixel -= delY;
x1 += pixelX;
}
if(nextPixel < delX){
pixel += delX;
y1 += pixelY;
}
}
glEnd();
}
int main()
{
GLFWwindow* window;
if (!glfwInit()){
return -1;
}
window = glfwCreateWindow(640, 480, "Bresenham Line Drawing Algorithm", NULL, NULL);
if (!window)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
while (!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
bresenham(-0.5f, 0.5f, -0.5f, 0.5f);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}