3

I am trying to create a line in opengl using multiple points.

if i use these points 0:0:0 25:25:0 50:0:0

than this is the output of the line

The line has a issue the edge points are not connected , how can i connect the end points.

enter image description here

This is the code where the data is generated for the line using two points.

void Boundary::DrawLine(Point p1, Point p2)
 {
     float dx, dy, dist, x1, y1, x2, y2, x3, y3, x4, y4, n;
     dx = p1.x - p2.x;
     dy = p1.y - p2.y;
     n = 2;
     dist = sqrt(dx * dx + dy * dy);
     dx /= dist;
     dy /= dist;

     x1 = p1.x + (n / 2) * dy;
     y1 = p1.y - (n / 2) * dx;
     x2 = p1.x - (n / 2) * dy;
     y2 = p1.y + (n / 2) * dx;

     x3 = p2.x + (n / 2) * dy;
     y3 = p2.y - (n / 2) * dx;
     x4 = p2.x - (n / 2) * dy;
     y4 = p2.y + (n / 2) * dx;


         // data for the line
         float vertices[] = {
                x2, y2, 0.0,
                 x4, y4, 0.0,
                 x1, y1, 0.0,
                 x3, y3, 0.0
                 }; 
     
 }

This is the draw function where stdvecPoints is a vector of structure Point,

void Boundary::Draw()
 {
     for (int i = 0; i < stdvecPoints.size() - 1; i++) {

         DrawLine(stdvecPoints[i], stdvecPoints[i + 1]);
     }
 }
Summit
  • 2,112
  • 2
  • 12
  • 36

1 Answers1

2

your endpoints are currently on edge of line... they should be also shifted by n/2 not just radially but also axially ...

line 90deg

so if (dx,dy) is unit direction vector and n is thickness of your line then I would try:

dx*=(n/2.0);
dy*=(n/2.0);

x1 = p1.x + dx + dy;
y1 = p1.y + dy - dx;   
x2 = p1.x + dx - dy;
y2 = p1.y + dy + dx;

x3 = p1.x - dx + dy;
y3 = p1.y - dy - dx;   
x4 = p1.x - dx - dy;
y4 = p1.y - dy + dx;

Beware I do did not test this as I do not have the underlying functions you use so its possible the sign of the shift is reversed in case your line is not enlarged but shrinked instead just swap the first +/- sign in all points. As your (dx,dy) is p1-p2 I think is correct but without testing not for sure ...

However for non perpendicular and straight line joins this will create artifacts too (just not as big ones) to remedy that you have to have circular ends of line. That however is much faster to do in shader side for example see:

If you want multiples of 45 deg joints then you can do this instead:

line 45deg

However you would need to render polygon instead of rectangle (6 points) where 4 points are the ones you have now and the missing 2 will be

dx*=(n/2.0);
dy*=(n/2.0);
x5 = p1.x + dx;
y5 = p1.y + dy;   
x6 = p2.x - dx;
y6 = p2.y - dy;   
Spektre
  • 49,595
  • 11
  • 110
  • 380