Top Banner
ANAND INSTITUTE OF HIGHER TECHNOLOGY OLD MAHABALIPURAM ROAD, KALASALINGAM NAGAR KAZHIPATTUR, CHENNAI-603 103. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CS2405-COMPUTER GRAPHICS LABORATORY LAB MANUAL Prepared by, Ms.R.Femila Goldy,AP/CSE
107
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • ANAND INSTITUTE OF HIGHER TECHNOLOGYOLD MAHABALIPURAM ROAD, KALASALINGAM NAGAR

    KAZHIPATTUR, CHENNAI-603 103.

    DEPARTMENT OF COMPUTER SCIENCE ANDENGINEERING

    CS2405-COMPUTER GRAPHICS LABORATORY

    LABMANUAL

    Prepared by,Ms.R.Femila Goldy,AP/CSE

  • ANAND INSTITUTE OF HIGHER TECHNOLOGYOLD MAHABALIPURAM ROAD, KALASALINGAM NAGAR

    KAZHIPATTUR, NEAR CHENNAI-603 103.

    CS2405-COMPUTER GRAPHICS LABORATORY

    List of Experiments

    1. Write a program to draw the line using DDA algorithm.2. Write a program to draw the line using Bresenhams algorithm.3. Develop a program to draw the circle using midpoint circle algorithm.4. Develop a program to draw the ellipse using midpoint 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. Develop a program to clip a polygon using Sutherland Hodgeman Polygon clippingalgorithm.

    10. Write a simple opengl program to create a 3D object.11. Write a simple opengl program to create a 3D scene.

    12. Program to implement the 3D transformation.

    13. Write a Program to implement 3D Composite Transformation.14. Develop a fractal image using blender.

  • Ex. No. 1 DDA LINE DRAWING ALGORITHM

    AIM:To write a C program for drawing a line and to display the pixel positions using digital

    differential Analyser (DDA) algorithm.DESCRIPTION:

    The digital differential analyzer (DDA) is a scan-conversion line algorithm basedon calculation either y or x.The line at unit intervals in one coordinate and determinecorresponding 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

    intervals (x=1) and compute each successive y values asxk+1 = xk + 1

    yk+1 = yk + mFor lines with a positive slope (Left-right), greater than 1 (y=1) and calculate eachsucceeding x value as

    yk+1 = yk + 1xk+1 = xk + (1/m)

    A line with positive slope (Right-Left), if the slope is less than or equal to 1, at unit xintervals (x=-1) and compute each successive y values as

    xk+1 = xk - 1yk+1 = yk - m

    For lines with a positive slope (Right-left), greater than 1 (y=-1) and calculate eachsucceeding x value as

    yk+1 = yk - 1xk+1 = xk - (1/m)

  • ADVANTAGES: It is a faster method than the direct use of the line equation.

    It eliminates the floating point multiplication by making use of raster characteristics, soincrements are applied in x or y direction to step to pixel position along the line path.

    DISADVANTAGES: It drifts away from the actual line path because of rounding off float values to integer.

    It is time consuming since floating point arithmetic and rounding operations are done tocalculate pixel position.

    ALGORITHM:Step 1: Accept Input as two endpoint pixel positions

    Step 2: Horizontal and vertical differences between the endpoint positions are assigned toparameters dx and dy (Calculate dx=xb-xa and 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 along the line path.

    Step 5: loop the following process for steps number of timesa. Use a unit of increment or decrement in the x and y direction

    b. i f xa is less than xb the values of increment in the x and y directions are 1 and m c.Ifxa is greater than xb then the decrements -1 and m are used.

    CODING:#include#include#include#includeint round(float m){int n;if((m-0.5)>floor(m))n=ceil(m);elsen=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 usesonly incremental integer 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(xposition) and plot the pixel whose scan line y value is closest to the line path. Assuming we havedetermined that the pixel at (xk, yk) is to be displayed, we next need to decide which pixel to plotin column xk+1.Our choices are the pixels at positions (xk+l, yk) and (xk+l, yk+l).

    ALGORITHM:Step 1: Input the two line endpoints and store the left end point in (x0,y0)Step 2: Load (x0,y0) into frame buffer, ie. Plot the first point.

  • Step 3: Calculate the constants x, y, 2y and obtain the starting value for thedecision parameter as P0 = 2y-x

    Step 4: At each xk along the line, starting at k=0 perform the following test

    If Pk < 0, the next point to plot is(xk+1,yk) andPk+1 = Pk + 2y

    otherwise, the next point to plot is (xk+1,yk+1) andPk+1 = Pk + 2y - 2x

    Step 5: Perform step4 x times.CODING:#include#include#include#includevoid 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
  • 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 tothe specified circle path at each step for a given radius r and screen. center position (xc,yc) setup our algorithm to calculate pixel positions around a circle path centered at the coordinateposition by adding xc to x and yc to y.

    Circle function is fcircle(x,y) = x2+y2-r2Any point (x,y) on the boundary of the circle with radius r satisfies the equation fcircle (x,y)=0.If the point is in the interior of the circle, the circle function is negative. And if the point isoutside the circle the, circle function is positive

    fcircle (x,y) = 0, if (x,y) is outside the circle boundary

    ALGORITHM:Step 1: Input radius r and circle center (xc,yc) and obtain the first point on the

    circumference of the circle centered on the origin as

  • (x0,y0) = (0, r)Step 2: Calculate the initial value of the decision parameter as P0= (5/4)-r=1-rStep 3: At each xk position, starting at k=0, perform the following test. If Pk =y.CODINGS:#include#include#includevoid 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\tcoords(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 samevalues for all points on the ellipse.

    The sum of the two distances d1 and d2, between the fixed positions F1 and F2 (calledthe foci of the ellipse) to any point P on the ellipse, is the same value, i.e.

    d1 + d2 = constantThe midpoint ellipse method is applied throughout the first quadrant in two parts and

    then obtain positions in the remaining 3 quadrants by symmetry.

    f (,x )y r 2x2 r 2 y2 r 2r 2ellipse y x x y

    0 if (,x

    )y is inside the ellipsefellipse (,x )y0 if(, ) is oxn tyhe ellipse

    0 if (,x )y is outside the ellipseIn 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 than 1.

  • y x

    y x

    Starting at (0, ry) we take unit steps in the x direction until we reach the boundarybetween region 1 and region 2. Then we take unit steps in the y direction over the remainder ofthe curve in the first quadrant.

    At the boundary

    dy 1

    dx2r 2 x 2r 2 y

    therefore, we move out of region 1 whenever

    2r 2 x 2r 2 yRegion 1:(Choose (xi+1,yi ) or (xi+1,yi-1))

    Region 2: (Choose (xi, yi-1) or (xi+1,yi-1))Step in the negative y direction and midpoint is taken between horizontal pixels at each

    step.

  • ALGORITHM :Step 1: Input 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 the initial value of the decision parameter in region 1 as

    Step 3: At each xk position in region1 starting at k=0 perform the following test. If P1k=2rx2 y

    Step 4: Calculate the initial value of the decision parameter in region 2 using the last point(x0,y0) is the last position calculated in region 1.

    Step 5: At each position yk in region 2, starting at k=0 perform the following test, Ifp2k>0 the next point along the ellipse centered on (0,0) is (xk,yk-1) and

    Otherwise the next point along the ellipse is (xk+1,yk-1) and

    Using the same incremental calculations for x any y as in region 1.Step 6: Determine symmetry points in the other three quadrants.Step 7: Move each calculate pixel position (x,y) onto the elliptical path centered on (xc,yc)

    and plot the coordinate values x=x+xc,y=y+yc2 2Step 8: Repeat the steps for region1 until 2ry x>=2rx y

    CODING:#include#include

  • #include#include#includeint round(float m){int n;if((m-0.5)>floor(m))n=ceil(m);elsen=floor(m);return n;}void 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=py-rx2;p=p+ry1+px-py;} elsep=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));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(p0)p=p+rx1-py;elsep=p+rx1-py+px; 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 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 attributeparameters, such as color and size, determine the fundamental characteristics of a primitive. Theoutput primitives Such as Line, Circle and Ellipse are associated with set of attributes such asLine (color and Line Style), Circle (Color) and Ellipse (Color and Patterns).initgraph() Initialize the Graphics System

    initgraph() is a graphics system control function. It is used to initialize the graphicssystem. It should be the first graphics function called. initgraph() loads the graphics driver,after allocating memory for it, then puts the system in graphics mode. 'gdriver' is set to DETECT(autodetection), it calls detectgraph() and automatically selects the highest resolution graphicsmode for 'gmode'.

    'dpath' names the directory path where the graphic driver 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

    restore the system to the previous display (text) mode. closegraph() function restores theprevious 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.

    Syntax:closegraph();

    Shapes:

  • Computer graphics has many in-built commands, which can be used either to draw ashape and/or for filling a color in any bounded 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 endpoint of line.

    Example: line(10,10,100,100);It will draw a line from point (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 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, int stangle, int endangle, int xradius, int yradius);

  • Argument What It Is

    (x,y) Center of ellipsexradius 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 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 thicknessparameter 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);Output:

    Example: ellipse(100,100,0,360,10,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);

    Sectordraws 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, int endangle,int xradius, int yradius);barSyntax:

    void bar(int left, int top, int right, int bottom); Remarks:bar draws a filled-in, rectangular, 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 What It Is

    (left, top) the rectangle's upper left corner(right,bottom)

    the rectangle's lower right corner

    The coordinates are in pixels.

    setcolor():draws any subsequent graphics in a color 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 infollowing table.Color is the color constant or color name.

    PatternConstant

    Pattern Name

    0 EMPTY_FILL1 SOLID_FILL2 LINE_FILL3 LTSLASH_FILL4 SLASH_FILL5 BKSLASH_FILL6 LTBKSLASH_FILL7 HATCH_FILL8 XHATCH_FILL9 INTELEAVE_FILL10 WIDE_DOT_FILL11 CLOSE_DOT_FILL

    setlinestyle():specifies the thickness of the line to be drawn. These styles are not used for the circles.

    Syntax:setlinestyle(linestyle,user_defined_style,line_width);

    Constant Line0 SOLID_LINE1 DOTTED_LINE2 CENTRE_LINE3 DASHED_LINE4 USERBIT_LINE

    User_defined_style is user defined style and if ignored set to zero.Line_width is tickness of line as given below

    0 -NORM_WIDTH3- THICK_WIDTH

    Example:setlinestyle(2,0,3);

  • getbkcolorreturns the current background color.

    Syntax:int getbkcolor(void);

    setbkcolorsetbkcolor sets the background to the color specified by color.

    Syntax:

    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.o If the seed is outside the enclosed area, the exterior will be filled.

    Use fillpoly instead of floodfill whenever possible so you can maintain code compatibility withfuture versions.textheight

    textheight takes the current font size and multiplication factor, and determines the heightof textstring in pixels.

    Syntax:int far textheight(char far *textstring);

    textwidthtextwidth takes the string length, current font size, and multiplication factor, and

    determines the width of textstring in pixels

    Syntax:int far textwidth(char far *textstring);

    settextstylesettextstyle 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 all text output by outtext and outtextxy.Enum: Names for BGI fonts

    Name Value MeaningDEFAULT_FONT 0 8x8 bit-mapped fontTRIPLEX_FONT 1 Stroked triplex fontSMALL_FONT 2 Stroked small fontSANS_SERIF_FONT 3 Stroked sans-serif fontGOTHIC_FONT 4 Stroked gothic font

    Direction

    Font directions supported are horizontal text (left to right) and vertical text(rotated 90 degrees counterclockwise). The default direction is HORIZ_DIR.

    Name : Value : DirectionHORIZ_DIR 0 : Left to rightVERT_DIR 1 : Bottom to top

    CODING:#include#include#includevoid 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_FILL\n5.BKSLASH_FILL\n6.LTBSLASH_FILL\n7.HATCH_FILL\n8.XHATCH_FILL\n9.INTERLEAVE_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

  • RESULT:Thus the program for attributes of output primitive is implemented and executed

    successfully.

  • Ex. No.6 IMPLEMENTATION OF 2D TRANSFORMATION

    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 the coordinate description of objects.

    Basic transformation: Translation Rotation Scaling

    Other transformation: Reflection Shear

    Translation:A translation moves all points in an object along the same straight-line path to new

    positions.To translate a 2D position, we add translation distances tx and ty to the original

    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 + tx , y= y + ty

    x x tx y y ty

    P P T

    Rotation:

    A rotation repositions all points in an object along a circular path in the planecentered at the pivot point.

  • The original coordinates are:x r cos()cos cosr sin sinr y r sin()cos sinr sin cosr

    x r cos()y r sin()

    Substituting

    x x cos y siny x sin y cos

    Matrix form x cos sin x

    Scaling

    y sin

    P R P

    cos y

    Altering the size of an object. Sx and Sy are the scaling factors. Values less than 1 reduce the size of the objects Values greater than 1 produce an enlarged object. Uniform scaling it is necessary to assign same value for sx and sy. Unequal values for Sx and Sy result in a non uniform scaling.

    x xSxMatrix form

    x

    S x

    y yS y0 x

    y 0 S y y

    P S P

    Scaling relative to fixed point (xf, yf)

    x x f ()x x f Sxy y f ()y y f S y

  • x 1 0 0 x y 0 1 0

    y 1 0 0 1 1

    1 0 0 1 1

    1 0 0 1 1

    Reflection:A reflection is a transformation that produces a mirror image of an object. The mirror

    image for a two-dimensional reflection is generated relative to an axis of reflection by rotatingthe object 180o about the reflection axis.Reflection about x axis:

    x 1 0 0 x y 0 1 0 y

    Reflection about y axis:

    Relative to the coordinate origin

    x 1 0 0 x y 0 1 0 y

    With respect to the line y = x

  • 1 0 0 1 1y 1 0 0 y

    1 0 0 1 1y 0 1 0 y

    x 0 1 0 x

    Shear:

    A transformation that distorts the shape of an object such that the transformed shapeappears as if the object were composed of internal layers that had been caused to slide over eachother is called a shear. Two common shearing transformations are those that shift coordinate xvalues and those that shift y values.

    x-direction shearx x shx yy y

    Matrix form

    x 1 shx 0 x

    x-direction relative to other reference line

    x x shx ()y yrefy y

    Matrix form

    x 1 shx shx yref x y 0 1 0 y 1 0 0 1 1

  • y-direction shear

    x x

    y y shy x

    Matrix form

    x

    1 0 0 x

    y shy 1 0 y 1 0 0 1 1

    y-direction relative to other reference linex x

    Matrix form y y shy ()x xref x 1 0 0 x y shx 1 shy xref y 1 0 0 1 1

  • ALGORITHM :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()function.

    Step 3 : In case of translation get the translation factors and add then with the oldcoordinates of the triangle and Draw the triangle now with the new coordinates.

    Step 4 : In case of scaling get the scaling factors and multiply them with the oldcoordinates and draw the triangle with new coordinates.

    Step 5 : For Rotation get the rotation angle and the fixed point is obtained from the user andadd the calculated values to the old coordinates and draw the triangle with newcoordinates.

    Step 6 : For shearing get the shearing constants and referenceAbout x and y axis,

    (i) For shearing about x axis keep x coordinate as it in and after and change ycoordinate.(ii) For shearing about y axis keep y coordinate as it in and after x axiscoordinate.

    Draw the triangle with new calculated coordinates.Step 7 : Stop the program.

    CODING:#include#include#include#include#define COL 2int 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){int temp[6],i;for(i=0;i
  • 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
  • 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 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 enter rotation angle(in degree):");scanf("%d",&phi);rotate(phi);printf("reflection about line x=y");reflect();printf("sheared image");shear();getch();closegraph();}OUTPUT:

  • Ex. No.7 IMPLEMENTATION OF 2D COMPOSITE TRANSFORMATION

    AIM:

    To write a C-Program to perform various 2D composite transformations.

    AlgorithmStep 1 : Start the program

    Step 2 : Include all header files and Initialize the variables that are necessary for the executionof the program.

    Step 3 : To perform Translation, get coordinates of line and translate it, again translate thetranslated line.

    Step 4 : To perform scaling, get the scaling factor and change the lines length, again scale thechanged one to the Original position.

    Step 5 : To perform rotation, get the angle and rotate the line, again get the angle and rotate thealready rotated line.

    Step 6 : To perform the general fixed point scaling, first translate the line, scale it and performreverse translation.

    Step 7 : Stop the program.

    CODING:#include#include#include#includevoid 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("\nenter 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");scanf("%d%d",&sx1,&sy1);printf("\nenter sx and sy for 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,ax4;int ay1,ay2,ay3,ay4;int refx,refy;printf("\nenter the 1st angle");scanf("%f",&theta1);printf("\nenter the 2nd 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 OF CLIPPING A LINE USING COHENSUTHERLAND LINE CLIPPING ALGORITHM

    AIM:

    To write a C-program to perform line clipping using Cohen Sutherland line clippingalgorithm.

    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 or Clipping. The region againstwhich an object is to clipped is called a clip window.

    Cohen Sutherland line clipping algorithm is one of the oldest and most popular line-clipping procedures. The method speeds up the processing of line segments by performinginitial tests that reduce the number of intersections that must be calculated. It quickly detects anddispenses with two common and trivial cases.

    To clip a line, we need to consider only its endpoints. If both endpoints of a line lie insidethe 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 mustlie entirely outside of the window. It is trivially rejected and needs to be neither clipped nordisplayed.

    Every line endpoint in a picture is assigned a four digit binary code called a region code thatidentifies the location of the point relative to the boundaries of the clipping rectangle.

  • ALGORITHM:1. Assign a region code for each endpoints.

    2. If both endpoints have a region code 0000 --- trivially accept these line.3. Else, perform the logical AND operation for both region codes.

    3.1 if the result is not 0000 - trivially reject the line.3.2 else (result = 0000, need clipping)

    3.2.1. Choose an endpoint of the line that is outsidethe window.

    3.2.2. Find the intersection point at the windowboundary (base on regioncode).

    To find intersection point, use line equationintersection with LEFT or RIGHT boundary.

    x = xwmin (LEFT) x = xwmax (RIGHT)

    y = y1 + m(x x1)intersection with BOTTOM or TOP boundary.

    y = ywmin (BOTTOM) y = ywmax (TOP)

    x = x1 + (y 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 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 IMPLEMENTATION OF CLIPPING A POLYGON USINGSUTHERLAND HODGEMAN POLYGON CLIPPING

    ALGORITHM

    AIM:

    To write a C-program to perform polygon clipping using Sutherland Hodgeman polygonclipping algorithm.

    DESCRIPTION:The Sutherland Hodgeman Polygon Clipping Algorithm works by extending each line

    of the convex clip polygon in turn and selecting only vertices from the subject polygon that is onthe visible side. It accepts an ordered sequence of vertices v1, v2, v3... vn and puts out a set ofvertices defining the clipped polygon.

    Clip the polygon by processing the polygon boundary as a whole against eachwindow.

    Process all polygon vertices against each clip rectangle boundary in turn. First clip the polygon against the left boundary to produce a new sequence of

    vertices.

    The new sequence of vertices is then successive passed to right, bottom and topboundary clipper.

    At each step a new sequence of output vertices is generated and passed to the next

    boundary 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 is outside, and second is inside, output the intersection and the

    second vertex

    If both input vertices are inside, then just output second vertex If first input vertex is inside, and second is outside, output is the intersection If both vertices are outside, output is nothing. The last vertex in the list is always added to the first 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&&x2
  • if(x1=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; floatxi,yi,xf,yf,py[20];initgraph(&gd,&gm,"C:\\TC\\BGI");clrscr();printf("\nenter the coords of rectangular clip window\n 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("\nenter coords");for(i=0;i
  • clipr(py[i],py[i+1],py[i+2],py[i+3]);n=k/2;for(i=0;i
  • 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 deviceIndependent Graphics Programming language and application programming interface.

    ADVANTAGE OF OPENGL Cross platform (Windows, Linux, Mac, even some handheld devices). Fast Portable Easy to use Well-documented

    OPENGL LIBRARIES Basic GL- Fundamental Library

    Starts With gl

    GLUT- Graphics Library Utility Toolkit Opening Windows Developing and managing Menus Managing Events

    GLU- Utility Library Matrix Operation Drawing Primitives

    GLUI- User Interface Library Works along GLUT controls such as buttons, checkboxes, radio buttons.

    DYNAMICALLY-LINKED LIBRARIES opengl32.dll glu32.dll

  • LIBRARIES glut32.dll

    opengl32.lib glu32.lib glut32.lib

    INCLUDE FILES gl.h glu.h glut.h

    OPENING A WINDOW FOR DRAWINGThe First task in making pictures is to open a screen window for drawing. The following

    initialize and display the screen window in the program.

    1. glutInit(&argc, argv)It should be called before any other GLUT routine because it initializes the

    GLUT library.

    2. glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)Specify the display mode for a window.

    3. glutInitWindowSize(640,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. glutInitWindowPosition(100,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 pixelsdown from the top.

    5. glutCreateWindow(Example)The command takes a string as a parameter which may appear in the title bar.

    6. glutMainLoop()The window is not actually displayed until the glutMainLoop() is entered.

    EVENT DRIVEN PROGRAMMINGThe 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(mydisplay)Redraws screen when window opened or another window moved off it.

    2. glutReshapeFunc(myreshape)Reports new window width and height for reshaped window. (Moving a window

    does not produce a reshape event.

    3. glutKeyboardFunc(mykeyboard)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)GLUT supports interaction with the computer mouse that is triggered when one

    of the three typical buttons is presses. A mouse callback function can be initiated whena given mouse button is pressed or released. The command glutMouseFunc() is used tospecify the callback function to use when a specified button is a given state ata certain location.

    OPENGL SYNTAXvoid glBegin(GLenum mode)glvertex2i(arguments);glvertex2i(arguments);void glEnd(void)

    FORMAT OF glVertex COMMAND

    EXAMPLE:

    //the following code plots three dotsglBegin(GL_POINTS);glVertex2i(100, 50);glEnd( );

  • OPENGL DATATYPES

    PROCEDURE:OPEN GL-SETUP

    Before executing the programs you have to place three header files (dll, Header, Lib) in thefollowing locations

    Header:

    C:\Program Files\Microsoft Visual Studio\VC98\Include\GLLib:

    C:\Program Files\Microsoft Visual Studio\VC98\LibDll:

    C:\WINDOWS\system32 Go to StartProgramsMicrosoft Visual Studio 6.0 Microsoft Visual C++ 6.0 FileNew...

  • New dialog boxes opens in that select the win32console application from the projects taband 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 tab and select the browse button as given in the belowscreenshot.

  • Select the path for the three header files that you have pasted in different locations andclick on the ok button.

    FileNew...

    Select the C++ source file from the files tab and give the name for the file and click okbutton .

  • Now select project menu and select the settings from the drop down menu.

    In the project settings dialog box click on the link tab and type the three file names at theend 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 in Microsoft FoundationClasses option

    Then click on the C/C++ tab and select C++ Language from the category drop down listand click on the ok button

  • After performing these steps type the required program code save the program and click

    on the build button.

    Then click on the Execute program buttonCODING:Drawing a Teapot#include glut.hvoid 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(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 glut.hvoid 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(1.0f, 1.0f, 1.0f);glVertex3f(-1.0f, -1.0f, 0.0f);glColor3d(1.0f, 0.0f, 0.0f);glVertex3f(1.0f, -1.0f, 0.0f);glColor3d(0.0f, 1.0f, 0.0f);glVertex3f(1.0f, 1.0f, 0.0f);glColor3d(0.0f, 0.0f, 1.0f);glVertex3f(-1.0f, 1.0f, 0.0f);glEnd();glFlush();}OUTPUT:

    RESULT:Thus the program for drawing a teapot is implemented and executed successfully.

  • Ex. No. 11 IMPLEMENTATION OF 3D OBJECTS USING OPENGL

    AIM :To write a program using OPENGL for displaying a three dimensional objects.

    DESCRIPTION:OpenGL has separate transformation matrices for different graphics features

    glMatrixMode(GLenum mode) GLMODELVIEW - for manipulating model in scene

    GL_PROJECTION - perspective 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 ()Multiply the current matrix with the specified matrix

    glViewport()Set the viewport

    Example :glViewport(0, 0, width, height);

    gluPerspective()Sets up a perspective projection matrix.

    Syntax :gluPerspective(angle, asratio, ZMIN, ZMAX);

    Example :gluPerspective(60.0, width/height, 0.1, 100.0);

    gluLookAt()

  • view volume that is centered on a specified eyepoint

    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 if double buffered.

    OPENGL FUNCTIONS FOR DRAWING 3D OBJECTS glutWireCube(double size); glutSolidCube(double size); glutWireSphere(double radius, int slices, int stacks); glutSolidSphere(double radius, int slices, int stacks); glutWireCone(double radius, double height, int slices, int stacks); glutSolidCone(double radius, double height, int slices, int stacks); glutWireTorus(double inner_radius, double outer_radius, int sides, int rings); glutSolidTorus(double inner_radius, double outer_radius, int sides, int rings); glutWireTeapot(double size); glutSolidTeapot(double size);

    CODING:#include#include#include#includestatic GLfloat rot=0,a=1.0,b=1.0,c=1.0,as,tx,tz,ty,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 ();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);glutWireSphere (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(unsigned 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){

    }break;

    }}

    case 1:

    case 2:

    case 3:

    case 4:

    case 5:

    case 6:

    case 7:

    pr=1;break;

    pr=2;break;

    pr=3;break;

    pr=4;break;

    pr=5;break;

    pr=6;break;

    pr=7;break;

    void main (int argc, char** argv){

    }OUTPUT:

    1.Teapot2.Sphere

    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();

  • 3.Torus4.Cube5.Cone6.Tetrahedron7.OctahedronEnter 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 and executed successfully.

  • Ex. No. 12 IMPLEMENTATION OF 3D SCENES USING OPENGL

    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 that are necessary for theexecution 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 [] arrays with pushmatrix,wall Rotated function. Finally call the flush function.

    Step 8: Define the main function with argc and argv parameters with Init display modefunction, 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(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};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 and executed successfully.

  • Ex. No. 13 IMPLEMENTATION OF 3D TRANSFORMATION USINGOPENGL

    AIM:To write a c program for performing 3D transformation using opengl.

    DESCRIPTION:glTranslate ()

    Multiply the current matrix by a translation matrix glTranslated(GLdouble x, GLdoubley, GLdouble z);

    Syntax:void glTranslatef(GLfloat x, GLfloat y, GLfloat z);x, y, z - Specify the x, y, and z coordinates of a translation vector.

    glRotate()Multiply the current matrix by a rotation matrix

    Syntax:void glRotated(GLdouble angle, GLdouble x, GLdouble y, GLdouble z);void glRotatef(GLfloat angle, GLfloat x, GLfloat y, GLfloat z);angle : Specifies the angle of rotation, in degrees.x, y, z : Specify the x, y, and z coordinates of a vector, respectively.

    glScale()Multiply the current matrix by a general scaling matrixvoid glScaled(GLdouble x, GLdouble y, GLdouble z);

    Syntax:void glScalef(GLfloat x, GLfloat y, GLfloat z);x, y, z : Specify scale factors along the x, y, and z axes, respectively.

    CODING:

  • Ex. No. 14 IMPLEMENTATION OF 3D COMPOSITE TRANSFORMATIONUSING 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 execution of theprogram.

    Step 3: Define the required variables with the initialization valuesStep 4: Define the mydisp function with clear, matrix mode and load identity function calling

    Step 5: Define mykey function with the pr values for different 3D images including cube,tetrahedron.

    Step 6: Get the transformation option M 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 parameters and call init and init display modefunction.

    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,ty,tz,sx,sy,sz,rx,ry,rz,an,ang;static GLintop,p,pr,pd,ch,key; void 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 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("\nEnter the option");scanf("%d",&p);switch(p)

    {case 1:

    case 2:

    case 3:

    case 4:

    case 5:

    case 6:

    pr=1;break;

    pr=2;

    break;

    pr=3;

    break;

    pr=4;

    break;

    pr=5;break;

    pr=6;break;

  • }break;

    case 'm':

    case'M':

    case 7:

    pr=7;

    break;

    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:

    case 3:

    case 2:

    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;

    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;

    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("3DPROGRAM"); 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 m (for rotating)

    RESULT:Thus the program for 3D composite transformation is implemented using openGL and

    executed successfully.

  • BLENDER

    Blender is a free and open-source 3D computer graphics software product used forcreating animated films, visual effects, interactive 3D applications or video games. Blender'sfeatures include 3D modeling, UV unwrapping, texturing, rigging and skinning, fluid and smokesimulation, particle simulation, animating, rendering, video editing and compositing.

    RENDERING:A rendering is a pictorial output of a 3D scene or object. Features like materials, lighting,

    oversampling and shadows control the 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 appears by applying 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 fog or dusty look with ahalo or volume lighting effect. 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 howfar 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, zdirection.

    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 frameand 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 mode..O key- The O key (not zero) will put you into proportional vertex editing while in editmode.A key- While in edit mode its good for selecting all vertices for commands like removedoubles and subdivide. A twice will clear selected and reselect.

    B key- Gives you a box (window drag) to select multiple objects. In edit mode, works thesame to select multiple vertices, but hitting B twice gives you a circle select that can be sizedby scrolling the mouse wheel.

    Space Bar- Brings up the tools menu where you can add meshes, cameras, lights, etc.Number Pad- Controls your views. 7 top, 1 front, 3 side, 0 camera, 5 perspective, .Zooms on selected object, + and zoom in and out. The +- buttons also control affectedvertices size in proportional vertex editing.

    Mouse- Left to manipulate, right to select, center wheel to zoom and rotate view. If you holddown shift and center wheel you can pan around 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/downgoes 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 pressingP.

    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 nowgo back multiple steps. Sorry, no system-wide undo command.

    M key- Moves selected objects to other layers. Mirror- while in edit mode, M will giveYou 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. canthen 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-MaterialButtons; 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 many types of objects that can be created in blender. They may be

    Plane- A simple two-dimensional shape ideal for grounds. Can be sub-divided and used withproportional vertex editing to make nice hilly terrain.

    Cube- Basic 3D shape. Nice object to start with to shape into rectangles and other shapes.Circle- Wont display as a 3D object, but can be extruded and shaped.UV Sphere- A sphere generated with rings and segments, like the latitude and longitude of theearth.

    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- move or grabS key- sizing or scalingR key- rotate

  • Ex.No.15 CREATING FRACTALS USING BLENDER

    AIM:

    To create a fractal 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 pressTAB

  • 3)Add a cylinder by choosing Add-> Mesh-> cylinder. The cylinder appears at the origin.

    4) Scale it to the desired size by pressing the S key and press X and press SHIFT+Z to scale thecylinder along x and z axis and drag the mouse until you obtain the desired size .

  • 5) Now rotate the cylinder. Press the R button and press Y key to rotate along the Y axis andtype 90 and press ENTER.

    6) Now translate the cylinder along the x axis by holding the mouse over the red line anddragging 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 entirecube.

    8) Press SHIFT+D to duplicate the cube and click on the screen. And translate the cube to theposition as in the below the image:

  • 9) Now select the entire model by pressing the B key and the drag it to select model.

    10) Now to position the cursor to the center press SHIFT+S and in the following pop up menuselect cursor to selected option:

    This will move the cursor to the center of the model.

  • 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 3Dcursor option:

  • 13) To center the model to the center of the grid press Shift+S and choose cursor to centeroption :

    14) Now press ALT+S and choose selection to cursor option:

  • 15) To provide a reference plane add an empty plane by choosing ADD-> EMPTY -> PLAINAXES:

    16) Now select the entire model by right clicking it.

  • 17) Here fractals are created using the ARRAY MODIFIER. To select the Array modifier clickon the WRENCH ICON as in the image below:

    18) Select Add modifier and choose array.

  • 19) Check off Relative offset and check Object offset and click on the empty space below andfrom the pop up menu select Empty

    20) Translate along the Y axis up by holding the blue line and dragging it up.

  • 21) Rotate the top model by pressing Rand Z to rotate along z axis and rotate to a position as inthe 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.