Generate a "pieslice" in C without using the pieslice() of graphics.h - c++

In the BGI library's "graphics.h" header there is a function pieslice in that header file,its syntax is:
#include <graphics.h>
void pieslice(int x, int y, int stangle, int endangle, int radius);
[x,y are the center of the circle,stangle and endangle are the starting and end angles respectively]
Can we make a pieslice in C/C++ without using this in-built function of the BGI library.Please help. Tried making it with the help of the lines and mid-point circle generation algorithms.
My code so far:
#include<stdio.h>
#include<graphics.h>
static const double PI =3.141592
int main()
{
int gd=DETECT,gm;
initgraph(&gd,&gm,NULL);
int xc,yc,r,st_angle,ed_angle,k;
printf("Enter the centers of pieslice:\n");
scanf("%d %d",&xc,&yc);
printf("Enter the radius:\n");
scanf("%d",&r);
printf("Enter the starting angle:\n");
scanf("%d",&st_angle);
printf("Enter the end angle:\n");
scanf("%d",&ed_angle);
for(k=st_angle; k<=ed_angle;k++)
{
double radians =(PI /180.0) * k;
int X = xc+ cos(radians) * r;
int Y = yc+ sin(radians) * r;
putpixel(x,y,WHITE);
delay(5000);
}
void wait_for_char()
{
//Wait for a key press
int in = 0;
while (in == 0) {
in = getchar();
}
}
getch();
}
I was able to do the calculation part where i used the parametric equation of circle,but unable to generate the figure using the graphics.h function. Some help would be nice. Thank you in advance.
While running this program,i am getting this error:
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
a.out: ../../src/xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
a.out: ../../src/xcb_io.c:274: poll_for_event: Assertion `!xcb_xlib_threads_sequence_lost' failed.
Aborted (core dumped)

why not use vectors?
So (0,0) centered pie of radius r is determined by:
u = (cos(a0),sin(a0))
v = (cos(a1),sin(a1))
x^2 + y^2 <= r^2 // circle
(x,y) x u -> CW
(x,y) x v -> CCW
the CW/CCW is determined by computing 3D cross product and examining the sign of results z coordinate...
so process all pixels in circle outscribed square and render all pixels that complies all 3 conditions.
Something like this:
void pie(int x0,int y0,int r,int a0,int a1,DWORD c)
{
// variables
int x, y, // circle centered point
xx,yy,rr, // x^2,y^2,r^2
ux,uy, // u
vx,vy, // v
sx,sy; // pixel position
// my Pixel access (remove these 3 lines)
int **Pixels=Main->pyx; // Pixels[y][x]
int xs=Main->xs; // resolution
int ys=Main->ys;
// init variables
rr=r*r;
ux=double(r)*cos(double(a0)*M_PI/180.0);
uy=double(r)*sin(double(a0)*M_PI/180.0);
vx=double(r)*cos(double(a1)*M_PI/180.0);
vy=double(r)*sin(double(a1)*M_PI/180.0);
// render |<-- remove these -->|
for (y=-r,yy=y*y,sy=y0+y;y<=+r;y++,yy=y*y,sy++) if ((sy>=0)&&(sy<ys))
for (x=-r,xx=x*x,sx=x0+x;x<=+r;x++,xx=x*x,sx++) if ((sx>=0)&&(sx<xs))
if (xx+yy<=rr) // inside circle
if ((x*uy)-(y*ux)<=0) // x,y is above a0 in clockwise direction
if ((x*vy)-(y*vx)>=0) // x,y is below a1 in counter clockwise direction
Pixels[sy][sx]=c; // change for putpixel
}
However I do not use BGI so just change the Pixels[sy][sx]=c; with your putpixel(sx,sy,c); and remove obsolete range check ifs for sx,sy. Also remove the resolution xs,ys and Pixels variables.
Here preview for (xs2,ys2 is mine middle of screen):
pie(xs2,ys2,ys2-200,10,50,0x00FF0000);
Note that I have 32 bit RGB color instead of your indexed 8 bit ones and angles are in degrees. Also note that mine y axis points down so incrementing angle is going clockwise starting from the x axis (pointing to right)
This however works only for pies below 180 degrees. For bigger ones you need to invert the cross product conditions to render when not inside the not filled pie part instead something like this:
void pie(int x0,int y0,int r,int a0,int a1,DWORD c) // a0 < a1
{
// variables
int x, y, // circle centered point
xx,yy,rr, // x^2,y^2,r^2
ux,uy, // u
vx,vy, // v
sx,sy; // pixel position
// my Pixel access
int **Pixels=Main->pyx; // Pixels[y][x]
int xs=Main->xs; // resolution
int ys=Main->ys;
// init variables
rr=r*r;
ux=double(r)*cos(double(a0)*M_PI/180.0);
uy=double(r)*sin(double(a0)*M_PI/180.0);
vx=double(r)*cos(double(a1)*M_PI/180.0);
vy=double(r)*sin(double(a1)*M_PI/180.0);
// handle big/small pies
x=a1-a0;
if (x<0) x=-x;
// render small pies
if (x<180)
{
for (y=-r,yy=y*y,sy=y0+y;y<=+r;y++,yy=y*y,sy++) if ((sy>=0)&&(sy<ys))
for (x=-r,xx=x*x,sx=x0+x;x<=+r;x++,xx=x*x,sx++) if ((sx>=0)&&(sx<xs))
if (xx+yy<=rr) // inside circle
if (((x*uy)-(y*ux)<=0) // x,y is above a0 in clockwise direction
&&((x*vy)-(y*vx)>=0)) // x,y is below a1 in counter clockwise direction
Pixels[sy][sx]=c;
}
else{
for (y=-r,yy=y*y,sy=y0+y;y<=+r;y++,yy=y*y,sy++) if ((sy>=0)&&(sy<ys))
for (x=-r,xx=x*x,sx=x0+x;x<=+r;x++,xx=x*x,sx++) if ((sx>=0)&&(sx<xs))
if (xx+yy<=rr) // inside circle
if (((x*uy)-(y*ux)<=0) // x,y is above a0 in clockwise direction
||((x*vy)-(y*vx)>=0)) // x,y is below a1 in counter clockwise direction
Pixels[sy][sx]=c;
}
}
pie(xs2,ys2,ys2-200,50,340,0x00FF0000);
The code can be further optimized for example x*uy can be changed to addition in for cycle like for(...,xuy=x*uy;...;...,xuy+=uy) eliminating slow multiplication from inner loops. The same goes for all 4 therms in the cross product conditions.
[edit1] To be more clear we have something like this:
for (x=-r,xx=x*x,sx=x0+x;x<=+r;x++,xx=x*x,sx++)
{
if (...(x*uy)...) { do something }
}
the (x*uy) is computed on each iteration of x. The x is incrementing so we can compute the value of (x*uy) from the previous value ((x-1)*uy)+uy which does not need multiplication as ((x-1)*uy) is the value from last iteration. So adding single variable that holds it can get rid of the repeated multiplication:
int xuy; // ******** *******
for (x=-r,xx=x*x,sx=x0+x,xuy=x*uy;x<=+r;x++,xx=x*x,sx++,xuy+=uy)
{
if (...(xuy)...) { do something }
}
so the initial multiplication is done just once and from then its just addition ...
Also this way of rendering is fully parallelisable...

Related

How do I implement the math function to calculate the ellipse normal that crosses a point into C++?

To calculate the shortest distance from a point to the circumference of an ellipse, I have to calculate the normal/angle that passes through this point. See the following illustration:
The math to calculate this normal is explained here. In short:
Where E is the ellipse and L is the line between the point p and the circumference that creates the normal.
In C++, I have the following code fragment, where I need to insert this formula - solving it to variable t:
#include <cmath>
/// Calculate the normal of a line from ellipse circumference to point.
///
/// #param ew The width of the ellipse
/// #param eh The height of the ellipse
/// #param x The relative x position (relative to ellipse center)
/// #param y The relative y position (relative to ellipse center)
/// #return The normal in radians.
///
auto calculateNormal(float ew, float eh, float x, float y) -> double {
// ???
return std::atan(...);
};
How can I implement the formula in C++ to get the normal as shown?
What you currently have is not yet solved system of equations which as I originally taught from experience with similar but slightly simpler problem the algebraic solution leads to horrible stuff that would be too slow and inaccurate to compute (math solver throw about 2 pages of equations for roots which I throw away right away) so I would attack this with search approach instead.
If you are worrying about speed due to using goniometrics you can avoid that completely by simply computing normal as numeric derivation of the circumference points and just compare the slopes between normal (nx,ny) and found_point(x,y) - input_point(px,py).
The algo is like this:
search x in range <-a,+a>
compute y=f(x) and y1=f(x+epsilon)
I simply rewrite the implicit ellipse equation into something like this:
float ellipse_y(float rx,float ry,float x) // y = f(x)
{
if (fabs(x)>rx) return 0.0
return sqrt((rx*rx)-(x*x))*ry/rx;
}
of coarse the result should be +/- depending on the quadrant so if py<0 use negative values...
The epsilon should be some small value but not too small, I used 0.001*rx where rx,ry are sizes of the ellipse half axises.
compute normal (nx,ny)
so simply take two consequent points (x,y) and (x+epsilon,y1) substract them and rotate by 90deg by exchanging their coordinates and negate one of them. Once put together I got this:
void ellipse_n(float rx,float ry,float &nx,float &ny,float x,float &y) // x',y',y = f(x)
{
if (x<=-rx){ y=0.0; nx=-1.0; ny=0.0; return; }
ny=x+(0.001*rx); // epsilon
if (ny>=+rx){ y=0.0; nx=+1.0; ny=0.0; return; }
y=ellipse_y(rx,ry,x); // first point
nx=y-ellipse_y(rx,ry,ny); // second point
ny=ny-x;
/*
// normalize
x=divide(1.0,sqrt((nx*nx)+(ny*ny)));
nx*=x;
ny*=x;
*/
}
The normalization is optional (I commented it out for speed as its not needed for the search itself).
compute error e for the search
Simply the slopes (x-px,y-py) and (nx,ny) should be equal so:
e=fabs(((y-py)*nx)-((x-px)*ny));
The x search should minimize the e towards zero.
Do not forget to handle py<0 by negating y. Putting all togetherusing my approx search leads to:
//---------------------------------------------------------------------------
float ellipse_y(float rx,float ry,float x) // y = f(x)
{
if (fabs(x)>rx) return 0.0;
return sqrt((rx*rx)-(x*x))*ry/rx;
}
//---------------------------------------------------------------------------
void ellipse_pn(float rx,float ry,float &nx,float &ny,float x,float &y) // x',y',y = f(x) if (py>=0)
{
if (x<=-rx){ y=0.0; nx=-1.0; ny=0.0; return; }
ny=x+(0.001*rx); // epsilon
if (ny>=+rx){ y=0.0; nx=+1.0; ny=0.0; return; }
y=ellipse_y(rx,ry,x); // first point
nx=y-ellipse_y(rx,ry,ny); // second point
ny=ny-x;
}
//---------------------------------------------------------------------------
void ellipse_nn(float rx,float ry,float &nx,float &ny,float x,float &y) // x',y',y = f(x) if (py<=0)
{
if (x<=-rx){ y=0.0; nx=-1.0; ny=0.0; return; }
ny=x+(0.001*rx); // epsilon
if (ny>=+rx){ y=0.0; nx=+1.0; ny=0.0; return; }
y=-ellipse_y(rx,ry,x); // first point
nx=y+ellipse_y(rx,ry,ny); // second point
ny=ny-x;
}
//---------------------------------------------------------------------------
void this_is_main_code()
{
float rx=0.95,ry=0.35; // ellipse
float px=-0.25,py=0.15; // input point
float x,y,nx,ny;
approx ax; double e;
if (py>=0.0)
{
for (ax.init(-rx,+rx,0.25*rx,3,&e);!ax.done;ax.step())
{
x=ax.a;
ellipse_pn(rx,ry,nx,ny,x,y);
e=fabs(((y-py)*nx)-((x-px)*ny));
}
x=ax.aa; y=+ellipse_y(rx,ry,x);
}
else{
for (ax.init(-rx,+rx,0.25*rx,3,&e);!ax.done;ax.step())
{
x=ax.a;
ellipse_nn(rx,ry,nx,ny,x,y);
e=fabs(((y-py)*nx)-((x-px)*ny));
}
x=ax.aa; y=-ellipse_y(rx,ry,x);
}
// here (x,y) is found solution and (nx,ny) normal
}
//---------------------------------------------------------------------------
You still can adjust the search parameters (step and recursions) to have desired precision and speed. Also you can optimize by inlinening and removing heap thrashing and moving the range checks before the iterations...
Also you should adjust the normal computation for range <rx-epsilon,rx> as it truncates it to x=+rx (you could use negative epsilon for that).
[Ed1t1]
If I see it right the point with matching normal is also closest points so we can search directly that (which is even faster):
// search closest point
if (py>=0.0)
{
for (ax.init(-rx,+rx,0.25*rx,3,&e);!ax.done;ax.step())
{
x=ax.a;
y=ellipse_y(rx,ry,x);
x-=px; y-=py; e=(x*x)+(y*y);
}
x=ax.aa; y=+ellipse_y(rx,ry,x);
}
else{
for (ax.init(-rx,+rx,0.25*rx,3,&e);!ax.done;ax.step())
{
x=ax.a;
y=-ellipse_y(rx,ry,x);
x-=px; y-=py; e=(x*x)+(y*y);
}
x=ax.aa; y=-ellipse_y(rx,ry,x);
}
Also I feel there still might be some better solution using graphic approach like rescale to circle solve for circle and then scale back to ellipse +/- some corrections however too lazy to try...

how to alternate colors in a circle, so that circle looks like rotating?

The expected output should be like this with the colors changing their position as well:
Expected output-:
the colors should change their positions in a circle so that it looks like they are moving without changing the position of circle.
though my code is written in codeblocks in c/c++, i will be happy to get answers in any other programming languages.
my present code
#include<graphics.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<string.h>
#include<iostream>
using namespace std;
void vvcircle(float xk,float yk,float radius);
int i=0;
int main()
{
float xk,yk,radius;
int gdriver=DETECT,gmode,errorcode;
initgraph(&gdriver,&gmode,"C:\\TURBOC3\\BGI");
// cout<<"enter the value of x, y and radius of circle"<<endl;
//cin>>xk>>yk>>radius;
vvcircle(200,200,100);
getch();
closegraph();
return 0;
}
void vvcircle(float xk,float yk,float radius)
{
int color[60]={0,1,2,3,4,5,6,7,8,9};
while(radius>0)
{
float xo,yo;
float P;
xo=0.0;
yo=radius;
P=1-radius;
/// vvcircle(200,200,100);
for(;xo<=yo;)
{
putpixel(xo+xk,yo+yk,1);
putpixel(yo+xk,xo+yk,1);
putpixel(-yo+xk,xo+yk,2);
putpixel(xo+xk,-yo+yk,2);
putpixel(-yo+xk,-xo+yk,4);
putpixel(-xo+xk,-yo+yk,4);
putpixel(yo+xk,-xo+yk,4);
putpixel(-xo+xk,+yo+yk,4);
if(P<0)
{
xo=xo+1;
yo=yo;
P=P+2*xo+1;
}
else
{
xo=xo+1;
yo=yo-1;
P=P+(2*xo)-(2*yo)+1;
// putpixel(xo,yo,WHITE);
}
}
radius=radius-1;
}
}
Present output-:
i get many concentric circles with colors. but i want to move the colors so that it looks like the circle is moving and it is not achieved.
How about something like this:
#include <math.h>
void my_circle(int xc,int yc,int r,float a) // center(x,y), radius, animation angle [rad]
{
const int n=4; // segments count
int x,sx,xx,x0,x1,rr=r*r,
y,sy,yy,y0,y1,i,
dx[n+1],dy[n+1], // segments edges direction vectors
c[n]={5,1,2,3}; // segments colors
float da=2.0*M_PI/float(n);
// BBOX
x0=xc-r; x1=xc+r;
y0=yc-r; y1=yc+r;
// compute segments
for (i=0;i<=n;i++,a+=da)
{
dx[i]=100.0*cos(a);
dy[i]=100.0*sin(a);
}
// all pixels in BBOX
for (sx=x0,x=sx-xc;sx<=x1;sx++,x++){ xx=x*x;
for (sy=y0,y=sy-yc;sy<=y1;sy++,y++){ yy=y*y;
// outside circle?
if (xx+yy>rr) continue;
// compute segment
for (i=0;i<n;i++)
if ((x*dy[i ])-(y*dx[i ])>=0)
if ((x*dy[i+1])-(y*dx[i+1])<=0)
break;
// render
putpixel(sx,sy,c[i]);
}}
}
It simply loop through all pixels of outscribed square to your circle, determines if pixel is inside and then detect which segment it is in and color it with segments color.
The segments are described by direction vectors from circle center towards the segments edges. So if pixel is inside it mean its CW to one edge and CCW to the other so in 2D inspecting z coordinate of the cross product between vector to pixel and vectors to edges will tell if the pixel is in or not ...
As you can see I did not use floating point math in the rendering it self, its needed only to compute the segments edge vectors prior rendering...
I used standard 256 color VGA palette (not sure what BGI uses I expect 16 col) so the colors might be different on your platform here preview:
The noise is caused by my GIF capturing tool dithering the render itself is clean ...
Do not forget to call the my_circle repeatedly with changing angle ...
PS. I encoded this in BDS2006 without BGI so in different compiler there might be some minor syntax problem related to used language quirks...
I faked the putpixel with this:
void putpixel(int x,int y,BYTE c)
{
static const DWORD pal[256]=
{
0x00000000,0x000000A8,0x0000A800,0x0000A8A8,0x00A80000,0x00A800A8,0x00A85400,0x00A8A8A8,
0x00545454,0x005454FC,0x0054FC54,0x0054FCFC,0x00FC5454,0x00FC54FC,0x00FCFC54,0x00FCFCFC,
0x00000000,0x00101010,0x00202020,0x00343434,0x00444444,0x00545454,0x00646464,0x00747474,
0x00888888,0x00989898,0x00A8A8A8,0x00B8B8B8,0x00C8C8C8,0x00DCDCDC,0x00ECECEC,0x00FCFCFC,
0x000000FC,0x004000FC,0x008000FC,0x00BC00FC,0x00FC00FC,0x00FC00BC,0x00FC0080,0x00FC0040,
0x00FC0000,0x00FC4000,0x00FC8000,0x00FCBC00,0x00FCFC00,0x00BCFC00,0x0080FC00,0x0040FC00,
0x0000FC00,0x0000FC40,0x0000FC80,0x0000FCBC,0x0000FCFC,0x0000BCFC,0x000080FC,0x000040FC,
0x008080FC,0x009C80FC,0x00BC80FC,0x00DC80FC,0x00FC80FC,0x00FC80DC,0x00FC80BC,0x00FC809C,
0x00FC8080,0x00FC9C80,0x00FCBC80,0x00FCDC80,0x00FCFC80,0x00DCFC80,0x00BCFC80,0x009CFC80,
0x0080FC80,0x0080FC9C,0x0080FCBC,0x0080FCDC,0x0080FCFC,0x0080DCFC,0x0080BCFC,0x00809CFC,
0x00B8B8FC,0x00C8B8FC,0x00DCB8FC,0x00ECB8FC,0x00FCB8FC,0x00FCB8EC,0x00FCB8DC,0x00FCB8C8,
0x00FCB8B8,0x00FCC8B8,0x00FCDCB8,0x00FCECB8,0x00FCFCB8,0x00ECFCB8,0x00DCFCB8,0x00C8FCB8,
0x00B8FCB8,0x00B8FCC8,0x00B8FCDC,0x00B8FCEC,0x00B8FCFC,0x00B8ECFC,0x00B8DCFC,0x00B8C8FC,
0x00000070,0x001C0070,0x00380070,0x00540070,0x00700070,0x00700054,0x00700038,0x0070001C,
0x00700000,0x00701C00,0x00703800,0x00705400,0x00707000,0x00547000,0x00387000,0x001C7000,
0x00007000,0x0000701C,0x00007038,0x00007054,0x00007070,0x00005470,0x00003870,0x00001C70,
0x00383870,0x00443870,0x00543870,0x00603870,0x00703870,0x00703860,0x00703854,0x00703844,
0x00703838,0x00704438,0x00705438,0x00706038,0x00707038,0x00607038,0x00547038,0x00447038,
0x00387038,0x00387044,0x00387054,0x00387060,0x00387070,0x00386070,0x00385470,0x00384470,
0x00505070,0x00585070,0x00605070,0x00685070,0x00705070,0x00705068,0x00705060,0x00705058,
0x00705050,0x00705850,0x00706050,0x00706850,0x00707050,0x00687050,0x00607050,0x00587050,
0x00507050,0x00507058,0x00507060,0x00507068,0x00507070,0x00506870,0x00506070,0x00505870,
0x00000040,0x00100040,0x00200040,0x00300040,0x00400040,0x00400030,0x00400020,0x00400010,
0x00400000,0x00401000,0x00402000,0x00403000,0x00404000,0x00304000,0x00204000,0x00104000,
0x00004000,0x00004010,0x00004020,0x00004030,0x00004040,0x00003040,0x00002040,0x00001040,
0x00202040,0x00282040,0x00302040,0x00382040,0x00402040,0x00402038,0x00402030,0x00402028,
0x00402020,0x00402820,0x00403020,0x00403820,0x00404020,0x00384020,0x00304020,0x00284020,
0x00204020,0x00204028,0x00204030,0x00204038,0x00204040,0x00203840,0x00203040,0x00202840,
0x002C2C40,0x00302C40,0x00342C40,0x003C2C40,0x00402C40,0x00402C3C,0x00402C34,0x00402C30,
0x00402C2C,0x0040302C,0x0040342C,0x00403C2C,0x0040402C,0x003C402C,0x0034402C,0x0030402C,
0x002C402C,0x002C4030,0x002C4034,0x002C403C,0x002C4040,0x002C3C40,0x002C3440,0x002C3040,
0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,
};
if ((x<0)||(x>=Main->xs)) return;
if ((y<0)||(y>=Main->ys)) return;
Main->pyx[y][x]=pal[c];
}
Where Main->xs, Main->ys is my window resolution and Main->pyx is direct pixel acces to its canvas for more info see:
Graphics rendering: (#4 GDI Bitmap)

Programming a specific 3d (star-like) model in OpenGL? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How can I create the following model:
by starting from the first drawing. Could it be programmed in OpenGL entirely or should I use other software like 3d Studio Max or Unity? Are there some specific algorithms that should be used?
Yes this can be done in C++/OpenGL
create random curves emitting from center
simple 3D quadratic polynomial curve will fit the bill.
convert the curves to cones
simply interpolate points along each curve and use it as a center for the cone slice. The direction is set by the previous or next point along the curve. Interpolate the cone slices and add their points to some point list. See:
Smoothly connecting circle centers
create faces
simply connect the computed points to form the cones using any primitive ... I would suggest GL_QUADs...
core
if you want to add also the core (nuclei?) it can be done a s a sphere with some noise added to its surface and probably some filtering to smooth it a bit...
Here simple curve generation C++ example:
List<double> pnt;
void spicule_init()
{
double t,tt,x,y,z;
double a0[3],a1[3],a2[3];
int ix0,ix,i,j;
Randomize();
for (i=0;i<20;i++) // cones
{
// random quadratic 3D curve coeff
for (j=0;j<3;j++)
{
a0[j]=0.0; // center (0,0,0)
a1[j]=2.0*(Random()-0.5); // main direction
a2[j]=1.0*(Random()-0.5); // curvature
}
// curve interpolation
ix0=pnt.num;
for (t=0.0;t<=1.0;t+=0.04)
for (tt=t*t,j=0;j<3;j++)
pnt.add(a0[j]+(a1[j]*t)+(a2[j]*tt));
}
}
Preview of the generated points:
[Edit1] When added the cones,normals and faces it looks like this:
Its far from perfect but I think is a good start point. Just tweak the radius r and the curve coefficients a1[],a2[] to achieve desired shape ... and may be add the core and or check for self intersections too, I am too lazy to do that...
Here the updated C++/GL code:
//---------------------------------------------------------------------------
List<double> pnt,nor; // points, normals
List<int> fac; // QUAD faces
//---------------------------------------------------------------------------
void Circle3D(List<double> &pnt,List<double> &nor,double *p0,double *n0,double r,int N)
{
int i;
double a,da=divide(pi2,N),p[3],dp[3],x[3],y[3];
vector_ld(x,1.0,0.0,0.0); if (fabs(vector_mul(x,n0)>0.7)) vector_ld(x,0.0,1.0,0.0);
vector_mul(x,x,n0); vector_one(x,x);
vector_mul(y,x,n0); vector_one(y,y);
for (a=0.0,i=0;i<N;i++,a+=da)
{
vector_mul( p,x,cos(a));
vector_mul(dp,y,sin(a));
vector_add(p,p,dp); nor.add(p[0]); nor.add(p[1]); nor.add(p[2]);
vector_mul(p,p,r);
vector_add(p,p,p0); pnt.add(p[0]); pnt.add(p[1]); pnt.add(p[2]);
}
}
//---------------------------------------------------------------------------
void spicule_init() // generate random spicule mesh
{
const int N=36; // points/circle
const int N3=3*N;
double t,tt,x,y,z,r;
double a0[3],a1[3],a2[3];
double p[3],n[3];
int e,i,j,i00,i01,i10,i11;
Randomize();
pnt.num=0; nor.num=0; fac.num=0;
for (i=0;i<20;i++) // cones
{
// random quadratic 3D curve coeff
for (j=0;j<3;j++)
{
a0[j]=0.0; // center (0,0,0)
a1[j]=2.0*(Random()-0.5); // main direction and size
a2[j]=1.0*(Random()-0.5); // curvature
}
// curve interpolation
vector_ld(n,0.0,0.0,0.0);
for (e=0,t=0.05;t<=1.0;t+=0.05)
{
// points,normals
for (tt=t*t,j=0;j<3;j++) p[j]=a0[j]+(a1[j]*t)+(a2[j]*tt);
r=0.15*(1.0-pow(t,0.1)); // radius is shrinking with t
vector_sub(n,p,n); // normal is p(t)-p(t-dt)
Circle3D(pnt,nor,p,n,r,N); // add circle to pnt (N points)
vector_copy(n,p); // remember last point
// faces
if (!e){ e=1; continue; } // ignore first slice of cone
i00=pnt.num- 3; i10=i00-N3;
i01=pnt.num-N3; i11=i01-N3;
for (j=0;j<N;j++)
{
fac.add(i00);
fac.add(i01);
fac.add(i11);
fac.add(i10);
i00=i01; i01+=3;
i10=i11; i11+=3;
}
}
}
}
//---------------------------------------------------------------------------
void spicule_draw() // render generated spicule
{
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
int i,j;
glColor3f(1.0,1.0,1.0);
glBegin(GL_QUADS);
for (i=0;i<fac.num;i++)
{
j=fac.dat[i];
glNormal3dv(nor.dat+j);
glVertex3dv(pnt.dat+j);
}
glEnd();
}
//---------------------------------------------------------------------------
If you do not know how to compute vector operations like cross/dot products or absolute value see:
// cross product: W = U x V
W.x=(U.y*V.z)-(U.z*V.y)
W.y=(U.z*V.x)-(U.x*V.z)
W.z=(U.x*V.y)-(U.y*V.x)
// dot product: a = (U.V)
a=U.x*V.x+U.y*V.y+U.z*V.z
// abs of vector a = |U|
a=sqrt((U.x*U.x)+(U.y*U.y)+(U.z*U.z))
vector_mul(a[3],b[3],c[3]) is cross product a = b x c
a = vector_mul(b[3],c[3]) is dot product a = (b.c)
vector_one(a[3],b[3]) is unit vector a = b/|b|
vector_copy(a[3],b[3]) is just copy a = b
vector_add(a[3],b[3],c[3]) is adding a = b + c
vector_sub(a[3],b[3],c[3]) is substracting a = b - c
vector_neg(a[3],b[3]) is negation a = -b
vector_ld(a[3],x,y,z) is just loading a = (x,y,z)
Also some (if not all the) Vector math used can be found here:
Understanding 4x4 homogenous transform matrices
I also use mine dynamic list template so:
List<double> xxx; is the same as double xxx[];
xxx.add(5); adds 5 to end of the list
xxx[7] access array element (safe)
xxx.dat[7] access array element (unsafe but fast direct access)
xxx.num is the actual used size of the array
xxx.reset() clears the array and set xxx.num=0
xxx.allocate(100) preallocate space for 100 items

Create a plot graphs with c++ visual studio

The Y axis will be scaled automatically, depending on the values coming fallowing function.
void mouseHandleCordinate(double val){
// include graph function.
}
So I want to create the plot chart against the time. X axis represent time and Y represent the value coming above function. How I create above graph function.
Always pass the data into void mouseHandleCordinate(double val) function.
As example:
val >>> 2.1,3,1,6,7,5.5,0,9,5,6,7,3.6,2,5,6,7,8,1,2,3,4 >> represent double val
Time>>> 21,20,19,18,17,......., 4,3,2,1 second
not sure I got what you asking but looks like you want to create continuous function following table of sampled points like:
const int N=21; // number of samples
const double t0=21.0,t1=1.0; // start,end times
const double val[N]={ 2.1,3,1,6,7,5.5,0,9,5,6,7,3.6,2,5,6,7,8,1,2,3,4 };
double f(double t) // nearest
{
t = (t-t0)/(t1-t0); // time scaled to <0,1>
t*= (N-1); // time scaled to <0,N) .. index in table
int ix=t; // convert to closest index in val[]
if ((ix<0)||(ix>=N)) return 0.0; // handle undefined times
return val[ix]; // return closest point in val[]
}
This will give you the nearest neighbor style function value. If you need something better use linear or cubic or better interpolation for example:
double f(double t) // linear
{
t = (t-t0)/(t1-t0); // time scaled to <0,1>
t*= (N-1); // time scaled to <0,N) .. index in table
int ix=t; // convert to closest index in val[]
if ((ix<0)||(ix>=N)) return 0.0; // handle undefined times
if (ix==N-1) return val[ix]; // return closest point in val[] if on edge
// linear interpolation
t = t-floor(t); // distance of time between ix and ix+1 points scaled to <0,1>
return val[ix]+(val[ix+1]-val[ix])*t; // return linear interpolated value
}
Now to your problem:
void mouseHandleCordinate(double mx) // mouse x coordinate in [pixels] I assume
{
double t,x,y,x0,y0
// plot
x=0;
y=f(view_start_time)
for (t=view_start_time;t<=view_end_time;t+=(view_end_time-view_start_time)/view_size_in_pixels,x0=x,x++)
{
y0=y; y=f(t);
// render line x0,y0,x,y
}
// mouse highlight
t = view_start_time+((view_end_time-view_start_time)*mx/view_size_in_pixels);
x = mx;
y = f(t);
// render point x,y ... for example with circle r = 16 pixels
}
where:
view_start_time is time of the left most pixel in your plot view
view_end_time is time of the right most pixel in your plot view
view_size_in_pixels is the x resolution in [pixels] of your plot view
[Notes]
I code the stuff directly in SO editor so there may be typos ...
Hoping you are calling the mouseHandleCordinate in some Paint event instead of on mouse movement which should only schedule repaint order... Also you should add y view scale in similar manner to x scale I used ...
For more info see:
How can i produce multi point linear interpolation?

How do I simulate 2D spherical waves from a point source?

I'm trying to simulate waves by numerically integrating the wave equation using euler integration (just until I get the kinks worked out, then I'll switch to runge-kutta). I'm using an array of floats as a grid. Then I create a disturbance by changing the value of the grid at one point. Now, instead of radiating in all directions away from this point, the wave only travels in one direction, towards the upper-left, i.e. towards decreasing x and y. So, my question is how do I make the wave radiate out?
Here's my code
void Wave::dudx(float *input,float *output) //calculate du/dx
{
for(int y=0;y<this->height;y++)
{
for(int x=0;x<this->width;x++)
{
output[x+y*this->width]=(this->getPoint((x+1)%this->width,y)-this->getPoint(x,y)); //getPoint returns the value of the grid at (x,y)
}
}
}
void Wave::dudy(float *input,float *output) //calculate du/dy
{
for(int x=0;x<this->width;x++)
{
for(int y=0;y<this->height;y++)
{
output[x+y*this->width]=(this->getPoint(x,(y+1)%this->height)-this->getPoint(x,y));
}
}
}
void Wave::simulate(float dt)
{
float c=6.0f;
//calculate the spatial derivatives
this->dudx(this->points,this->buffer);
this->dudx(this->buffer,this->d2udx2);
this->dudy(this->points,this->buffer);
this->dudy(this->buffer,this->d2udy2);
for(int y=0;y<this->height;y++)
{
for(int x=0;x<this->width;x++)
{
this->points[x+y*this->width]+=c*c*(this->d2udx2[x+y*this->width]+this->d2udy2[x+y*this->width])*dt*dt; //I know that I can calculate c*c and dt*dt once, but I want to make it clear what I'm doing.
}
}
}
Just for the sake of somebody else coming here for the same problem. The usual way to convert the Laplacian to a finite difference expression on a regular grid is:
∆u(x,y) -> idx2*[u(x+1,y) + u(x-1,y) - 2*u(x,y)] +
idy2*[u(x,y+1) + u(x,y-1) - 2*u(x,y)]
where idx2 and idy2 are the inverse squares of the grid spacing in dimension x and y respectively. In the case when the grid spacing in both dimensions is the same, this simplifies to:
∆u(x,y) -> igs2*[u(x+1,y) + u(x-1,y) + u(x,y+1) + u(x,y-1) - 4*u(x,y)]
The multiplicative coefficient can be removed by hiding it inside other coefficients, e.g. c, by changing their units of measurement:
∆u(x,y) -> u(x+1,y) + u(x-1,y) + u(x,y+1) + u(x,y-1) - 4*u(x,y)
By the way, there cannot be 2D spherical waves since spheres are 3D objects. 2D waves are called circular waves.