Drawing an image along a slope in OpenGL - opengl

I'm writing a program that can draw a line between two points with filled circles. The circles:
- shouldn't overlap each other
- be as close together as possible
- and the centre of each circle should be on the line.
I've written a function to produce the circles, however I'm having trouble calculating position of each circle so that they are correctly lined up
void addCircles(scrPt endPt1, scrPt endPt2)
{
float xLength, yLength, length, cSquare, slope;
int numberOfCircles;
// Get the x distance between the two points
xLength = abs(endPt1.x - endPt2.x);
// Get the y distance between the two points
yLength = abs(endPt1.y - endPt2.y);
// Get the length between the points
cSquare = pow(xLength, 2) + pow(yLength, 2);
length = sqrt(cSquare);
// calculate the slope
slope = (endPt2.y - endPt1.y) / (endPt2.x - endPt1.x);
// Find how many circles fit inside the length
numberOfCircles = round(length / (radius * 2) - 1);
// set the position of each circle
for (int i = 0; i < numberOfCircles; i++)
{
scrPt circPt;
circPt.x = endPt1.x + ((radius * 2) * i);
circPt.y = endPt1.y + (((radius * 2) * i) * slope);
changeColor();
drawCircle (circPt.x, circPt.y);
}
This is what the above code produces:
I'm quite certain that the issue lies with this line, which sets the y value of the circle:
circPt.y = endPt1.y + (((radius * 2) * i) * slope);
Any help would be greatly appreciated

I recommend to calculate the direction of the line as a unit vector:
float xDist = endPt2.x - endPt1.x;
float yDist = endPt2.y - endPt1.y;
float length = sqrt(xDist*xDist + yDist *yDist);
float xDir = xDist / length;
float yDir = yDist / length;
Calculate the distance from one center point to the next one, numberOfSegments is the number of sections and not the number of circles:
int numberOfSegments = (int)trunc( length / (radius * 2) );
float distCpt = numberOfSegments == 0 ? 0.0f : length / (float)numberOfSegments;
A center point of a circle is calculated by the adding a vector the the start point of the line. The vector pints in the direction of the line and its length is given, by the distance between 2 circles multiplied by the "index" of the circle:
for (int i = 0; i <= numberOfSegments; i++)
{
float cpt_x = endPt1.x + xDir * distCpt * (float)i;
float cpt_y = endPt1.y + yDir * distCpt * (float)i;
changeColor();
drawCircle(cpt_x , cpt_y);
}
Note, the last circle on a line may be redrawn, by the first circle of the next line. You can change this by changing the iteration expression of the for loop - change <= to <:
for (int i = 0; i < numberOfSegments; i++)
In this case at the end of the line won't be drawn any circle at all.

Related

How to generate geometry for part of a sphere

There are few algorithms to generate the points needed to render a sphere, but I couldn't not find a good algorithm nor to adapt a full sphere algorithm to generate the points for a part of the sphere.
Let's assume I have the min/max latitude, min/max longitude and the sphere radius. How do I generate a mesh to be able to render this part of the sphere?
I made hemisphere & part of hemisphere mesh. I edit songho Ahn's source code slightly and you can refer from following link :
http://www.songho.ca/opengl/gl_sphere.html
the main method of class Sphere are buildVertices*
You can get desired result from editing this method.
I made hemisphere like this :
void HemiSphere::buildVerticesSmooth()
{
...
float sectorStep = 2 *PI / sectorCount;
float stackStep = (PI / 2) / stackCount;
float sectorAngle, stackAngle;
for(int i = 0; i <= stackCount; ++i)
{
stackAngle = -PI / 2 + i * stackStep; // starting from -pi/2 to 0
xy = radius * cosf(stackAngle); // r * cos(u)
z = radius *( 1 + sinf(stackAngle) ); // r * sin(u)
...
and I also made semi-hemisphere which cut its floor so that it have even floor on the bottom. To do this, leave x y coordinate unchanged, just edit z coordinate to 0.
void HemiSphere::buildVerticesSmooth()
{
....
float sectorStep = 2 *PI / sectorCount;
float stackStep = (PI / 2) / stackCount;
float sectorAngle, stackAngle;
float d = sqrt(radius*radius - flat_radius*flat_radius)/radius;
for(int i = 0; i <= stackCount; ++i)
{
stackAngle = -PI / 2 + i * stackStep; // starting from -pi/2 to 0
xy = radius * cosf(stackAngle); // r * cos(u)
z = radius *( d + sinf(stackAngle) ); // r * sin(u)
if (z<0.0) z = 0.0;
....
Hope this helps.

Algorithm to detect if two lines intersect does not give accurate/wanted results in SFML

I've been scratching my head for a couple of days on this one.
In my 2D top down game I have an array of FloatRects which represents walls.
I want to shoot a bullet represented by a point at X distance from the player (X being the weapon's range).
What I want to do is to check if there is a wall on the bullet's trajectory and if there is set the new bullet target to the collision point.
To do this I've tried to check if a side of a rectangle intersects with my bullet's trajectory line using this solution:
https://stackoverflow.com/a/1968345/10546991
I've used the program linked above but it gives me strange results, when the target is higher than the player the bullet just shoot behind.
Take a look at the following example :
Note : In SFML the Y axis points down
A is the player
B is the bullet's impact point or target, call it however you want.
C is the rectangle's Top Left side
D is the rectangle's Top Right side
(2500,2000) = a
(2500, 1300) = b
(2400, 2500) = c
(2600, 2500) = d
S1 = (0, -700)
S2 = (200, 0)
numeratorS = 700 * -100
numeratorT = 200 * -500
denominator = -200 * 700
s = 700 * - 100 / -200 * 700 = -70 000 / -140 000 = 7/14 = 1/2
t = -100 000 / -140 000 = 10 / 14 = 5 / 7
intersectionPoint.x = 2500 + (1/2 * 0) = 2500
intersectionPoint.y = 2000 + (1/2 * -700) = 1650
intersectionPoint (2500,1650)
So as you can see when testing if there is an intersection between the line between the player and the bullet's impact point and the top side of the rectangle (which is below the player) the program finds an intersection in between the player and the bullet!
I'm also providing a part of the code I use to detect collisions
Vector2f intersectionPoint = target;
//Check if bullet hits a wall and calculate new target
for (int i = 0; i < arraySize; i++)
{
float intersectionPointMagnitude = sqrt(intersectionPoint.x * intersectionPoint.x + intersectionPoint.y * intersectionPoint.y);
//Storing rect corner positions
Vector2f rectTopLeft;
rectTopLeft.x = collisions[i].left;
rectTopLeft.y = collisions[i].top;
Vector2f rectBottomLeft;
rectBottomLeft.x = collisions[i].left;
rectBottomLeft.y = collisions[i].top + collisions[i].height;
Vector2f rectBottomRight;
rectBottomRight.x = collisions[i].left + collisions[i].width;
rectBottomRight.y = collisions[i].top + collisions[i].height;
Vector2f rectTopRight;
rectTopRight.x = collisions[i].left + collisions[i].width;
rectTopRight.y = collisions[i].top;
Vector2f intersectionLeft = intersectionPoint;
if (Maths::vectorsIntersect(start, target, rectTopLeft, rectBottomLeft, intersectionLeft))
{
//We want to set a new target only if the detected collision is closer than the previous one
intersectionLeft = intersectionLeft - start;
float intersectionLeftMagnitude = sqrt(intersectionLeft.x * intersectionLeft.x + intersectionLeft.y * intersectionLeft.y);
if (intersectionLeftMagnitude < intersectionPointMagnitude)
{
intersectionPoint = intersectionLeft;
target = start + intersectionPoint;
}
}
I just can't understand where the issue is coming from so if anyone could help me out it'll be greatly appreciated.
Edit : Here is Maths::vectorsIntersect which is really similar to the function in the link above
bool vectorsIntersect(Vector2f A, Vector2f B, Vector2f C, Vector2f D, Vector2f& intersectionPoint)
{
Vector2f S1 = B - A;
Vector2f S2 = D - C;
//Calculate scalar parameters
float denominator = (S1.x * S2.y - S1.y * S2.x);
//We can't divide by 0!
if (denominator == 0.0f)
return false;
//S & T have the same denominator
float numeratorS = (S1.x * (A.y - C.y) - S1.y * (A.x - C.x));
float numeratorT = (S2.x * (A.y - C.y) - S2.y * (A.x - C.x));
float s, t;
s = numeratorS / denominator;
t = numeratorT / denominator;
//Check for intersection point
if (abs(s) > 0.0f && abs(s) < 1.0f && abs(t) > 0.0f && abs(t) < 1.0f)
{
//Return intersection point
intersectionPoint.x = A.x + (t * S1.x);
intersectionPoint.y = A.y + (t * S1.y);
return true;
}
return false;
}
EDIT 2 :
Alright I feel stupid now, in my Maths::vectorIntersect function I was checking if the absolute values of both s and t are between 0 and 1, which is why when the scalar parameters where between -0 and -1 the function returned true and led to unexpected behaviors.
Problem solved thank you for the help

line-width for ellipse is not constant

I am drawing hollow ellipse using opengl. I calculate vertices in c++ code using standard ellipse formula. In fragment shader i just assign color to each fragment. The ellipse that i see on the screen has thinner line width on the sharper curves as compared to that where curve is not that sharp. So question is, how to make line-width consistent across the entire parameter of ellipse? Please see the image below:
C++ code :
std::vector<float> BCCircleHelper::GetCircleLine(float centerX, float centerY, float radiusX, float radiusY, float lineWidth, int32_t segmentCount)
{
auto vertexCount = (segmentCount + 1) * 2;
auto floatCount = vertexCount * 3;
std::vector<float> array(floatCount);
const std::vector<float>& data = GetCircleData (segmentCount);
float halfWidth = lineWidth * 0.5f;
for (int32_t i = 0; i < segmentCount + 1; ++i)
{
float sin = data [i * 2];
float cos = data [i * 2 + 1];
array [i * 6 + 0] = centerX + sin * (radiusX - halfWidth);
array [i * 6 + 1] = centerY + cos * (radiusY - halfWidth);
array [i * 6 + 3] = centerX + sin * (radiusX + halfWidth);
array [i * 6 + 4] = centerY + cos * (radiusY + halfWidth);
array [i * 6 + 2] = 0;
array [i * 6 + 5] = 0;
}
return std::move(array);
}
const std::vector<float>& BCCircleHelper::GetCircleData(int32_t segmentCount)
{
int32_t floatCount = (segmentCount + 1) * 2;
float segmentAngle = static_cast<float>(M_PI * 2) / segmentCount;
std::vector<float> array(floatCount);
for (int32_t i = 0; i < segmentCount + 1; ++i)
{
array[i * 2 + 0] = sin(segmentAngle * i);
array[i * 2 + 1] = cos(segmentAngle * i);
}
return array;
}
Aiming this:
The problem is likely that your fragments are basically line segments radiating from the center of the ellipse.
If you draw a line, from the center of the ellipse through the ellipse you've drawn, at any point on the perimeter, you could probably convince yourself that the distance covered by that red line is in fact the width that you're after (roughly, since you're working at low spatial resolution; somewhat pixelated). But since this is an ellipse, that distance is not perpendicular to the path being traced. And that's the problem. This works great for circles, because a ray from the center is always perpendicular to the circle. But for these flattened ellipses, it's very oblique!
How to fix it? Can you draw circles at each point on the ellipse, instead of line segments?
If not, you might need to recalculate what it means to be that thick when measured at that oblique angle - it's no longer your line width, may require some calculus, and a bit more trigonometry.
Ok, so a vector tangent to the curve described by
c(i) = (a * cos(i), b * sin(i))
is
c'(i) = (- a * sin(i), b * cos(i))
(note that this is not a unit vector). The perpendicular to this is
c'perp = (b * cos(i), a * sin(i))
You should be able to convince yourself that this is true by computing their dot product.
Lets calculate the magnitude of c'perp, and call it k for now:
k = sqrt(b * b * cos(i) * cos(i) + a * a * sin(i) * sin(i))
So we go out to a point on the ellipse (c(i)) and we want to draw a segement that's perpendicular to the curve - that means we want to add on a scaled version of c'perp. The scaling is to divide by the magnitude (k), and then multiply by half your line width. So the two end points are:
P1 = c(i) + halfWidth * c'perp / k
P2 = c(i) - halfWidth * c'perp / k
I haven't tested this, but I'm pretty sure it's close. Here's the geometry you're working with:
--
Edit:
So the values for P1 and P2 that I give above are end-points of a line-segment that's perpendicular to the ellipse. If you really wanted to continue with just altering the radiusX and radiusY values the way you were doing, you could do this. You just need to figure out what the 'Not w' length is at each angle, and use half of this value in place of halfWidth in radiusX +/- halfWidth and radiusY +/- halfwidth. I leave that bit of geometry as an exercise for the reader.

interior angles of irregular polygon with angles > 180

I'm trying to calculate the values shown in the picture in red i.e. the interior angles.
I've got an array of the points where lines intersect and have tried using the dot-product but it only returns the smallest angles. I need the full range of internal angles (0-359) but can't seem to find much that meets this criteria.
Assuming your angles are in standard counterclockwise format, the following should work:
void angles(double points[][2], double angles[], int npoints){
for(int i = 0; i < npoints; i++){
int last = (i - 1 + npoints) % npoints;
int next = (i + 1) % npoints;
double x1 = points[i][0] - points[last][0];
double y1 = points[i][1] - points[last][1];
double x2 = points[next][0] - points[i][0];
double y2 = points[next][1] - points[i][1];
double theta1 = atan2(y1, x1)*180/3.1415926358979323;
double theta2 = atan2(y2, x2)*180/3.1415926358979323;
angles[i] = (180 + theta1 - theta2 + 360);
while(angles[i]>360)angles[i]-=360;
}
}
Obviously, if you are using some sort of data structure for your points, you will want to replace double points[][2] and references to it with references to your data structure.
You can obtain full angle range (-Pi..Pi) with atan2 function:
atan2(crossproduct, dotproduct)

Line-Circle Algorithm not quite working as expected

First, see:
https://math.stackexchange.com/questions/105180/positioning-a-widget-involving-intersection-of-line-and-a-circle
I have an algorithm that solves for the height of an object given a circle and an offset.
It sort of works but the height is always off:
Here is the formula:
and here is a sketch of what it is supposed to do:
And here is sample output from the application:
In the formula, offset = 10 and widthRatio is 3. This is why it is (1 / 10) because (3 * 3) + 1 = 10.
The problem, as you can see is the height of the blue rectangle is not correct. I set the bottom left offsets to be the desired offset (in this case 10) so you can see the bottom left corner is correct. The top right corner is wrong because from the top right corner, I should only have to go 10 pixels until I touch the circle.
The code I use to set the size and location is:
void DataWidgetsHandler::resize( int w, int h )
{
int tabSz = getProportions()->getTableSize() * getProportions()->getScale();
int r = tabSz / 2;
agui::Point tabCenter = agui::Point(
w * getProportions()->getTableOffset().getX(),
h * getProportions()->getTableOffset().getY());
float widthRatio = 3.0f;
int offset = 10;
int height = solveHeight(offset,widthRatio,tabCenter.getX(),tabCenter.getY(),r);
int width = height * widthRatio;
int borderMargin = height;
m_frame->setLocation(offset,
h - height - offset);
m_frame->setSize(width,height);
m_borderLayout->setBorderMargins(0,0,borderMargin,borderMargin);
}
I can assert that the table radius and table center location are correct.
This is my implementation of the formula:
int DataWidgetsHandler::solveHeight( int offset, float widthRatio, float h, float k, float r ) const
{
float denom = (widthRatio * widthRatio) + 1.0f;
float rSq = denom * r * r;
float eq = widthRatio * offset - offset - offset + h - (widthRatio * k);
eq *= eq;
return (1.0f / denom) *
((widthRatio * h) + k - offset - (widthRatio * (offset + offset)) - sqrt(rSq - eq) );
}
It uses the quadratic formula to find what the height should be so that the distance between the top right of the rectangle, bottom left, amd top left are = offset.
Is there something wrong with the formula or implementation? The problem is the height is never long enough.
Thanks
Well, here's my solution, which looks to resemble your solveHeight function. There might be some arithmetic errors in the below, but the method is sound.
You can think in terms of matching the coordinates at the point of the circle across
from the rectangle (P).
Let o_x,o_y be the lower left corner offset distances, w and h be the
height of the rectangle, w_r be the width ratio, dx be the desired
distance between the top right hand corner of the rectangle and the
circle (moving horizontally), c_x and c_y the coordinates of the
circle's centre, theta the angle, and r the circle radius.
Labelling it is half the work! Simply write down the coordinates of the point P:
P_x = o_x + w + dx = c_x + r cos(theta)
P_y = o_y + h = c_y + r sin(theta)
and we know w = w_r * h.
To simplify the arithmetic, let's collect some of the constant terms, and let X = o_x + dx - c_x and Y = o_y - c_y. Then we have
X + w_r * h = r cos(theta)
Y + h = r sin(theta)
Squaring and summing gives a quadratic in h:
(w_r^2 + 1) * h^2 + 2 (X*w_r + Y) h + (X^2+Y^2-r^2) == 0
If you compare this with your effective quadratic, then as long as we made different mistakes :-), you might be able to figure out what's going on.
To be explicit: we can solve this using the quadratic formula, setting
a = (w_r^2 + 1)
b = 2 (X*w_r + Y)
c = (X^2+Y^2-r^2)