ANAND INSTITUTE OF HIGHER TECHNOLOGY OLD MAHABALIPURAM MAHABALIPURAM ROAD, KALASALINGAM KALASALINGAM NAGAR KAZHIPATTUR, KAZHIPATTUR, CHENNAI-603 CHENNAI-603 103.
DEPARTMENT DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
CS2405-COMP CS2405-COMPUTER UTER GRAPHICS GRAPHICS LABORATORY
Prepared by,
ANAND INSTITUTE OF HIGHER TECHNOLOGY OLD MAHABALIPURAM MAHABALIPURAM ROAD, KALASALINGAM KALASALINGAM NAGAR KAZHIPATTUR, KAZHIPATTUR, NEAR CHENNAI-603 103.
CS2405-COMPUTER CS2405-COMPUTER GRAPHICS GRAPHICS LABORATORY
Exp eriments List of Exp
1. Write a program to draw the line using DDA algorithm. ’s algorithm. 2. Write a program program to draw the the line using Bresenha Bresenham m’s algorithm. 3. Develop a program to draw the circle using midpoint circle algorithm. 4. Develop a program to draw the ellipse using midpoint ellipse ellipse algorithm. 5. Program to implement the various attributes of output primitives. 6. Program to implement the 2D transformation. 7. Program to implement the 2D Composite transformation. 8. Develop a program to clip a line using Cohen Sutherland line clipping algorithm. 9. Develo Develop p a progra program m to clip clip a polygon polygon using Sutherl Sutherland and Hodgema Hodgeman n Polygon Polygon clipping clipping algorithm. 10. Write a simple opengl program to create a 3 D object. 11. Write a simple opengl program to create a 3 D scene. 12. Program to implement the 3D transformation. 13. Write a Program to implement 3D Composite Transformation. 14. Develop Develop a fracta fractall image image using blender. blender.
Ex. No. 1
DDA LINE DRAWING AL A LGORITHM
AIM:
To write a C program program for drawing drawing a line and to display display the pixel positions positions using using digital differential Analyser (DDA) algorithm. DESCRIPTION:
The digita digitall differ different ential ial analyzer analyzer (DDA) (DDA) is a scan-conversion line algorithm algorithm based on calculation either ∆y or ∆x.The line at unit intervals in one coordinate and determine corresponding integer values nearest the line path for the other coordinate.
Straight line Segment with five sampling positions along the x axis between x1 and x2.
A line with positive slope (Left-right), if the slope is less than or equal to 1, at unit x and compute each successi intervals (∆x=1) and compute successive ve y values as xk+1 = xk + 1 yk+1 = yk + m For For line liness with with a posi positi tive ve slope slope (Lef (Leftt-rig right ht), ), grea greate terr than than 1 (∆ y=1) and calcula calculate te each succee succeeding ding x value value as yk+1 = yk + 1 xk+1 = xk + (1/m) A line with positive slope (Right-Left), if the slope is less than or equal to 1, at unit x
intervals (∆x=-1) and compute each successive successive y values as xk+1 = xk - 1 yk+1 = yk - m For lines lines with with a positi positive ve slope slope (Right (Right-le -left) ft),, greate greaterr than than 1 (∆ y=-1) and calcul calculate ate each succee succeeding ding x value value as yk+1 = yk - 1 xk+1 = xk - (1/m)
ADVANTAGES:
• •
It is a faster method than the direct use of the line equation. It eliminates the floating point multiplication multiplication by making making use of raster characteristics, characteristics, so increments are applied in x or y direction to step to pixel position along the line path.
DISADVANTAGES:
• •
It drifts drifts away from the actual line path because of rounding off float values to inte ger. It is time consuming since floating point arithmetic and rounding operations are done to calculate pixel position.
ALGORITHM:
Step 1: Accept Input Input as two endpoint pixel positions Step 2: Horizontal and vertical differences between the endpoint positions are assigned to parameters parameters dx and dy (Calculate (Calculate dx=xb-xa and dy=yb-ya). dy=yb-ya). Step 3: The difference with the greater magnitude determines the value of parameter steps. Step 4: Starting with pixel position (xa, ya), determine the offset needed at each step to generate the next pixel position position along the line path. Step 5: loop the following following process process for steps number number of times a.
Use a unit unit of incr increment ement or decrem decrement ent in the the x and and y direct direction ion
b. i f xa is less than xb the the values of increment increment in the x and y directions directions are 1 and m c.If c.If xa is greater than xb then the decrements -1 and – and – m m are used. CODING:
#include
#include #include #include int round(float m) { int n; if((m-0.5)>floor(m)) n=ceil(m); else n=floor(m); return n; } void main()
{ int x1,x2,y1,y2; int gdriver=DETECT,gmode; void lineDDA(int xa,int ya,int xb,int yb); initgraph(&gdriver,&gmode,"E:\\TC\\BGI"); setbkcolor(GREEN); printf("enter starting point coordinates\n"); scanf("%d%d",&x1,&y1); printf("enter end point coordinates\n"); scanf("%d%d",&x2,&y2); lineDDA(x1,y1,x2,y2); getch(); closegraph(); } void lineDDA(int xa,int ya,int xb,int yb) { int dx=xb-xa,dy=yb-ya,steps,k; float xincr,yincr,X=xa,Y=ya; if(abs(dx)>abs(dy)) steps=abs(dx); else steps=abs(dy); xincr=dx/(float)steps; yincr=dy/(float)steps; putpixel(round(X),round(Y),2); printf("\nk\tX\t\tY\tround(X)\tround(Y)\tcoord(X,Y)"); for(k=0;k
OUTPUT:
RESULT:
Thus the program for DDA line drawing algorithm is implemented and executed successfully.
Ex. No. 2
BRESENHAM LINE DRAWING ALGORITHM
AIM:
To write a C program for drawing a line and to display the pixel positions using Bresenham line drawing algorithm. DESCRIPTION:
An accurate and efficient raster line generating algorithm developed by Bresenhams that uses only incremental incremental integer calculations. calculations. Pixel positions along a line path are then determined by sampling at unit x intervals. Starting from the left end point (x0, y0) of a given line, we step to each successive column(x position) and plot the pixel whose scan line y value is closest to the line path. Assuming we have determined that the pixel at (xk , yk ) is to be displayed, we next need to decide which pixel to plot in column xk+1.Our choices are the pixels at positions (xk +l, +l, yk ) and (xk +l, +l, yk +l). +l).
ALGORITHM: Step 1: Input Input the two two line endpoints endpoints and store store the left left end point point in (x (x0, y0) Step 2: Load (x0, y0) into frame buffer, ie. Plot P lot the first point.
Step 3: Calculate the constants ∆ constants ∆x, x, ∆y, 2∆ 2 ∆ y and obtain the starting value for the decision decision parameter parameter as P0 = 2∆ y-∆ y-∆x line, starting starting at k=0 k=0 perform the following following test Step 4: At 4: At each x k along the line, If P k < 0, the next point to plot is(xk+1,yk ) and and Pk+1 = Pk + 2∆ y
otherwise, the next point to plot is (xk+1,yk+1) and and Pk+1 = Pk + 2∆ y - 2∆x
Step Step 5: Perfor Perform m step4 ∆ step4 ∆ x times. CODING:
#include #include #include #include void main() { int xa,ya,xb,yb; int gdriver=DETECT,gmode; void bres(int xa,int ya,int xb,int yb); initgraph(&gdriver,&gmode,"D:\\TC\\BGI"); setbkcolor(LIGHTRED); printf("enter the starting point coords"); scanf("%d%d",&xa,&ya); printf("enter the endpoints coords"); scanf("%d%d",&xb,&yb); bres(xa,ya,xb,yb); getch();closegraph(); } void bres(int xa,int ya,int xb,int yb) { int dx,dy,p,twody,twodydx,x,y,xend,k=0; dx=abs(xa-xb); dy=abs(ya-yb); p=2*dy-dx; twody=2*dy; twodydx=2*(dy-dx); if(xa>xb) { x=xb;y=yb; xend=xa; } else {
x=xa;y=ya; xend=xb; } printf("k\tp\tcoors\n"); putpixel(x,y,2); while(x
RESULT:
Thus the program for Bresenham line drawing algorithm is implemented and executed successfully.
Ex. No. 3
MIDPOINT CIRCLE ALGORITHM
AIM:
To write a C program for drawing a circle using midpoint circle algorithm. DESCRIPTION:
A circle is defined as a set of points that are all the given distance (xc,yc).
In the raster line algorithm at unit intervals and determine the closest pixel position to the specified circle path at each step for a given radius r and screen. center position (xc,yc) set up our algorithm to calculate pixel positions around a circle path centered at the coordinate positi position on by adding adding xc to x and yc to y. Circle function is f circle (x,y) = x2+y2-r2 circle(x,y) Any point (x,y) on the boundary of the circle with radius r satisfies the equation f circle circle (x,y)=0. If the point is in the interior of the circle, the circle function is negative. And if the point is outside the circle the, circle function is positive f circle circle (x,y) =
<0, if (x,y) (x,y) is inside inside the circle circle boundary boundary =0, if (x,y) is on the circle boundary >0, if (x,y) is outside outside the circle boundary boundary
ALGORITHM: Step Step 1: Input nput radi radius us r and circle circle cente centerr (xc,yc) and obtain the first point on the circumference of the circle centered on the origin origin as
(x0,y0) = (0, r)
Step 2: Calculate the initial value of the decision parameter as P0= (5/4)-r=1-r position, starting at k=0, perform the following test. If P k <0 <0 the next point Step 3: At each x k position, along the circle centered centered on (0,0) is (xk+1, yk ) and Pk+1=P k+2x k+1+1 Otherwise Otherwise the next point along the circle circle is (xk +1, +1, yk -1 -1) and Pk+1=Pk+2x k+1+1-2 yk+1 Where 2xk+1=2xk+2 and 2yk+1 =2y k-2 Step 4: Determine Determine symmetry points in in the other seven octants. octants. Step 5: Move each calculated pixel position (x,y) (x,y) onto the circular path centered at (xc,yc) and plot the the coordinate coordinate values. x=x+xc y=y+yc
Step 6: Repeat step step 3 through 5 until x>=y. CODINGS: #include #include #include void main() { int radius,xcenter,ycenter,x,y,p,k=0; int gdriver=DETECT,gmode; clrscr(); initgraph(&gdriver,&gmode,"C:\\TC\\BGI"); setbkcolor(LIGHTRED); printf("enter circle center"); scanf("%d%d",&xcenter,&ycenter); printf("enter the radius"); scanf("%d",&radius); x=0; y=radius; p=1-radius;putpixel(x,y,5); printf("k\tp\t coords(x,y)\t\n"); printf("%d\t%d\t(%d,%d)\n",k,p,xcenter,ycenter); while(x
{ p=p+2*x+1; delay(200); } else { y--; p=p+2*(x-y)+1; delay(200); } putpixel(xcenter+x,ycenter+y,3); putpixel(xcenter-x,ycenter+y,3); putpixel(xcenter+x,ycenter-y,3); putpixel(xcenter-x,ycenter-y,3); putpixel(xcenter+y,ycenter+x,3); putpixel(xcenter-y,ycenter+x,3); putpixel(xcenter+y,ycenter-x,3); putpixel(xcenter-y,ycenter-x,3); printf("%d\t%d\t(%d,%d)\n",k,p,x+xcenter,y+ycenter); } getch(); } OUTPUT:
RESULT:
Thus the program for midpoint circle algorithm is implemented and executed successfully.
Ex. No.4
MIDPOINT ELLIPSE ALGORITHM
AIM:
To write a C program for drawing an ellipse using midpoint ellipse algorithm. DESCRIPTION:
An ellipse can be given in terms of the distances from any point on the ellipse to two fixed positions called the foci of the ellipse. The sum of these two distances is the same values for all points on the ellipse.
The sum of the two distances d 1 and d 2, between the fixed positions F 1 and F 2 (called the foci of the ellipse) to any point P on the ellipse, is the same v alue, i.e. d 1 + d + d 2 = c onstant
The midpoint ellipse ellipse method is applied throughout throughout the first first quadrant in two parts and then obtain positions in the remaining 3 quadrants by symmetry. f ellipse (, x y )
= r y2 x 2 + r x2 y 2 − r x2 r y2
) is inside the ellipse x y (, x < 0 if (, f ellipse (, x y )0 =if (=, ) is o xn y tyhe ellipse > 0 if (, ) is outside the ellipse (, x y
In the x direction where the slope of the curve has a magnitude less than 1 and unit steps in the y direction where the slope has a magnitude greater greater than 1.
Starting at (0, r y) we take unit steps in the x direction until we reach the boundary between region 1 and region 2. Then we take unit steps in the y direction over the remainder of the curve in the first quadrant.
At the boundary dy dx
= −1 ⇒
2r y x = 2r x y 2
2
therefore, we move out of region 1 whenever 2r y x ≥ 2r x y 2
2
Region 1:(Choose (x i+1,yi ) or (x i+1,yi-1))
Region 2: (Choose (x i, yi-1) or (x i+1,y i-1)) Step in the negative y direction and midpoint is taken between horizontal pixels at each step.
ALGORI ALGORITHM THM :
Step Step 1: Input nput rx,ry and ellipse center (xc,yc) and obtain the first point on an ellipse centered on the origin as (x0,y0) = (0,ry) Step 2: Calculate Calculate the initial initial value of the the decision decision parameter parameter in region 1 as
Step 3: At each each xk position position in region1 starting at k=0 perform the following test. If P1 k <0, <0, the next point along the ellipse centered on (0,0) is(xk+1, yk ) and
Otherwise the next point along the ellipse is (xk +1, +1, yk -1) -1) and
And continue until 2ry2 x>=2rx2 y Step 4: Calculate last point Calculate the initial value of the decision parameter parameter in region 2 using 2 using the last (x0,y0) is the last position calculated in region 1.
Step Step 5: At each each posit positio ion n yk in regio region n 2, star startin ting g at k=0 k=0 perfor perform m the foll follow owing ing test, test, If p2k >0 >0 the next point along the ellipse centered on (0,0) is (xk ,y ,yk-1) and and
Otherwise the next point along the ellipse is (xk +1,y +1,yk -1) - 1) and and
Using the same incremental incremental calculations calculations for for x any y as in region 1. Step 6: Determine Determine symmetry points in the other other three three quadrants. quadrants. Step 7: Move each calculate calculate pixel position (x,y) onto the elliptical elliptical path centered centered on (xc,yc) and plot the coordinate values x=x+xc,y=y+yc 2 2 Step 8: Repeat the steps for region1 until 2ry x>=2rx y CODING: #include #include
#include #include #include int round(float m) { int n; if((m-0.5)>floor(m)) n=ceil(m); else n=floor(m); return n; } void ellipseplotpoints(int,int,int,int); ellipseplotpoints(int,int,int,int); void main() { int gdriver=DETECT,gmode; int xc,yc,rx,ry; int p,k=0,k1=0,x,y,px,py,rx1,ry1,rx2,ry2; initgraph(&gdriver,&gmode,"C:\\TC\\BGI"); printf("enter the radius\n"); scanf("%d%d",&rx,&ry); printf("enter the xcenter and ycenter\n"); scanf("%d%d",&xc,&yc); ry1=ry*ry; rx1=rx*rx; ry2=2*ry1; rx2=2*rx1; x=0; y=ry; ellipseplotpoints(xc,yc,x,y); p=round(ry1-rx1*ry+(0.25*rx1)); px=0; py=rx2*y; printf("\nregion1\n"); printf("\nk\tx,y\tp\tpx\tpy\n"); printf("\n%d\t(%d,%d)\t%d\t%d\t%d",k,x,y,p,px,py); while(px
px=px+ry2; if(p>=0) { y=y-1; py=pyrx2; p=p+ry1+px-py; } else p=p+ry1+px; ellipseplotpoints(xc,yc,x,y); printf("\n%d\t(%d,%d)\t%d\t%d\t%d",k,x,y,p,px,py); } printf("\nregion2\n"); printf("\nk1\tx,y\tp\tpx\tpy\n"); p=round(ry1*(x+0.5)*(x+0.5)+rx1*(y-1)*(y-1)-rx1*ry1); //p=(round(ry1*((x*x)+(2*x*0.5)+0.25))+(rx1*((y*y)-(2*y*1)+1))-(rx1*ry1)); //p=(round(ry1*((x*x)+(2*x*0.5)+0.25))+(rx1*((y*y)-(2*y*1)+1))-(rx1*ry 1)); printf("\n%d\t(%d,%d)\t%d\t%d\t%d",k1,x,y,p,px,py); while(y>0) { y=y-1; k1++; py=py-rx2; if(p<=0) { x=x+1; px=px+ry2; } if(p>0) p=p+rx1-py; else p=p+rx1-py+px; ellipseplotpoints(xc,yc,x,y); ellipseplotpoints(xc,yc,x,y); printf("\n%d\t(%d,%d)\t%d\t%d\t%d",k1,x,y,p,px,py); } getch(); closegraph(); } void ellipseplotpoints(int ellipseplotpoints(int xc,int yc,int x,int y) { putpixel(xc+x,yc+y,2);
putpixel(xc-x,yc+y,2); putpixel(xc+x,yc-y,2); putpixel(xc-x,yc-y,2); } OUTPUT:
RESULT:
Thus the program for midpoint ellipse algorithm is implemented and executed successfully.
Ex. No. 5
ATTRIBUTES OF OUTPUT PRIMITIVES
AIM:
To write a C program to set attributes to line, circle and ellipse. DESCRIPTION:
Output primitives have geometric and non-geometric attributes. A parameter that affects the way a primitive is to be displayed is referred to as an attribute parameter. Some attribute parameters, such as color and size, determine the fundamental characteristics of a primitive. The output primitives Such as Line, Circle and Ellipse are associated with set of attributes such as Line (color and Line Style), Circle (Color) and Ellipse (Color and Patterns). initgraph() initgraph()
Initialize Initialize the Graphics Graphics System
initgraph( initgraph()) is a graphics graphics system system control control function. function. It is used to initialize initialize the graphics graphics system. system. It should should be be the first first graphics graphics function function called. called. initgraph( initgraph()) loads loads the graphics graphics driver, driver, after allocating memory for it, then puts the system in graphics mode. 'gdriver' is set to DETECT (autodetect (autodetection), ion), it calls detectgraph() detectgraph() and automatically automatically selects the highest resolution graphics graphics mode for 'gmode'. 'gmode'.
'dpath' names the directory path where the graphic driver driver files files are located. Syntax:
initgraph(&gdriver,&gmode,"C:\\TC\\BGI"); closegraph():
It is used to close graphics mode. When you exit from graphics mode, you should restor restoree the syste system m to the previou previouss display display (text) (text) mode. mode. closeg closegraph raph() () functi function on restor restores es the previous display mode. If you do not use this function and still you exit from graphics mode, system gives some undesirable effects such as loss of cursor or off-sine characters. It is because system tries to write text in graphics mode. graphics mode. Syntax:
closegraph(); Shapes:
Computer graphics has many in-built commands, which can be used either to draw a shape and/or and/or for filling filling a color in any bounded shape. shape. lineto():
This command draws a line on screen from current cursor position to the (x,y) position mentioned in command. Syntax:
lineto(x,y); Where, (x,y) are co-ordinates of end point of line. line():
This command draws a line on screen. Syntax:
line(x1,y1,x2,y2); Where, (x1,y1) are co-ordinates of starting point of line and (x2,y2) are co- ordinates of end point of line. Example: line(10,10,100,100);
It will draw a line from point po int (10,10) to point (100,100). Output: It draws only a line not a box on screen.
circle(): This command draws a circle on screen. Syntax: circle(x,y,r);
(x, y) are co-ordinates of centre of circle
r is radius of circle. Example: circle(50,50,10); It draws a circle with centre (50,50) and an d radius 10. Output:
rectangle(): draws a rectangle on screen. Syntax: rectangle(x1,y1,x2,y2);
(x1,y1) are co-ordinates of top-left corner point of rectangle (x2,y2) are co-ordinates of bottom-right corner point of rectangle. Example: rectangle(10,10,100,100);
It will draw a rectangle as shown in following output. Output:
ellipse():
draws an ellipse on screen. Syntax:
void ellipse(int x, int y, y, int stangle, int endangle, endangle, int xradius, int yradius); yradius);
Argument Argument What What It Is
(x,y) ,y)
Center of ellipse
xradius
Horizontal axis
yradius
Vertical axis
stangle
Starting angle
endangle
Ending angle
The ellipse or sector travels from stangle to endangle. If stangle = 0 and endangle = 360, the call to ellipse draws a complete complete ellipse. Angle for ellipse, fillellipse, and sector (counter-clockwise) 90 degrees
180
0 degrees, 360 degrees 270 degrees
The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used. For full ellipse, the start and end should be 0 and 360 else it will draw an arc on screen. Example: ellipse(100,100,0,360,20,10) ellipse(100,100,0,360,20,10);; Output:
Example: ellipse(100,100,0,360,10 ellipse(100,100,0,360,10,20); ,20); Output:
fillellipse draws an ellipse, then fills the ellipse with the current fill color and fill pattern. Syntax: void far fillellipse(int x, int y,int xradius, int yradius); Sector draws and fills an elliptical pie slice in the current drawing color, then fills it using the pattern and color defined by setfillstyle or setfillpattern. Syntax:
void far sector(int x, int y, int stangle, stangle, int endangle,int xradius, int yradius); bar Syntax: void bar(int left, int top, int right, int bottom); Remarks:
bar draws a filled-in, rectangular, two-dimensional two-dimensional bar. The bar is filled using the current fill pattern and fill color. bar does not outline the bar. To draw an outlined two-dimensional bar, use bar3d with depth = 0. Parameter Parameter What What It Is
(left, (left, top)
the rectangle rectangle's 's upper left corner corner
(right,
the rectangle's lower right corner
bottom)
The coordinates are in pixels. setcolor():
draws any subsequent graphics in a color given given in command. Syntax: setcolor(color); color is either color constant or color name Example:
setcolor(RED); line(10,10,100,100); It will draw a line in red color. If it is, line(10,10,100,100); setcolor(RED);
It will not draw line in red color. setfillstyle(): decides the filling pattern and the filling color but it do not actually fill. Syntax: setfillstyle(pattern,color);
Pattern can be either pattern constant or patter name. These pattern constants are given in following table.Color is the color constant or color name. Pattern Constant 0 1 2 3 4 5 6 7 8 9 10 11
Pattern Name
EMPTY_FILL SOLID_FILL LINE_FILL LTSLASH_FILL SLASH_FILL BKSLASH_FILL LTBKSLASH_FILL HATCH_FILL XHATCH_FILL INTELEAVE_FILL WIDE_DOT_FILL CLOSE_DOT_FILL
setlinestyle(): specifies the thickness of the line to be b e drawn. These styles are not used us ed for the circles. Syntax:
setlinestyle(linestyle,user_defined_style,line_width); Con Constant 0 1 2 3 4
Line Line SOLID_LINE DOTTED_LINE CENTRE_LINE DASHED_LINE USERBIT_LINE
User_defined_style is user defined style style and if ignored set to zero. Line_width is tickness of line as given below 0 -NORM_WIDTH 3- THICK_WIDTH Example: setlinestyle(2,0,3);
getbkcolor
returns the current background color. Syntax:
int getbkcolor(void); getbkcolor(void); setbkcolor
setbkcolor sets the background to the color specified specified by color. Syntax:
setbkcolor(color setbkcolor(color name); floodfill floodfill fills an enclosed area on bitmap devices. The area bounded by the color border is flooded with the current fill pattern and fill color. Syntax: void far floodfill(int x, int y, int border); (x,y) is a "seed point". o If the seed is within an enclosed area, the inside will be filled. filled. o If the seed is outside the enclosed area, area, the exterior will be filled. filled. Use fillpoly instead of floodfill whenever possible so you can maintain code compatibility with future versions. textheight textheight takes the current font size and multiplication factor, and determines the height of textstring textstring in pixels. Syntax:
int far textheight(char tex theight(char far *textstring); textwidth
textwid textwidth th takes takes the stri string length length,, curre current nt font font size, size, and multi multipli plicat catio ion n factor factor,, and determines the width of textstring in pixels
Syntax:
int far textwidth(char far *textstring); *textstring); settextstyle settextstyle sets the text font, the direction in which text is displayed, and the size of the characters. Syntax:
void far settextstyle(int font, int direction, int charsize);
A call to settextstyle affects affects all text output by outtext and outtextxy. Enum: Names Names for for BGI fonts Name Value Meaning 0 DEFAULT_FONT 8x8 bit-mapped font 1 TRIPLEX_FONT Stroked triplex font SMALL_FONT
2
Stroked small font
SANS_SERIF_FONT
3
Stroked sans-serif font
GOTHIC_FONT
4
Stroked gothic font
Direction
Font directions supported are are horizontal text (left to right) and vertical text (rotated 90 degrees counterclockwise) count erclockwise).. The default direction is HORIZ_DIR. Name ame : Valu alue : Direc rection tion HORIZ_DI HORIZ_DIR R 0 : Left Left to right right VERT VERT_D _DIIR 1 : Bott Bottom om to top top CODING: #include
#include #include void main() { int a,b,c,d,e,f,i=10; int gdriver=DETECT, gmode; initgraph(&gdriver,&gmode,"E:\\TC\\BGI"); do { printf("1.line\n2.circle\n3.sector\n4.ellipse\n5.exit\n"); printf("enter choice\n"); scanf("%d",&a); setbkcolor(LIGHTRED); switch(a) { case 1:
setcolor(GREEN); printf("line\n"); printf("0.SOLID_LINE\n1.DOTTED_LINE\n2.DASHED_LINE\n"); printf("enter choice\n"); scanf("%d",&b); setlinestyle(b,0,3); line(200,200,100,100); break; case 2: setcolor(RED); printf("circle\n"); circle(100,100,50); break; case 3: setcolor(BLUE); printf("sector\n"); printf("1.LIGHTGREEN\n2.LIGHTRED\n3.YELLOW\n"); printf("0.EMPTY_FILL\n1.SOLID_FILL\n2.LINE_FILL\n3.LTSLASH_FILL\n4.HATCH_FIL L\n5.BKSLASH_FILL\n6.LTBSLASH_FILL\n7.HATCH_FILL\n8.XHATCH_FILL\n9.INTER LEAVE_FILL\n10.WIDE_DOT_FILL\n11.CLOSE_FILL\n12.USER_FILL\n"); printf("enter choice\n"); scanf("%d",&c); scanf("%d",&f); setfillstyle(c,f); sector(300,300,0,360,50,30); break; case 4: setcolor(GREEN); printf("ellipse\n"); printf("enter choice\n"); scanf("%d",&d);
scanf("%d",&e); ellipse(300,300,0,360,50,30); settextstyle(d,e,25); outtext("ellipse"); break; case 5: exit(); break; } }while(i<=10); closegraph(); getch(); } OUTPUT:
RESULT:
Thus the program for attributes of output primitive is implemented and executed successfully.
Ex. No.6
IMPLEM LEMENT ENTATION ION OF 2D TRAN RANSFO SFORMA RMATIO TION
AIM:
To write a C-Program to perform various 2D-Transformations including Translations, Scaling, Rotations, Reflection, Shear. DESCRIPTION:
Changes in orientations, size and shape are accomplished with geometric transformations that alter alter the coordinate coordinate description description of objects. objects. Basic transformation:
Translation
Rotation
Scaling
Other transformation:
Ref lecti lection
Shear
Translation:
A translation moves all points in an object along the same straight-line path to new positi positions ons.To .To transl translate ate a 2D positi position, on, we add transl translati ation on distan distances ces t x and t y to the origi original nal y’ ).The coordinates ( x,y) to obtain the new coordinate position ( x’, y ).The path is represented by a vector,
called the translation or shift vector. x x’ = x
+ t x , y’ = y y + t y t x x′ x x t x = + y ′ y y y t y P′ = P + T
Rotation: A rotation repositions all points in an object along a circular path in the plane centered at the pivot point.
The original coordinates are: x′ = r cos(ϕ +sϑ c=osr r cos(ϕ )co )co
ϕsin ϑsi−nr
ϕ
ϑ
y′ = r sin(ϕ +sϑ s=inr sin(ϕ )co )co
ϕsin ϑc+ os osr
ϕ
ϑ
x = r cos(ϕ cos(ϕ ) y = r sin(ϕ sin(ϕ )
Substituting x′ = x cosϑ cos ϑ − y sin ϑ y ′ = x sin ϑ + y cosϑ cos ϑ
Matrix form x′ cosϑ cos ϑ − sin ϑ xx x y ′ = sin ϑ cosϑ y cos ϑ y P′ = R ⋅ P
Scaling
Altering the size of an object. S x x and S y are the scaling f act actors.
Values less than 1 reduce the size of the objects
Values greater than 1 produce an enlarged object.
Uniform Uniform scaling scaling it is necessa necessary ry to assign assign same same value for sx and sy. sy.
Unequal values for Sx and S y result in a non uniform scaling. scaling. x′ = xS x
Matrix form
y ′ = yS y
x ′ S x y ′ = 0 y
x
x x S y y y 0
P ′ = S ⋅ P
Scaling relative to fixed point ( x f , y f ) x′ = x f
+ () x − x f S x y ′ = y f + () y y − y f S y
Reflection: A reflection is a transformation that produces a mirror image of an object. Th e mirror
image for a two-dimensional reflection is generated relative to an axis of reflection by rotating the object 180 o about the reflection axis. Reflection about x axis: x′ 1 0 x y′ = 0 −1 1 0 0
x 0 x
y 1 1
0
Reflection about y axis:
x′ −1 x y ′ = 0 1 0
0
0 xx
1
0
y
0 1 1
Relative to the coordinate origin
x′ −1 0 x y′ = 0 −1 1 0 0
With respect to the line y line y = x
0 x x
y 1 1
0
x′ 0 x y′ = 1 1 0
1
x 0 x
0
0 y
0
1 1
Shear:
A transformation that distorts the shape of an object such that the transformed shape appears as if the object were composed of internal layers that had been caused to slide over each other is called a shear. Two common shearing transformations are those that shift coordinate x values and those that shift y values. x-direction x-direction shear x′ = x + sh x ⋅ y y′ = y
Matrix form x′ 1 x y′ = 0 1 0
sh x
1 0
0 xx
y 1 1 0
x-direction x-direction relative to other reference line x′ = x + sh x () y y − y ref y′ = y
Matrix form x′ 1 x y′ = 0 1 0
sh x
1 0
− sh x ⋅ yref x x y 0 1 1
y-direction y-direction shear x′ = x y′ = y + sh y ⋅ x
Matrix form x′ 1 x y ′ = sh y 1 0
0 0 xx 1 0
y 1 1 0
y-direction y-direction relative to other reference line x′ = x
Matrix form
y ′ = y + sh y () x − xref x′ 1 x y ′ = sh x 1 0
0 1 0
xx − sh y ⋅ xref y 1 1 0
ALGORI ALGORITHM THM : Step 1 : Start the program. Step 2 : Get the choice from the user about the transformation to the performed after Including necessary header files and Initializing necessary variables with initgraph() initgraph() function. Step 3 : In case of translation get the translation factors and add then with the old coordinates of the triangle and Draw the triangle n ow with the new coordinates. Step 4 : In case of scaling get the the scaling factors and multiply them with the old coordinates and draw the triangle with new coordinates. Step 5 : For Rotation get the rotation angle angle and the fixed point is obtained from the user and add the calculated values to the old coordinates and draw the triangle with new coordinates. Step 6 : For shearing get get the shearing constants and reference About x and y axis, (i) For shearing about x axis keep x coordinate as it in and after and change y coordinate. (ii) For shearing about y axis keep y coordinate as it in and after x axis coordinate. Draw the triangle with new calculated coordinates. Step 7 : Stop the program. CODING: #include #include #include #include #define COL 2 int a[]={245,45,260,60,220,60}; int ROUND(float a) { return (int)(a>0)?a+.5:a-.5; } void draw(int *temp)
{ line(temp[0],temp[1],temp[2],temp[3]); line(temp[0],temp[1],temp[4],temp[5]); line(temp[2],temp[3],temp[4],temp[5]); } void translate(int tx,int ty) t y) { int temp[6],i; for(i=0;i<6;i++) { temp[i]=a[i]+tx; i++; temp[i]=a[i]+ty; } draw(temp); } void scale(int sx,int sy) { int temp[6],i; for(i=0;i<6;i++) { temp[i]=a[i]*sx; i++; temp[i]=a[i]*sy; } draw(temp); } void rotate(int tde) { int i,temp[6]; float t,cx,cy; cx=(a[0]+a[2]+a[4]/3); cy=(a[1]+a[3]+a[5]/3); t=tde*M_PI/180; for(i=0;i<6;i++) { temp[i]=ROUND((a[i]-cx)*cos(t)-(a[i+1]-cy)*sin(t)+cx); temp[i+1]=ROUND((a[i]-cx)*sin(t)+(a[i+1]-cy)*cos(t)+cy); } draw(temp);
setcolor(0); line(a[0],a[1],a[2],a[3]); line(a[0],a[1],a[4],a[5]); line(a[2],a[3],a[4],a[5]); setcolor(3); } void reflect() { int i,temp[6],tde=45; float t,cx,xy; for(i=0;i<6;i++) { temp[i]=a[i+1]; temp[i+1]=a[i]; } draw(temp); getch(); setcolor(0); line(temp[0],temp[1],temp[2],temp[3]); line(temp[0],temp[1],temp[4],temp[5]); line(temp[2],temp[3],temp[4],temp[5]); setcolor(3); t=tde*M_PI/180; for(i=0;i<6;i+=2) { temp[i]=ROUND((a[i]*cos(t))-(a[i+1]*sin(t))); temp[i+1]=ROUND((a[i]*sin(t))+(a[i+1]*cos(t))); } setcolor(4); line(temp[0],temp[1],temp[2],temp[3]); line(temp[0],temp[1],temp[4],temp[5]); line(temp[2],temp[3],temp[4],temp[5]); } void shear() { int sh,i,temp[6]; printf("enter the shear value"); scanf("%d",&sh); for(i=0;i<6;i+=2) {
temp[i]=(a[i]+(sh*a[i+1])); temp[i+1]=a[i+1]; } draw(temp); } void main() { int x,y,gd=DETECT,gm,phi,d; clrscr(); initgraph(&gd,&gm,"C:\\TC\\BGI"); setcolor(COL); printf("initial primitive"); draw(a); printf("translation \n \n enter tx and ty"); scanf("%d%d",&x,&y); translate(x,y); printf("scaling \n enter sx and sy"); scanf("%d%d",&x,&y); scale(x,y); printf("rotation \n \n enter rotation r otation angle(in degree):"); scanf("%d",&phi); rotate(phi); printf("reflection about line x=y"); x= y"); reflect(); printf("sheared image"); shear(); getch(); closegraph(); } OUTPUT:
Ex. No.7 No.7
IMPL IMPLEME EMENT NTAT ATIO ION N OF 2D COMPOS COMPOSITE ITE TRAN TRANSF SFORM ORMAT ATION ION
AIM:
To write a C-Program C -Program to perform various 2D composite transformations. Algorithm
Step 1 : Start the program Step 2 : Include all header files and Initialize the variables that are necessary for the execution of the program. Step 3 : To perform Translation, get get coordinates of line and translate it, again translate the translated line. Step 4 : To perform scaling, scaling, get the scaling factor factor and change the lines length, again scale the changed one to the Original position. Step 5 : To perform rotation, rotation, get the angle and rotate the line, again get the angle and rotate the already rotated line. Step 6 : To perform perform the general fixed fixed point scaling, scaling, first first translate the line, scale it and perform reverse translation. Step 7 : Stop the program. CODING: #include #include #include #include void translate(); void scale(); void rotate(); void main() { int ch; int gd=DETECT,gm; initgraph(&gd,&gm,"d:\\tc\\bgi"); setcolor(6); outtextxy(100,88,"object"); rectangle(100,150,150,100);
printf("MENU"); printf("\n1.translation\n2.scale\n3.rotate"); printf("\ printf("\nenter nenter choice"); choice"); scanf("%d",&ch); cleardevice(); switch(ch) { case 1: translate(); break; case 2: scale(); break; case 3: rotate(); break; default:printf("you have entered the wrong choice"); break; } getch(); closegraph(); } void translate() { int tx,ty,tx1,ty1,tx2,ty2; setcolor(2); outtextxy(240,10,"TRANSLATION"); outtextxy(238,20,"--------"); printf("\nenter tx and ty for translation1"); scanf("%d%d",&tx1,&ty1); printf("\nenter tx and ty for translation2"); scanf("%d%d",&tx2,&ty2); tx=tx1+tx2;ty=ty1+ty2; cleardevice(); rectangle(100,150,150,100); rectangle(100+tx1,150+ty1,150+tx1,100+ty1); printf("\n after translation"); rectangle(100+tx,150+ty,150+tx,100+ty); } void scale()
{ int sx,sy,sx1,sy1,sx2,sy2; setcolor(2); outtextxy(240,10,"SCALING"); outtextxy(238,20,"--------"); printf("\nenter sx and sy for scaling1"); scaling1"); scanf("%d%d",&sx1,&sy1); printf("\nenter sx and sy for scaling2"); scaling2"); scanf("%d%d",&sx2,&sy2); sx=sx1+sx2;sy=sy1+sy2; cleardevice(); rectangle(100,150,150,100); rectangle(100*sx1,150*sy1,150*sx1,100*sy1); printf("\n after scaling"); rectangle(100*sx,150*sy,150*sx,100*sy); } void rotate() { float theta,theta1,theta2; int x1,x2,x3,x4; int y1,y2,y3,y4; int ax1,ax2,ax3,a ax1,ax2,ax3,ax4; x4; int ay1,ay2,ay3,ay4; int refx,refy; printf("\ printf("\nenter nenter the 1st angle"); angle"); scanf("%f",&theta1); printf("\ printf("\nenter nenter the 2nd angle"); angle"); scanf("%f",&theta2); theta=theta1+theta2; theta=theta*(3.14/180); cleardevice(); setcolor(2); outtextxy(240,10,"ROTATE"); outtextxy(238,20,"--------"); refx=100;refy=100; x1=100;y1=100; x2=150;y2=100; x3=150;y3=150; x4=100;y4=150; ax1=refy+(x1-refx)*cos(theta1)-(y1-refy)*sin(theta1);
ay1=refy+(x1-refx)*sin(theta1)+(y1-refy)*cos(theta1); ax2=refy+(x2-refx)*cos(theta1)-(y2-refy)*sin(theta1); ay2=refy+(x2-refx)*sin(theta1)+(y2-refy)*cos(theta1); ax3=refy+(x3-refx)*cos(theta1)-(y3-refy)*sin(theta1); ay3=refy+(x3-refx)*sin(theta1)+(y3-refy)*cos(theta1); ax4=refy+(x4-refx)*cos(theta1)-(y4-refy)*sin(theta1); ay4=refy+(x4-refx)*sin(theta1)+(y4-refy)*cos(theta1); rectangle(100,150,150,100); line(ax1,ay1,ax2,ay2); line(ax2,ay2,ax3,ay3); line(ax3,ay3,ax4,ay4); line(ax4,ay4,ax1,ay1); ax1=refy+(x1-refx)*cos(theta)-(y1-refy)*sin(theta); ay1=refy+(x1-refx)*sin(theta)+(y1-refy)*cos(theta); ax2=refy+(x2-refx)*cos(theta)-(y2-refy)*sin(theta); ay2=refy+(x2-refx)*sin(theta)+(y2-refy)*cos(theta); ax3=refy+(x3-refx)*cos(theta)-(y3-refy)*sin(theta); ay3=refy+(x3-refx)*sin(theta)+(y3-refy)*cos(theta); ax4=refy+(x4-refx)*cos(theta)-(y4-refy)*sin(theta); ay4=refy+(x4-refx)*sin(theta)+(y4-refy)*cos(theta); line(ax1,ay1,ax2,ay2); line(ax2,ay2,ax3,ay3); line(ax3,ay3,ax4,ay4); line(ax4,ay4,ax1,ay1); } OUTPUT:
SCALING:
ROTATION:
RESULT:
Thus the program for 2D composite transformation is implemented and executed successfully.
Ex. No. 8
IMPLEMENTATION IMPLEMENTATION OF CLIPPING A LINE USING COHEN SUTHERLAND SUTHERLAND LINE CLIPPING ALGORITHM
AIM:
To write a C-program to perform line clipping using using Cohen Sutherland line clippin cl ipping g algorithm. DESCRIPTION:
Any procedure that identifies those portion of a picture that are either inside or outside of a specified region of space is referred as Clipping Algorithm Algorithm or Clipping. The region against which an object is to clipped is called a clip window. Cohen Sutherland line clipping algorithm algorithm is one of the oldest and most popular line-
clipping procedures. The method speeds up the processing of line segments by performing initial tests that reduce the number of intersections that must be calculated. It quickly detects and dispenses with two common and trivial cases. To clip a line, we need to consider only its endpoints. If both endpoints of a line lie inside the window, the entire line lies inside the window. It is trivially accepted and needs no clipping. On the other hand, if both endpoints of a line lie entirely to one side of the window, the line must lie entirely outside of the window. It is trivially rejected and needs to be neither clipped nor displayed.
Every line endpoint in a picture is assigned a four digit binary code called a region code that identifies identifies the location of the point relative relative to the boundaries of the the clipping clipping rectangle. rectangle.
ALGORITHM: 1. Assign a region code for each endpoints. endpoints. 2. If both endpoints have a region code 0000 --- trivially trivially accept these these line. 3. Else, perform perform the logical AND operation for both region codes. 3.1 if the result is not 0000 - trivially trivially reject reject the line. 3.2 else – else – (result (result = 0000, need clipping) 3.2.1. Choose an endpoint of the line that is outside the window. 3.2.2. Find the intersection point at the window boundary (base on regioncode). regioncode). To find intersection point, use line equation intersection with LEFT or RIGHT boundary. x = xwmin xwmin (LEF (LEFT) T)
x = xwmax xwmax (RIGHT)
x1) y = y1 + m(x – x1)
intersection with BOTTOM or TOP boundary. y = ywmin wmin (BOTT (BOTTOM OM))
y = ywmax wmax (TOP)
x = x1 + (y – (y – y1)/m y1)/m
3.2.3. Replace endpoint with the intersection point and update the region code. 3.2.4. Repeat step 2 until we find a clipped line either trivially accepted or trivially rejected. 4. Repeat step 1 for other oth er lines.
CODING: #include #include #include #include #include typedef unsigned intoutcode; enum {top=0x8,bottom=0x4,right=0x2,left=0x1}; void cohen(double,double,double,double,double,double,double,double); outcodecompoutcode(double,double,double,double,double,double); int main(void) {intgd=DETECT,gm; int x6,y6,x7,y7,x0,y0,x1,y1,xmax,ymax,xmin,ymin,x2,y2,x3,y3,x4,y4,x5,y5; initgraph(&gd,&gm,"C:\\TC\\BGI"); printf("enter the rectangle coordinates"); scanf("%d%d%d%d",&xmin,&ymin,&xmax,&ymax); printf("enter the 1st line coordinates"); scanf("%d%d%d%d",&x0,&y0,&x1,&y1); printf("enter the 2nd line coordinates"); scanf("%d%d%d%d",&x2,&y2,&x3,&y3); printf("enter the 3rd line coordinates"); scanf("%d%d%d%d",&x4,&y4,&x5,&y5); printf("enter the 4th line coordinates"); scanf("%d%d%d%d",&x6,&y6,&x7,&y7); getch();
setlinestyle(0,1,3); setcolor(1); rectangle(xmin,ymin,xmax,ymax); setcolor(2); line(x0,y0,x1,y1); setcolor(3); line(x2,y2,x3,y3); setcolor(4); line(x4,y4,x5,y5); setcolor(5); line(x6,y6,x7,y7); getch(); cleardevice(); printf("\n after clipping"); setcolor(6); cohen(x0,y0,x1,y1,xmin,ymin,xmax,ymax); setcolor(7); cohen(x2,y2,x3,y3,xmin,ymin,xmax,ymax); setcolor(8); cohen(x4,y4,x5,y5,xmin,ymin,xmax,ymax); setcolor(9); cohen(x6,y6,x7,y7,xmin,ymin,xmax,ymax); getch(); closegraph(); return 0;} voidcohen(double x0,double y0,double x1,double y1,double xmin,doubleymin,doubleymax)
{doublex,y; outcode outcode0,outcode1,outcodeout; int accept=0,done=0; outcode0=compoutcode(x0,y0,xmin,ymin,xmax,ymax); outcode1=compoutcode(x1,y1,xmin,ymin,xmax,ymax); do {if(!(outcode0|outcode1)) {accept=1; done=1;} else if(outcode0&outcode1) done=1; else {outcodeout=outcode0?outcode0:outcode1; if(outcodeout&top) {x=x0+(x1-x0)*(ymax-y0)/(y1-y0); y=ymax;} else if(outcodeout&bottom) {x=x0+(x1-x0)*(ymin-y0)/(y1-y0); y=ymin;} else if(outcodeout&right) {y=y0+(y1-y0)*(xmax-x0)/(x1-x0); x=xmax;} else {y=y0+(y1-y0)*(xmin-x0)/(x1-x0); x=xmin;} if(outcodeout==outcode0)
{x0=x; y0=y; outcode0=compoutcode(x0,y0,xmin,ymin,xmax,ymax); } else {x1=x; y1=y; outcode1=compoutcode(x1,y1,xmin,ymin,xmax,ymax); }}}while(done==0); if(accept) {rectangle(xmin,ymin,xmax,ymax); line(x0,y0,x1,y1); }} outcodecompoutcode(double x,doubley,doublexmin,doubleymin,doublexmax,doubleymax) { outcode code=0; if(y>ymax) code|=top; else if(yxmax) code|=right; if(x
OUTPUT:
RESULT:
Thus the program for Cohen Sutherland line clipping algorithm is implemented and executed successfully.
Ex. No. 9
IMPLEMENTATI IMPLEMENTATION ON OF CLIPPING A POLYGON USING SUTHERLAND SUTHERLAND HODGEMAN HODGEMAN POLYGON CLIPPING ALGORITHM
AIM:
To write a C-program to perform polygon clipping using Sutherland Hodgeman pol ygon clipping algorithm. DESCRIPTION:
The Sutherland Hodgeman Polygon Clipping Algorithm works by extending each line of the convex the convex clip clip polygon in turn and selecting only vertices from the subject polygon that is on the visible side. It accepts an ordered sequence of vertices v1, v2, v3... vn and puts out a set of vertices defining the clipped polygon. pol ygon.
•
Clip Clip the polygon polygon by process processing ing the polygon polygon boundary boundary as a whole whole against against each each window.
•
Process all polygon polygon vertices against each clip rectangle boundary in turn.
•
First First clip the polygon polygon against against the left boundary boundary to produce produce a new sequence sequence of vertices.
•
The new sequence sequence of vertices is then successive successive passed passed to right, bottom bottom and top boundary clipper. clipper.
•
At each step a new sequence sequence of output output vertices vertices is generated generated and passed passed to the next boundary clipper clipper
Rule for each edge for each clipper:
Input each edge (vertex pair) successively. Output is a new list of vertices.
Each edge goes through 4 clippers.
•
If first input vertex vertex is outside, and second is inside, inside, output the intersection intersection and the second vertex
•
If both input vertices are inside, then just output second vertex
•
If first first input vertex is inside, and second is outside, outside, output is the intersection intersection
•
If both vertices are outside, output is nothing.
•
The last vertex in the list is always added to the first vertex vertex
CODING:
#include #include #include #define round(a)((int)(a+0.5)) int k; float xmin,xmax,ymin,ymax,arr[20],m; void clipl(float x1,float y1,float x2,float y2) { if(x2-x1) m=(y2-y1)/(x2-x1); else m=100000; if(x1>=xmin&&x2>=xmin) { arr[k]=x2; arr[k+1]=y2; k+=2; } if(x1=xmin) { arr[k]=xmin;
arr[k+1]=y1+m*(xmin-x1); arr[k+2]=x2; arr[k+3]=y2; k+=4; } if(x1>=xmin&&x2ymax&&y2<=ymax) { arr[k]=x1+m*(ymax-y1); arr[k+1]=ymax; arr[k+2]=x2; arr[k+3]=y2; k+=4; } if(y1<=ymax&&y2>ymax) { arr[k]=x1+m*(ymax-y1); arr[k+1]=ymax; k+=2; }} void clipr(float x1,float y1,float x2,float y2) { if(x2-x1) m=(y2-y1)/(x2-x1); else m=100000;
if(x1<=xmax&&x2<=xmax) { arr[k]=x2; arr[k+1]=y2; k+=2; } if(x1>xmax&&x2<=xmax) { arr[k]=xmax; arr[k+1]=y1+m*(xmax-x1); arr[k+2]=x2; arr[k+3]=y2; k+=4; } if(x1<=xmax&&x2>xmax) { arr[k]=xmax; arr[k+1]=y1+m*(xmax-x1); k+=2; }} void clipb(float x1,float y1,float x2,float y2) { if(y2-y1) m=(x2-x1)/(y2-y1); else m=100000; if(y1>=ymin&&y2>=ymin) { arr[k]=x2; arr[k+1]=y2; k+=2; } if(y1=ymin) { arr[k]=x1+m*(ymin-y1); arr[k+1]=ymin; arr[k+2]=x2; arr[k+3]=y2; k+=4; } if(y1>=ymin&&y2
}} void main() { int i,n,p[20],gd=DETECT,gm; float xi,yi,xf,yf,py[20]; initgraph(&gd,&gm,"C:\\TC\\BGI"); clrscr(); printf("\nenter the coords of rectangular clip window\n xmin,ymin"); xmin,ymin"); scanf("%f%f",&xmin,&ymin); printf("\nxmax,ymax"); scanf("%f%f",&xmax,&ymax); printf("\npolygon to be clipped\n no of sides:"); scanf("%d",&n); printf("\ printf("\nenter nenter coords"); coords"); for(i=0;i<2*n;i++) scanf("%f",&py[i]); py[i]=py[0]; py[i+1]=py[1]; for(i=0;i<2*n;i++) p[i]=round(py[i]); setcolor(14); rectangle(xmin,ymax,xmax,ymin); printf("\nunclipped polygon"); setcolor(13); fillpoly(n,p); getch(); cleardevice(); k=0; for(i=0;i<2*n;i+=2) clipl(py[i],py[i+1],py[i+2],py[i+3]); n=k/2; for(i=0;i
clipr(py[i],py[i+1],py[i+2],py[i+3]); n=k/2; for(i=0;i
OUTPUT:
RESULT:
Thus the program for Sutherland Hodgemen Polygon clipping algorithm is implemented and executed successfully.
Ex. No.10
BASIC OPENGL PROGRAMS
DESCRIPTION:
OpenGL is a software interface that allows you to access the graphics hardware without taking care of the hardware details or which graphics adapter is in the system. It is device Independent Graphics Programm Programming ing language language and application programming interface. ADVANTAGE ADVANTAGE OF OPENGL OPENGL
Cross platform (Windows, Linux, Linux, Mac, even some handheld devices). devices).
Fast
Portable
Easy to use use
Well-documented
OPENGL LIBRARIES
•
Basic GL- Fundamental Fundamental Library Starts With – With – “gl”
•
GLUT- Graphics Library Utility Toolkit
Opening Windows
Developing Developing and managing managing Menus
Managing Events
• GLU- Utility Library
Matrix Operation
Drawing Primitives
GLUI- User Interface L Interface Library
Works along GLUT
controls such as buttons, checkboxes, radio buttons.
DYNAMICALLY-LINKED LIBRARIES
opengl32.dll
glu32.dll
glut32.dll
LIBRARIES
opengl32.lib
glu32.lib
glut32.lib
INCLUDE FILES
gl.h
glu.h
glut.h
OPENING OPENING A WINDOW WINDOW FOR DRAWING
The First task in making pictures is to open a screen window for drawing. The following initialize and display display the screen window in the the program. 1. glutInit glutInit(&a (&argc rgc,, argv) argv)
It should be called before any other GLUT routine because it initializes the GLUT library. 2. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
Specify Specify the display display mode for for a window. window. 3. glutInitWindowSiz glutInitWindowSize(640, e(640,480) 480)
To specify the size, in pixels, of our inital window. The arguments indicate the height and width (in pixels) of the requested window. 4. glutInitWindowPo glutInitWindowPosition(10 sition(100,15) 0,15)
To specify the screen location for the upper- left corner of our initial window. This function positioned the screen 100 pixels over from the left edge and 150 pixels down down from from the top. top. 5. glutCreateWindow glutCreateWindow(“Example”)
The command takes a string as a parameter which may appear in the title bar. 6. glutMai glutMainLoop( nLoop())
The window is not actually displayed until the glutMainLoop() is entered. EVENT DRIVEN PROGRAMMING
The method of associating a call back function with a particular type of event is called as event driven programming. OpenGL provides tools to assist with the event management.
There are four Glut functions available 1. glutDisplayFunc(m glutDisplayFunc(mydisplay) ydisplay)
Redraws screen when window opened or another window moved off it. 2. glutReshapeFunc(myr glutReshapeFunc(myreshape) eshape)
Reports Reports new window width width and height for reshaped reshaped window. (Moving (Moving a window does not produce a reshape event. 3. glutKeyboardFu glutKeyboardFunc(mykeyboar nc(mykeyboard) d)
To run the callback function specified and pass as parameters, the ASCII code of the pressed key, and the x and y coordinates of the mouse cursor at the time of the event. 4. glutMouseFunc(mymouse) glutMouseFunc(mymouse)
GLUT supports interaction with the computer mouse that is triggered when one of the three typical typical buttons is presses. presses. A mouse callback callback function function can be initiated initiated when a given mouse button is pressed or released. The command glutMouseFunc() is used to spec specify ify the the call callba back ck func functi tion on to use use when when a spec specif ifie ied d butt button on is a given iven stat statee at a certain certain location location.. OPENGL SYNTAX void glBegin(GLenum mode)
glvertex2i(arguments); glvertex2i(arguments); void glEnd(void)
FORMAT OF glVertex glVertex COMMAND COMMAND
EXAMPLE:
//the following followin g code plots three dots glBegin(GL_POINTS); glVertex2i(100, 50); glEnd( );
OPENGL DATATYPES
OPEN GL-SETUP PROCEDURE:
Before executing the programs you have to place three header files (dll, Header, Lib) in the following following locations locations Header: C:\Program Files\Microsoft Visual Studio\VC98\Include\GL Lib: C:\Program Files\Microsoft Visual Studio\VC98\Lib Dll: C:\WINDOWS\system32
Go to to Start StartPrograms Microsoft Visual Studio 6.0 Microsoft Visual C++ 6.0 FileNew...
New dialog boxes opens in that select the win32console application from the projects tab tab and give the name for the project and click on the ok and finish button.
Now select Tools menu and select options from it.
In that select the directories directories tab and select the browse button as given given in the below screenshot.
Select the path for the three header files that you have pasted in different locations and click on the ok button.
FileNew...
Select the C++ source file file from the files tab and give the name for the file and click ok button .
Now select project menu and select select the settings from from the drop down menu.
In the project settings settings dialog box click on the link tab and type the three file file names at the end of the object/library modules text box. File names: opengl32.lib glu32.lib glut32.lib
And then click on the General tab and select Not Using MFC MFC in Microsoft Foundation Classes option
Then click on the C/C++ tab and select C++ Language from the category drop down list and click on the ok button
After performing these steps type type the required program program code save the program and click click on the build button.
Then click on the Execute program button
CODING: Drawing a Teapot
h” #include “ #include “glut. glut.h” void display(); void reshape(GLsizei, GLsizei); void main(intargc, char** argv){ glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutCreateWindow("sample"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLoop(); } void display(){ glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glColor3f( glColor3f(1.0f, 1.0f, 1.0f, 1.0f); glutSolidTeapot(1.0);
glFlush(); }void reshape(GLsizei w, GLsizei h){ glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-0.5, 0.5, -0.5, 0.5, 1.0, 20.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); } OUTPUT
Drawing Sample
#include “ #include “g glut.h” void display(); void reshape(GLsizei w, GLsizei h); void main(intargc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(250, 250); glutInitWindowPosition(100, 100); glutCreateWindow("Drawing sample"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutMainLoop(); } void reshape(GLsizei w, GLsizei h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity();
glOrtho(-2.0f, 2.0f, -2.0f, 2.0f, -2.0f, 2.0f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void display() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glBegin(GL_POLYGON); glColor3d( glColor3d(1.0f, 1.0f, 1.0f, 1.0f); glVertex3f( glVertex3f(-1.0f -1.0f,, -1.0f, 0.0f); glColor3d( glColor3d(1.0f, 1.0f, 0.0f, 0.0f); glVertex3f(1.0f, -1.0f, 0.0f); glColor3d( glColor3d(0.0f, 0.0f, 1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glColor3d( glColor3d(0.0f, 0.0f, 0.0f, 1.0f); glVertex3f( glVertex3f(-1.0f -1.0f,, 1.0f, 0.0f); glEnd(); glFlush(); } OUTPUT:
RESULT:
Thus the program for drawing a teapot is implemented and executed successfully.
Ex.. No. Ex No. 11
IMPL IMPLEM EMEN ENTA TATI TION ON OF 3D OBJE OBJECT CTS S USIN USING G OPEN OPENGL GL
AIM :
To write a program using OPENGL for displaying a three dimensional objects. DESCRIPTION:
OpenGL has separate separate transformation transformation matrices matrices for different different graphics graphics features glMatrixMode(GLenum mode)
in scene • GLMODELVIEW - for manipulating model in • GL_PROJECTION - perspective perspective orientation orientation • GL_TEXTURE - texture map orientation glLoadIdentity()
Loads a 4-by-4 identity matrix into the current matrix glPushMatrix()
Push current matrix stack glPopMatrix()
Pop the current matrix stack glMultMatrix glMultMatrix () Multiply the current matrix with the specified matrix glViewport()
Set the viewport Example Example : glViewport(0, 0, width, height); gluPerspective()
Sets up a perspectiv perspectivee projection projection matrix. matrix. Syntax : gluPerspective(angle, asratio, ZMIN, ZMAX); Example Example : gluPerspective(60.0, width/height, width/height, 0.1, 100.0); gluLookAt()
view volume that is centered centered on a specified eyepoint eyepoint Example Example : gluLookAt(3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 ); glutSwapBuffers () :
glutSwapBuffers swaps the buffers of the current window window if double buffered. OPENGL OPENGL FUNCTIONS FOR FOR DRAWING 3D OBJECTS
• • • • • • • • • •
glutWireCube(doubl glutWireCube(doublee size); glutSolidCub glutSolidCube(double e(double size); glutWireSphe glutWireSphere(double re(double radius, int slices, slices, int int stacks); stacks); glutSolidSph glutSolidSphere(do ere(double uble radius, int slices, slices, int stacks); stacks); glutWireCone(d glutWireCone(double ouble radius, double double height, height, int slices, slices, int stacks); stacks); glutSolidCon glutSolidCone(double e(double radius, double double height, height, int slices, slices, int stacks); stacks); glutWireToru glutWireTorus(double s(double inner_radius, inner_radius, double double outer_radius, outer_radius, int int sides, int rings); rings); glutSolidToru glutSolidTorus(doub s(double le inner_radius, inner_radius, double double outer_radius, outer_radius, int int sides, int rings); rings); glutWireTeap glutWireTeapot(double ot(double size); glutSolidTea glutSolidTeapot(do pot(double uble size);
CODING: #include #include #include #include static GLfloat rot=0,a=1.0,b=1.0,c=1.0,as,tx,tz,t y,sx,sy,sz,rx,ry,rz,an,ang; static GLint op, p, pr, pd, ch, key; void mydisp() { glClear (GL_COLOR_BUFFER_BIT); glMatrixMode (GL_PROJECTION); glLoadIdentity glLoadIdentity (); gluPerspective (80.0, (GLdouble)4/(GLdouble)3, 0.1, 30.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0,10.0,20.0,1.0,0.0,1.0,0.0,1.0,0.0); if (pr==1) { glColor3f(0.5, 0.5, 1.0); glutWireTeapot(8); }
if (pr==2) { glColor3f (0.0, 0.2, 1.0); glutWireS glutWireSphere phere (12, 20, 40); } if (pr==3) { glColor3f(1.0, 0.0, 0.0); glutWireTorus (4, 8, 20, 40); } if (pr==4) { glColor3f (1.0, 0.4, 0.0); glutWireCube(10); } if (pr==5) { glColor3f (1.0, 0.0, 0.0); glutWireCone (8.0, 15.0, 10, 20); } if (pr==6) { glColor3f(1.0, 0.0, 1.0); glScalef(8,12,7); glutWireTetrahedron(); } if (pr==7) { glColor3f(1.0, 0.0, 1.0); glScalef(14,12,8); glutWireOctahedron(); } glutSwapBuffers(); } void myidle() { rot=rot + 1.0; glutPostRedisplay(); } void myKey(unsig myKey(unsigned ned char pd, int x, int y) { switch(pd) { case 'p': case 'P': printf("1.Teapot\n2.Sphere\n3.Torus\n4.Cube\n5.Cone\n6.Tetrahedron\n7.Octahedron");
printf ("\n Enter the Option :"); scanf("%d",&p); switch(p) { case 1: pr=1; break; case 2: pr=2; break; case 3: pr=3; break; case 4: pr=4; break; case 5: pr=5; break; case 6: pr=6; break; case 7: pr=7; break; } break; } } void main (int argc, char** argv) { glutInit (&argc,argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); glutInitWindowSize(420,360); glutInitWindowPosition(0,0); glutCreateWindow("3D PROGRAM"); glClearColor (1, 1, 1, 0); glutDisplayFunc(mydisp); glutKeyboardFunc(myKey); glutIdleFunc(myidle); glutMainLoop(); } OUTPUT: 1.Teapot 2.Sphere
3.Torus 4.Cube 5.Cone 6.Tetrahedron 7.Octahedron Enter the Option : 1
If Choice is 2
If Choice is 3
If Choice is 4
If Choice is 5
If Choice is 6
If Choice is 7
RESULT:
Thus the OpenGL program for 3D objects is implemented implemented and executed successfully. successfully.
Ex.. No. Ex No. 12
IMPL IMPLEM EMEN ENTA TATI TION ON OF 3D SCENE SCENES S USIN USING G OPEN OPENGL GL
AIM :
To write a program using OPENGL concept for displaying a three dimensional scenes. ALGORITHM:
Step 1 : Start the program Step 2: Include the header files gl/GL.h, gl/GLO.h,gl/glut.h gl/GLO.h,gl/glut.h that are necessary for the execution of the program. Step 3 : Define the function wall with thickness parameter call the pushmatrix, translated, scaled, popmatrix function. Step 4 : Define the function tableleg with thick and len parameters with pushmatrix, translated, scaled, popmatrix function. Step 5 : Define the function jackpart with pushmatrix, scaled,translated, popmatrix function. Step 6 : Define the function jackpart with pushmatrix, jackpart(), glrotated, popmatrix function.
Step 7 : Define display solid with mat-ambient[] and mat-diffuse mat-diffuse [] arrays with with pushmatrix, wall Rotated function. Finally call the flush function. Step 8 : Define the main main function with argc and argv parameters parameters with Init Init display mode function, define windwosize and window position, color functions. Step 9 : call the glutmainloop function Step 10: Stop the program. CODING: #include"windows.h" #include"iostream.h" #include"gl/Gl.h" #include"gl/Glu.h" #include"gl/Glut.h" void tableLeg(double thick,double len)
{ glPushMatrix(); glTranslated(0,len/2,0); glScaled(thick,len,thick);
glutSolidCube(1.0); glPopMatrix(); } void table(double topWid,double topThick,double legThick,double legLen) { glPushMatrix(); glTranslated(0,legLen,0); glScaled(topWid,topThick,topWid); glutSolidCube(1.0); glPopMatrix(); double dist=0.95*topWid/2.0-legThick/2.0; glPushMatrix(); glTranslated(dist,0,dist); tableLeg(legThick,legLen); glTranslated(0,0,-2*dist); tableLeg(legThick,legLen); glTranslated(-2*dist,0,2*dist); tableLeg(legThick,legLen); glTranslated(0,0,-2*dist); tableLeg(legThick,legLen); glPopMatrix(); } void displaySolid( displa ySolid(void) void) { GLfloat mat_ambient[]={0.7f,0.7f,0.7f,1.0f}; GLfloat mat_diffuse[]={0.6f,0.6f,0.6f,1.0f}; GLfloat mat_specular[]={1.0f,1.0f,1.0f,1.0f}; GLfloat mat_shininess[]={50.0f}; glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient); glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse); glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular); glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess); GLfloat lightIntensity[]={0.7f,0.7f,0.7f,1.0f} lightIntensity[]={0.7f,0.7f,0.7f,1.0f};; GLfloat light_position[]={2.0f,6.0f,3.0f,0.0f}; glLightfv(GL_LIGHT0,GL_POSITION,light_position); glLightfv(GL_LIGHT0,GL_DIFFUSE,lightIntensity); glMatrixMode(GL_PROJECTION); glLoadIdentity(); double winHt=1.0; glOrtho(-winHt*64/48.0,winHt*64/48.0,-winHt,winHt,0.1,100.0);
glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(2.3,1.3,2,0,0.25,0,0.0,1.0,0.0); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glPushMatrix(); glTranslated(0.5,0.40,0.30); glRotated(30,0,1,0); glutSolidSphere(0.1,15,15); glPopMatrix(); glPushMatrix(); glTranslated(0.4,0,0.4); table(0.6,0.02,0.02,0.3); glPopMatrix(); glFlush(); } void main(int argc, char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH); glutInitWindowSize(640,480); glutInitWindowPosition(100,100); glutCreateWindow("3D scenes"); glutDisplayFunc(displaySolid); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glShadeModel(GL_SMOOTH); glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); glClearColor(0.1f,0.1f,0.1f,0.0f); glViewport(0,0,640,480); glutMainLoop(); }
OUTPUT:
RESULT:
Thus the OpenGL program for 3D scenes is implemented implemented and executed successfully. successfully.
Ex. No. 13
IMPLEMENTATI IMPLEMENTATION ON OF 3D TRANSFORMATION TRANSFORMATION USING OPENGL
AIM:
To write a c program for performing 3D transformation using opengl. opengl. DESCRIPTION: glTranslate ()
Multiply the current matrix by a translation matrix glTranslated(GLdouble glTranslated(GLdouble x, GLdouble y, GLdouble z); Syntax:
void glTransl glTranslatef( atef(GLfloat GLfloat x, GLfloat GLfloat y, GLfloat GLfloat z); x, y, z - Specify the x, y, and z coordinates of a translation vector. glRotate()
Multiply Multiply the current current matrix matrix by a rotation rotation matrix matrix Syntax:
void glRotated glRotated(GLdo (GLdouble uble angle, GLdouble GLdouble x, GLdouble GLdouble y, GLdouble GLdouble z); void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z); angle : Specifies the the angle of rotation, in degrees. x, y, z : Specify the x, y, and z coordinates of a vector, respectively. respectively. glScale() Multiply Multiply the current current matrix matrix by a general scaling scaling matrix matrix void void glSca glScaled( led(GLd GLdoubl oublee x, GLdoub GLdouble le y, GLdoubl GLdoublee z); Syntax:
void glScalef glScalef(GLf (GLfloat loat x, GLfloat GLfloat y, GLfloat GLfloat z); x, y, z : Specify scale factors along the x, y, and z axes, respectively.
CODING:
Ex. No. 14
IMPLEMENTATI IMPLEMENTATION ON OF 3D COMPOSITE TRANSFORMATION TRANSFORMATION USING OPENGL
Aim:
To write a c program for performing 3Dcomposite transformation using opengl. ALGORITHM:
Step 1 : Start the program Step 2 : Include the header files including GL/glut.h that are required for the ex ecution of the program. Step 3 : Define the required variables with the initialization values Step 4 : Define the mydisp function function with clear, matrix mode and load identity function calling Step 5 : Define mykey function with the pr values for different different 3D images including cube, tetrahedron. Step 6 : Get the transformation transformation option ‘M’ option ‘M’ for for translation, scaling, Rotation. Step 7 : Get the translation, Scaling, Rotation Factors and define GLfloat for each values Step 8 : Define the main function with argc, argv argv parameters and call init and init display mode function. Step 9 : Define window size, position with function. Step 10: Stop the program. CODING: #include #include #include #include static GLfloat rot=0,a=1.0,b=1.0,c=1.0,as,tx rot=0,a=1.0,b=1.0,c=1.0,as,tx,ty,tz,sx,sy ,ty,tz,sx,sy,sz,rx,ry,rz,an,an ,sz,rx,ry,rz,an,ang; g; static GLintop,p,pr,pd,ch,key; void mydisp() mydisp() { glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(80.0,(GLdouble)4/(GLdouble)3,0.1,30.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(0.0,0.0,20.0,0.0,0.0,0.0,0.0,1.0,1.0); if(as==1)
glTranslatef(a,b,c); if(as==2) glScalef(a,b,c); if(as==3) glRotatef(an,a,b,c); if(pr==1) { glColor3f(1.0,1.0,0.0); glutWireTeapot(8); } if(pr==2) { glColor3f(0.0,1.0,1.0); glutWireSphere(12,20,40); } if(pr==3) { glColor3f(1.0,0.0,1.0); glutWireTorus(4,8,20,40); } if(pr==4) { glColor3f(1.0,1.0,0.0); glutWireCube(8); } if(pr==5) { glColor3f(1.0,0.0,0.0); glutWireCone(3.0,3.0,10,20); } if(pr==6) { glColor3f(1.0,0.0,1.0); glutWireTetrahedron(); } if(pr==7) { glColor3f(1.0,0.0,1.0); glutWireOctahedron(); }
glutSwapBuffers(); } void myidle() { rot=rot+1.0; glutPostRedisplay(); } void myKey(unsigned myKey(unsigned char pd,intx,int y) { switch(pd) { case 'p': case 'P': printf("1.teapot\n2.sphere\n3.torus\n4.cube\n5.cone\n6.tetrahedron\n7.octahedron"); printf("\ printf("\nEnter nEnter the option"); option"); scanf("%d",&p); switch(p) { case 1: pr=1; break; case 2: pr=2; break; case 3: pr=3; break; case 4: pr=4; break; case 5: pr=5; break; case 6: pr=6; break;
case 7: pr=7; break; } break; case 'm': case'M': glColor3f(1.0,1.0,0.0); glutWireTeapot(8); printf("1.translation \n 2.scaling \n3.rotation"); printf("\n Enter the option"); scanf("%d",&op); switch(op) { case 1: printf("Enter the tx,ty,tz values"); scanf("%f %f %f",&tx,&ty,&tz); a=(GLfloat)tx; b=(GLfloat)ty; c=(GLfloat)tz; as=1; break; case 2: printf("Enter the sx,sy,sz values"); scanf("%f %f %f",&sx,&sy,&sz); a=(GLfloat)sx; b=(GLfloat)sy; c=(GLfloat)sz; as=2; break; case 3: printf("Enter the rx,ry,rz values"); scanf("%f %f %f",&rx,&ry,&rz); a=(GLfloat)rx; b=(GLfloat)ry; c=(GLfloat)rz; as=3; break; default: printf("choose the correct option");
break; } } } void main(intargc,char** argv) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGB); glutInitWindowSize(640,480); glutInitWindowPosition(0,0); glutCreateWindow("3D PROGRAM"); glClearColor(0,0,0,0); glutDisplayFunc(mydisp); glutKeyboardFunc(myKey); glutIdleFunc(myidle); glutMainLoop(); } OUTPUT: By pressing p
by pressing m: for translation
by pressing m: (for scaling)
by pressing pressing m (for rotating)
RESULT:
Thus the program for 3D composite transformation transformation is implemented using openGL and executed successfully.
BLENDER
Blender is a free and open-source 3D computer graphics software product used for
creating animated films, visual effects, interactive 3D applications or video games. Blender's features include 3D modeling, UV unwrapping, texturing, rigging and skinning, fluid and smoke simulation, particle simulation, animating, rendering, video editing and co mpositing. RENDERING:
A rendering is a pictorial output of a 3D scene or object. Features like materials, lighting, oversampling and shadows control the effects effects and quality of the rendering. There are three parts present in rendering they are
Materials and Textures
Lighting
Cameras
Materials and Textures:
You can control they way an object o bject appears by applying ap plying color and textures. Materials provide realism with added effects.
Lighting:
Lighting provides the realism to your scene through reflections and shadows . You can control the type of light, intensity and color. Some lights can give a “ a “fo fog” g” or or “ “dusty dusty”” look with a halo or volume lighting effect. e ffect. Illumination distances can also be set.
Cameras:
Your camera is your point-of-view for the scene. Just like a real camera, you can control lens length to achieve close-ups or wide angles. Clipping distance can also be set to control how far and near the camera sees.
In every part it consists of three single arrow heads which points the direction (i.e.) is in x, y, z direction. Time factors:
In order to animate, you must first set the length of your animation in frames and your frames per second (fps).
The given above figure tells the frame size and the green line is the starting point of the frame and ending point will be set when a image is to be animated BASIC BLENDER COMMANDS: TAB key- Toggles between edit mode (vertex editing) and object select mo de..
“O” key (not zero) will put you into proportional vertex editing while in edit “O” key- The “O” key mode. “A” key- While in edit mode it’s good for selecting all vertices for commands like remove
doubles and subdivide. “A” subdivide. “A” twice twice will clear selected and reselect. “B” key- Gives you a box (window drag) to select multiple objects. In edit mode, works the
same to select multiple vertices, but hitting “ hitting “B B” twice gives you a circle circle select that can be sized by scrolling the mouse wheel. Space Bar- Brings up the tools menu where you can add meshes, cameras, lights, etc.
views. “7 7” top, “1 top, “1”” front, “3” front, “3” side, side, “0” “0” camera, camera, “5” “5” perspective, perspective, “.” “.” Number Pad- Controls your views. “ Zooms on selected object, “+ and –“zoom –“zoom in and out. The +- buttons also control affected vertices size in proportional vertex editing. Mouse- Left to manipulate, right to select, center wheel to zoom and rotate view. If you hold
down “shift” down “shift” and and center wheel you can pan around a round on the screen. Shift Key- Hold down the shift key to make multiple selections with the right mouse button. Arrow Keys- Used to advance frames in animation. Left/right goes 1 frame at a time, up/down
goes 10 frames at a time. “R” key- Rotates an object or selected vertices.
“S” key- Scales a selected object or vertices. “G” key- Grabs or moves the object or selected vertices. “P” key - While in edit mode, selected vertices can be separated into a single object by pressing
P. Shift-“D”- Duplicates or copies selected objects or selected vertices. “E” key- While in edit mode, selected vertices can be extruded by pressing E. “U” key- In Object Mode brings up the Single-User menu to unlink materials, animations
(IPOs), etc. for linked or copied objects. Undo command. Only works in edit mode and can now go back multiple steps. Sorry, no system-wide undo command. “M” key - Moves selected objects to other layers. Mirror- while in edit mode, “M” will “M” will give
You a mirror command. “Z” key- Toggles view from wireframe to solid.
Alt “Z”- Toggles a rough texture/shaded view. “N” key- Brings up the numeric info. On a selected object (location, rotation and size). Info. can
then be changed in the window. Ctrl “J”- Joins selected objects together. “F” key- Makes a face in edit mode of the selected vertices. You can only select 3-4 vertices at
a time to make a face. “X” or Delete- Delete selected objects, vertices or faces.
Function Keys- F1-Load File; F2-Save File; F3-Save Image; F4-Lamp Buttons; F5-Material
Buttons; F6-Texture Buttons; F7-Animation Buttons; F8-Real Time Buttons; F9- Edit Buttons; F10-Display Buttons; F11-Last Render; F12-Render TYPICAL VIEWS IN BLENDER:
The views that are present in blender are
• • • •
Top view Camera or perspective view Front view Right side view
CREATION OF OBJECTS:
There are are many types of objects objects that that can be created in blender. blender. They may be Plane- A simple two-dimensional shape ideal for grounds. Can be sub-divided and used with proportional vertex editing to make nice hilly terrain. Cube- Basic 3D shape. Nice object to start with to shape into rectangles and other shapes. Circle- Won’t Won’t display display as a 3D object, but can be extruded and shaped. UV Sphere- A sphere generated generated with rings and segmen segments, ts, like the latit latitude ude and longi longitude tude of the earth. Icosphere- A sphere generated with triangular shapes. Like Epcot Center. Cylinder- Like a can, closed with a top and bottom. The three main modifiers you can use to change an object (outside of edit mode) are moving it, resizing (scaling) it or rotating it. “G” key“G” key- move or grab “S” key- sizing or scaling “R” key- rotate
Ex.No.15
CREATING FRACTALS USING BLENDER
AIM: To create a fractal fra ctal image-DNA HELIX using Blender. PROCEDURE:
1) Open blender from the location it is stored.
2) Switch to edit mode by choosing edit mode from the highlighted section on the image or press TAB
3)Add a cylinder by choosing Add-> Mesh-> cylinder. c ylinder. The cylinder appears at the origin.
4) Scale it to the desired desired size by pressing the S key and press press X and press SHIFT+Z SHIFT+Z to scale the cylinder along x and z axis and drag the mouse until you you obtain the desired size .
5) Now rotate the cylinder. c ylinder. Press Press the R button and press Y key to rotate along the Y axis and type 90 and press ENTER.
6) Now translate the cylinder along the x axis by holding the mouse over the red line and dragging it to a position as displayed below.
7) Now Right click on one of the vertices of the cube and press CTRL+L to select the entire cube.
8) Press SHIFT+D to duplicate the cube and click on the screen. And translate the cube to the position as in the below the image:
9) Now select the entire model by b y pressing the B key and the drag dra g it to select model.
10) Now to position the cursor to the center press SHIFT+S SHIFT+S and in the following pop up menu select cursor to selected option:
This will move the cursor to the center of the mo del.
11)Switch back to OBJECT MODE by pressing the TAB key
12) To move the 3D cursor to the center press ALT+SHIFT+CRTL+C and choose Origin to 3D cursor option:
13) To center the model to the center of the grid press Shift+S and choose cursor to center option :
14) Now press ALT+S and choose selection to cursor option:
15) To provide a reference reference plane add an empty plane by choosing choosing ADD-> EMPTY -> PLAIN AXES:
16) Now select the entire model by right clicking it.
17) Here fractals are created using the ARRAY MODIFIER. To select the Array Array modifier modifier click click on the WRENCH ICON as in the image below:
18) Select Add modifier and choose array.
19) Check off Relative click on the empty empty space below below and and Relative offset and check Object Object offset and click from the pop up menu select Empty
20) Translate along the Y axis up by holding the blue line and dragging dragging it up.
21) Rotate the top model by b y pressing Rand Z to rotate along z axis and rotate to a position as in the image below:
22) Now Increasing the COUNT value in the array modifier panel will generate the helix .
23) FINAL IMAGE:
RESULT:
Thus the Fractal image-DNA HELIX was created and rendered successfully.