OpenGL Line Drawing and Calculations: Length, Gradient, Perpendicularity, and Parallelism
// File ID: lab03b.cpp
// Title: Program to draw lines and perform calculations using OpenGL
// Author:
#define FREEGLUT_STATIC
#include <GL/freeglut.h>
#include <math.h>
#include <iostream>
using namespace std;
// Function to draw geometric elements and perform calculations
void define_to_OpenGL()
{
// Calculate and output the lengths of the lines
float length_AB = sqrt(pow(a[2] - a[0], 2) + pow(a[3] - a[1], 2));
float length_CD = sqrt(pow(a[6] - a[4], 2) + pow(a[7] - a[5], 2));
cout << 'Length of line AB: ' << length_AB << endl;
cout << 'Length of line CD: ' << length_CD << endl;
// Calculate and output the gradients
float gradient_AB = (a[3] - a[1]) / (a[2] - a[0]);
float gradient_CD = (a[7] - a[5]) / (a[6] - a[4]);
cout << 'Gradient of line AB: ' << gradient_AB << endl;
cout << 'Gradient of line CD: ' << gradient_CD << endl;
// Check if the lines are perpendicular or parallel to each other
if (gradient_AB == gradient_CD)
cout << 'The lines AB and CD are parallel.' << endl;
else if (gradient_AB * gradient_CD == -1)
cout << 'The lines AB and CD are perpendicular.' << endl;
else
cout << 'The lines AB and CD are neither parallel nor perpendicular.' << endl;
// Draw the lines AB and CD using OpenGL
glBegin(GL_LINES);
glColor3f(1.0, 0.0, 0.0); // Red color
// Draw line AB
glVertex2f(a[0], a[1]);
glVertex2f(a[2], a[3]);
// Draw line CD
glColor3f(0.0, 0.0, 1.0); // Blue color
glVertex2f(a[4], a[5]);
glVertex2f(a[6], a[7]);
glEnd();
// Draw points A, B, C, and D using OpenGL
glBegin(GL_POINTS);
glColor3f(0.0, 1.0, 0.0); // Green color
// Draw point A
glVertex2f(a[0], a[1]);
// Draw point B
glVertex2f(a[2], a[3]);
// Draw point C
glVertex2f(a[4], a[5]);
// Draw point D
glVertex2f(a[6], a[7]);
glEnd();
glFlush();
}
// Function to initialize coordinates of line end points
void init()
{
// Define the coordinates of points A, B, C, and D
a[0] = -0.5;
a[1] = 0.0;
a[2] = 0.5;
a[3] = 0.0;
a[4] = -0.5;
a[5] = -0.5;
a[6] = 0.5;
a[7] = 0.5;
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutCreateWindow('Line Drawing');
init();
glutDisplayFunc(define_to_OpenGL);
glutMainLoop();
return 0;
}
You can customize the coordinates of points A, B, C, and D as per your requirements. The program uses OpenGL to draw the lines AB and CD, calculate and output their lengths, gradients, and check if they are perpendicular or parallel. It also draws points A, B, C, and D at the same time when the lines are drawn.
原文地址: https://www.cveoy.top/t/topic/y9J 著作权归作者所有。请勿转载和采集!