I need the points of a "rotating cylinder". I've got some lines of a curve and looking for an implementation to calculate 16 points arount them to get a cycle. My implemenation looks like:
QPointF MappingModel::calcThicknessYarns(float fCurrentX, float fCurrentY, int iCurrentCounter)
{
QPointF nextPoint;
int iAmountOfThicknessYarns = 16;
float fSingleAngle = 360.0 / iAmountOfThicknessYarns;
float fCurrentAngle = fSingleAngle * iCurrentCounter;
nextPoint = getXY(fCurrentAngle, 1.0, 1.0, fCurrentX, fCurrentY);
return nextPoint;
}
and
QPointF MappingModel::getXY(float angle, float width, float height, float xOffset, float yOffset)
{
QPointF xy;
float FI = angle*PIdev;
xy.setX((width * qCos(FI)) + xOffset) ;
xy.setY((height * qSin(FI)) - yOffset);
return xy;
}
My looks like this:
http://www.directupload.net/file/d/3741/e8bafwni_jpg.htm
http://www.directupload.net/file/d/3741/tkykay7w_jpg.htm
As you can see, the the vertical cylinder works fine, but the curve is false
This may help.
It shouldn't be difficult to adapt Vertex to QPointF.
typedef struct {
double x;
double y;
} Vertex;
/**
* #param radius Radius of circle
* #param angle Degrees
* #return The offset of vertex from the center of circle given radius and angle
*/
Vertex getVerticeOffset(double radius, double angle) {
double yOffset = -radius*cos((90 - angle)*M_PI/180); // convert to radians
return Vertex({(angle >= 90 && angle < 270 ? -1 : 1) * sqrt(pow(radius, 2) - pow(yOffset, 2)), yOffset});
}
Related
So Here is the current code which does it correctly:
public:
void SetTime( float time )
{
t = time;
}
typename BaseVertexShader::Output operator()( const Vertex& v ) const
{
// calculate some triggy bois
const auto angle = wrap_angle( v.pos.x * freq + t * wavelength );
const auto cosx = std::cos( angle );
const auto sinx = std::sin( angle );
// sine wave amplitude from position w/ time variant phase animation
const auto dz = amplitude * cosx;
const auto pos = Vec4{ v.pos.x,v.pos.y,v.pos.z + dz,1.0f };
// normal derived base on cross product of partial dx x dy
auto n = Vec4{
-freq * amplitude * sinx,
0.0f,
-1.0f,
0.0f
};
n.Normalize();
return { pos * worldViewProj,n * worldView,pos * worldView,v.t };
}
private:
static constexpr float wavelength = PI;
static constexpr float freq = 45.0f;
static constexpr float amplitude = 0.02f;
float t = 0.0f;
};
Essentially, this is being applied to a plane. We take each vertex position x and calculate the angle based on the formulae and pass this angle to the cos function to evaluate, also sin which is used later for the derivative part.
we calculate the dz value which is how much to shift the z component up and down to create the oscilatting ripple effect on a plane. How would I calculate the dx and dy parts.
At the bottom of the code they create n and makes it x component which defines the direction of the vector, as being -freq * amplititude * sin(x) which confuses me as I do not exactly how this is derived from crossing dx and dy, whatever those values are.
Note: the axis is right handed coordinates, and the plane has rotated 90 degrees around the x direction , so the local coordinates of my plane has z pointing down and x pointing right. but my world space is z pointing into the screen , y up , and x right.
I am facing problems trying to make 3d objects clickable by mouse. For intersection checking I use ray casting. Code I found, ported for my solution:
Exactly picking
bool RaySphereIntersect(Vector3, Vector3, float);
bool TestIntersection(Matrix projectionMatrix, Matrix viewMatrix, Matrix worldMatrix, Vector3 origin, float radius, int m_screenWidth, int m_screenHeight, int mouseX, int mouseY)
{
float pointX, pointY;
Matrix inverseViewMatrix, translateMatrix, inverseWorldMatrix;
Vector3 direction, rayOrigin, rayDirection;
bool intersect, result;
// Move the mouse cursor coordinates into the -1 to +1 range.
pointX = ((2.0f * (float)mouseX) / (float)m_screenWidth) - 1.0f;
pointY = (((2.0f * (float)mouseY) / (float)m_screenHeight) - 1.0f) * -1.0f;
// Adjust the points using the projection matrix to account for the aspect ratio of the viewport.
pointX = pointX / projectionMatrix._11;
pointY = pointY / projectionMatrix._22;
// Get the inverse of the view matrix.
inverseViewMatrix=XMMatrixInverse(NULL, viewMatrix);
// Calculate the direction of the picking ray in view space.
direction.x = (pointX * inverseViewMatrix._11) + (pointY * inverseViewMatrix._21) + inverseViewMatrix._31;
direction.y = (pointX * inverseViewMatrix._12) + (pointY * inverseViewMatrix._22) + inverseViewMatrix._32;
direction.z = (pointX * inverseViewMatrix._13) + (pointY * inverseViewMatrix._23) + inverseViewMatrix._33;
// Get the origin of the picking ray which is the position of the camera.
// Get the world matrix and translate to the location of the sphere.
// Now get the inverse of the translated world matrix.
inverseWorldMatrix= XMMatrixInverse(NULL, worldMatrix);
// Now transform the ray origin and the ray direction from view space to world space.
rayOrigin=XMVector3TransformCoord(origin, inverseWorldMatrix);
rayDirection=XMVector3TransformNormal(direction, inverseWorldMatrix);
// Normalize the ray direction.
rayDirection=XMVector3Normalize(rayDirection);
// Now perform the ray-sphere intersection test.
intersect = RaySphereIntersect(rayOrigin, rayDirection, radius);
if (intersect == true)
return true;
else
return false;
}
bool RaySphereIntersect(Vector3 rayOrigin, Vector3 rayDirection, float radius)
{
float a, b, c, discriminant;
// Calculate the a, b, and c coefficients.
a = (rayDirection.x * rayDirection.x) + (rayDirection.y * rayDirection.y) + (rayDirection.z * rayDirection.z);
b = ((rayDirection.x * rayOrigin.x) + (rayDirection.y * rayOrigin.y) + (rayDirection.z * rayOrigin.z)) * 2.0f;
c = ((rayOrigin.x * rayOrigin.x) + (rayOrigin.y * rayOrigin.y) + (rayOrigin.z * rayOrigin.z)) - (radius * radius);
// Find the discriminant.
discriminant = (b * b) - (4 * a * c);
// if discriminant is negative the picking ray missed the sphere, otherwise it intersected the sphere.
if (discriminant < 0.0f)
return false;
else
return true;
}
How do I create sphere
D3DSphere(float x, float y, float z, float radius, float r, float g, float b, float a)
{
this->x = x;
this->y = y;
this->z = z;
this->radius = radius;
this->shape = GeometricPrimitive::CreateSphere(radius*2.0f);
this->world = Matrix::Identity;
this->world = XMMatrixMultiply(this->world, Matrix::CreateTranslation(x, y, z));
this->index = vsphere;
d3dsphere[vsphere] = this;
vsphere++;
}
How do I call raycaster
void Game::LButtonUp(int x, int y)
{
Vector3 eye(camx, camy, camz);
Vector3 at(Vector3::Zero);
m_view = Matrix::CreateLookAt(eye, at, Vector3::UnitY);
for (int i = 0; i < vsphere; i++)
{
if (TestIntersection(m_projection, m_view, d3dsphere[i]->world, eye, d3dsphere[i]->radius, 800, 600, x, y))
{
MessageBoxW(NULL, L"LOL", L"It works", MB_OK);
break;
}
}
}
Nothing happens by clicking, but if I rotate camera, perpendicularly to XOY, sometimes, clicking near the sphere, message box appears.
Update
MessageBox appears independently on camera angle, and it seems, that it detects intersection correctly, but mirrored, relatively to the window center. For example, if sphere is at (0, window.bottom-20) point then I will get MessageBox if I click at (0, 20) point.
What if calculation of the direction of the picking ray is wrong, if it was wrote for left-handed system, and I use right-handed?
Probably, because of the right-handed system, that is used by default in DirectX Tool Kit the next section from caster
pointX = ((2.0f * (float)mouseX) / (float)m_screenWidth) - 1.0f;
pointY = (((2.0f * (float)mouseY) / (float)m_screenHeight) - 1.0f) * -1.0f;
Should be changed to
pointX = (((2.0f * (float)mouseX) / (float)m_screenWidth) - 1.0f) * -1.0f;
pointY = (((2.0f * (float)mouseY) / (float)m_screenHeight) - 1.0f);
Important
That code also will work wrong because of depth independence, i.e. you may select sphere that is situated behind the sphere you clicking. For solve that I changed the code:
float distance3(float x1, float y1, float z1, float x2, float y2, float z2)
{
float dx=x1-x2;
float dy=y1-y2;
float dz=z1-z2;
return sqrt(dx*dx+dy*dy+dz*dz);
}
void Game::LButtonUp(int x, int y)
{
Vector3 eye(camx, camy, camz);
Vector3 at(Vector3::Zero);
m_view = Matrix::CreateLookAt(eye, at, Vector3::UnitY);
int last_index=-1;
float last_distance=99999.0f;//set the obviously highest value, may happen in your scene
for (int i = 0; i < vsphere; i++)
{
if (TestIntersection(m_projection, m_view, d3dsphere[i]->world, eye, d3dsphere[i]->radius, 800, 600, x, y))
{
float distance=distance3(camx,camy,camz, d3dsphere[i]->x, d3dsphere[i]->y, d3dsphere[i]->z);
if(distance<last_distance)
{
last_distance=distance;
last_index=i;
}
}
}
d3dsphere[last_index];//picked sphere
}
I have the following code to draw an arbitrary arc:
void CenteredArc::drawPolygonArc(float radius, float thickness, float startAngle, float arcAngle) {
float num_segments = 360.0;
float radiusOuter = radius + thickness / 2;
float radiusInner = radius - thickness / 2;
float theta = arcAngle / num_segments;
float tangetial_factor = tanf(theta);//calculate the tangential factor
float radial_factor = cosf(theta);//calculate the radial factor
float xxOuter = radiusOuter * cosf(startAngle);
float yyOuter = radiusOuter * sinf(startAngle);
float xxInner = radiusInner * cosf(startAngle);
float yyInner = radiusInner * sinf(startAngle);
float prevXXOuter = -1;
float prevYYOuter = -1;
float prevXXInner = -1;
float prevYYInner = -1;
glPolygonMode(GL_FRONT, GL_FILL);
for(int ii = 0; ii < num_segments; ii++)
{
if (prevXXOuter != -1) {
glBegin(GL_POLYGON);
glVertex2f(prevXXOuter, prevYYOuter);
glVertex2f(xxOuter, yyOuter);
glVertex2f(xxInner, yyInner);
glVertex2f(prevXXInner, prevYYInner);
glEnd();
}
//calculate the tangential vector
//remember, the radial vector is (x, y)
//to get the tangential vector we flip those coordinates and negate one of them
float txOuter = -yyOuter;
float tyOuter = xxOuter;
float txInner = -yyInner;
float tyInner = xxInner;
//add the tangential vector
prevXXOuter = xxOuter;
prevYYOuter = yyOuter;
prevXXInner = xxInner;
prevYYInner = yyInner;
xxOuter += txOuter * tangetial_factor;
yyOuter += tyOuter * tangetial_factor;
xxInner += txInner * tangetial_factor;
yyInner += tyInner * tangetial_factor;
//correct using the radial factor
xxOuter *= radial_factor;
yyOuter *= radial_factor;
xxInner *= radial_factor;
yyInner *= radial_factor;
}
}
However, I would like for the arc to start off with the specified thickness on one end and gradually decrease to a thickness of zero on the other end. Any suggestions?
Edit: I am not using GL_LINE_STRIP because I am trying to avoid having overlapping lines and gaps like so:
I would use a line strip with decreasing glLineWidth.
This is my implementation, it doesn't gradially reduce the lineWidth but it could be modified to do so. Sorry for the extra stuff, it's from my game engine.
for(int i=0;i<arcs().size();i++)
{
Entities::Arc temp = arcs().at(i);
glLineWidth(temp.LW.value); // change LWidth
glColor3f( temp.CL.R, temp.CL.G, temp.CL.B );
// theta is now calculated from the arc angle instead, the
// - 1 part comes from the fact that the arc is open
float theta = temp.A.value*DEG2RAD / float(WW_SPLINE_ACCURACY - 1);
float tan = tanf(theta);
float cos = cosf(theta);
// we are now at the starting angle
double x = temp.R.value * cosf(temp.A.value*DEG2RAD);
double y = temp.R.value * sinf(temp.A.value*DEG2RAD);
// since the arc is not a closed curve, this is a strip now
glBegin(GL_LINE_STRIP);
for(int ii = 0; ii < WW_SPLINE_ACCURACY; ii++)
{
glVertex2d(x + temp.C.X, y + temp.C.Y);
double tx = -y;
double ty = x;
x += tx * tan;
y += ty * tan;
x *= cos;
y *= cos; //y = ( y + (ty*tan) )*cos;
}
glEnd();
glLineWidth(WW_DEFAULT_LWIDTH); // reset LWidth
}
I also used these values
#define WW_SPLINE_ACCURACY 72 // 72 for extra smooth arcs/circles, 32 minimum
#define WW_BEZIER_ACCURACY 20
/* Math stuff */
#define DEG2RAD 3.14159/180
#define PI 3.1415926535897932384626433832795;
...
glDisable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glDisable(GL_COLOR_MATERIAL);
glEnable (GL_LINE_SMOOTH);
glEnable (GL_BLEND);
//glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
glEnable(GL_POLYGON_SMOOTH);
glClearColor(0.188f, 0.169f, 0.329f, 1.0f); //#302b54
I'm not allowed to release the full source since I wrote it for a company but sharing a part or two wont hurt anybody :D
I have defined 2 points on the surface of a sphere using spherical coordinates.
// define end point positions
float theta_point_1 = (5/10.0)*M_PI;
float phi_point_1 = (5/10.0)*2*M_PI;
float x_point_1 = Radius * sin(theta_point_1) * cos(phi_point_1);
float y_point_1 = Radius * sin(theta_point_1) * sin(phi_point_1);
float z_point_1 = Radius * cos(theta_point_1);
float theta_point_2 = (7/10.0)*M_PI;
float phi_point_2 = (1/10.0)*2*M_PI;
float x_point_2 = Radius * sin(theta_point_2) * cos(phi_point_2);
float y_point_2 = Radius * sin(theta_point_2) * sin(phi_point_2);
float z_point_2 = Radius * cos(theta_point_2);
// draw end points
void end_points ()
{
glColor3f (1.0, 1.0, 1.0);
glPointSize(25.0);
glBegin(GL_POINTS);
glVertex3f(x_point_1,y_point_1,z_point_1);
glVertex3f(x_point_2,y_point_2,z_point_2);
glEnd();
}
To step between the two points, I do the following:
find the difference between theta_points_1,2 and phi_points_1,2
divide the differences by 'n' (yielding 's')
redraw 'n' times, while stepping up the theta and phi by 's' each time
In the following, I've defined the differences between my theta and phi values, divided them, and then redraw them.
// begining spherical coords
float theta_point_1_value=5;
float phi_point_1_value=5;
// ending sperical coords
float theta_point_2_value=7;
float phi_point_2_value=1;
// dividing the difference evenly
float step_points=30;
float step_theta = 2/step_points;
float step_phi = 4/step_points;
// step between spherical coordinates
void stepping_points ()
{
glColor3f (1.0, 0.0, 0.0);
for (int i = 1; i < step_points; i++)
{
float theta = (theta_point_1_value/10.0)*M_PI;
float phi = (phi_point_1_value/10.0)*2*M_PI;
float x = Radius * sin(theta) * cos(phi);
float y = Radius * sin(theta) * sin(phi);
float z = Radius * cos(theta);
glPushMatrix();
glTranslatef(x,y,z);
glutSolidSphere (0.05,10,10);
glPopMatrix();
}
glEnd();
}
Now I understand, this displays 30 solid spheres at the same position. Because I have NOT included 'step_theta' or 'step_phi' in any of the redraws.
And that is the root of my question. How do I employ 'step_theta' and 'step_phi' in my redraws?
What I want to do is say something like this at the top of my 'for' loop:
for (int i = 1; i < step_points; i++)
{
float theta_point_1_value = (theta_point_1_value+step_theta);
float phi_point_1_value = (phi_point_1_value+step_phi);
float theta = (theta_point_1_value/10.0)*M_PI;
float phi = (phi_point_1_value/10.0)*2*M_PI;
float x = Radius * sin(theta) * cos(phi);
float y = Radius * sin(theta) * sin(phi);
float z = Radius * cos(theta);
glPushMatrix();
glTranslatef(x,y,z);
glutSolidSphere (0.05,10,10);
glPopMatrix();
}
The above will redraw 30 solid spheres, but they don't show between my defined end points. It's pretty clear that either my math or syntax is screwy (or more than likely, both are).
Hint: What is the range of your loop variable, i? What do you want the range of your step_theta and step_phi to be?
When you declare a variable inside the loop, it goes out of scope and is destructed after every iteration. As such, only the value of i changes between your loop iterations.
Also: Consider using a vector/point class. (x_point_1, y_point_1) is not C++ :).
If you want consistent timing regardless of frame rate, you need to track the passage of time and use that to control how far you interpolate between the two points. Remember the start time and calculate the desired end time, then each frame, calculate (float)(now-start)/(end-start). This will give you a value between 0.0 and 1.0. Multiply that value by the delta of each spherical coordinate and add their start angles and you'll get what angles you need to be at now.
There is a fast way to draw circle like this
void DrawCircle(float cx, float cy, float r, int num_segments)
{
float theta = 2 * 3.1415926 / float(num_segments);
float c = cosf(theta);//precalculate the sine and cosine
float s = sinf(theta);
float t;
float x = r;//we start at angle = 0
float y = 0;
glBegin(GL_LINE_LOOP);
for(int ii = 0; ii < num_segments; ii++)
{
glVertex2f(x + cx, y + cy);//output vertex
//apply the rotation matrix
t = x;
x = c * x - s * y;
y = s * t + c * y;
}
glEnd();
}
I am wondering if there is a similar way to draw ellipse where its major/minor axes vector and size are both known.
If we take your example we can use an internal radius of 1 and apply horizontal/vertical radius separately in order to get an ellipse:
void DrawEllipse(float cx, float cy, float rx, float ry, int num_segments)
{
float theta = 2 * 3.1415926 / float(num_segments);
float c = cosf(theta);//precalculate the sine and cosine
float s = sinf(theta);
float t;
float x = 1;//we start at angle = 0
float y = 0;
glBegin(GL_LINE_LOOP);
for(int ii = 0; ii < num_segments; ii++)
{
//apply radius and offset
glVertex2f(x * rx + cx, y * ry + cy);//output vertex
//apply the rotation matrix
t = x;
x = c * x - s * y;
y = s * t + c * y;
}
glEnd();
}
There is no way to draw a curve in openGL, just a lot of straight lines. But if you used vertex buffer objects then you won't have to send each vertex to the graphics card which will be much faster.
My Java Example
If the ellipse is ((x-cx)/a)^2 + ((y-cy)/b)^2 = 1 then change the glVertex2f call to
glVertext2d(a*x + cx, b*y + cy);
To simplify the sums, lets suppose for a while that the ellipse is centred at the origin.
If the ellipse is rotated so that the semi-major axis (of length a) makes an angle theta with the x axis, then the ellipse is the set of points p so that p' * inv(C) * p = 1, where C is the matrix R(theta) * D * R(theta)' where ' denotes transpose and D is the diagonal matrix with entries a*a,b*b (b the length of the semi-minor axis). If L is the cholesky factor (eg here) of C then the ellipse is the set of points p so that (inv(L) * p)'*(inv(L) *p ) = 1, so that L maps the unit circle to the ellipse. If we have computed L as ( u 0 ; v w) (just once, before the loop) then the glVertexf call becomes glVertex2f( u*x + cx, v*x + w*y + cy);
L can be calculated like this (where C is cos(theta) and S is sin(theta)):
u = sqrt( C*C*a*a + S*S*b*b); v = C*S*(a*a-b*b); w = a*b/u;