Vous êtes sur la page 1sur 138

Multimedia Lab Manual

TABLE OF CONTENTS 1. INTRODUCTION 3 TO COMPUTER GRAPHICS

1.1. What is Computer Graphics?....................................................................... ....3 1.2. Origin of Computer Graphics.3 1.3. Classification of Computer Graphics 4 1.4. Working of an Interactive Graphics Display.4 1.5. Importance of Speed in displaying pictures..6 1.6. How does a picture grow, shrink and rotate?..................................................6 1.7. Applications of Computer graphics...6 2. ESSENTIAL CONCEPTS GRAPHICS10 IN COMPUTER

2.1. Pixel 10 2.2. Bitmap.... 10 2.3. Pixel Resolution.11 2.4. Image Resolution..12 2.5. Display Processors.12 2.6. Refresh Rate ..12 2.7. Frame Buffer..12 2.8. Cathode Ray Tube.15 2.9. Shadow Mask CRT17 2.10. Importance of Refresh Rates19

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

2.11. Aspect Ratio...19 2.12. Raster Graphics..19 2.12.1. Rasterization. .21 2.12.2. Raster Display...21 2.13. Types of Display Systems.22 2.13.1. Raster Scan Systems.22 2.13.2. Raster Scan Display Processor23 2.13.3. Raster Scan Display..24 2.13.4. Random Scan Systems.25 2.13.5. Random Scan Display..25 2.14. Colour in Raster Graphics.26 3. FUNDAMENTAL ALGORITHMS GRAPHICS.28 IN COMPUTER

3.1. Graphics Primitives and Attributes .28 3.2. Scan Conversion28 3.2.1. Scan converting a point28 3.2.2. Scan converting a line .29 3.3. Design criteria of straight lines29 3.4. Line Drawing Algorithms.29 3.4.1. Digital Differential Analyzer Algorithm..29 3.4.2. The Bresenhams Line-Drawing Algorithm...31 3.5. Scan converting a circle..34

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

The Bresenhams Circle-Drawing Algorithm. 34 3.5.1. Mid point circle algorithm... 35 4. BASIC TRANSFORMATIONS37 4.1. Transformation Principles37 4.2. World and Modeling Coordinates37 World Coordinates37 Modeling Coordinates..38 4.3. Basic Types of Transformation38 4.3.1. Translation 41 4.3.2. Scaling.. .42 4.3.3. Rotation .43 4.4. Matrix Representation of Transformations.44 5. ANIMATION .46 5.1. Design of an animation sequence ...46 Morphing47 6. GRAPHIC .50 FUNCTIONS OUT

7. WORKED EXERCISES..67

DDA algorithm..67 7.1. Bresenhams line drawing algorithm...70 7.2. Bresenhams circle drawing algorithm73 7.3. A dynamic solar system.75

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

7.4. A see-saw in a playground78 7.5. A virtual worship80 7.6. A leaky bucket83 7.7. A man riding a bicycle...86 8. UNIVERSITY PRACTICAL QUESTIONS90 EXAMINATION

9. VIVA QUESTIONS...92 10. APPENDIX 94 10.1. Sample codes of the graphic functions94 10.2. Key to the viva questions.124

1. INTRODUCTION TO COMPUTER GRAPHICS The main objective of this lab manual is to provide an overview of computer graphics. his manual also provide you a thorough understanding of the basic concepts, mathematical models, techniques, and algorithms used in computer graphics in two and three dimensions. Today there are very few aspects of our lives not affected by computers. Practically every cash or monetary transaction that takes place daily involves a computer. In many cases, the same is true of computer graphics. Whether you see them on television, in newspapers, in weather reports or while at the doctors surgery, computer images are all around you. A picture is worth a thousand words is a well-known saying and highlights the advantages and benefits of the visual presentation of our data. We are able to obtain a comprehensive overall view of our data and also study features and areas of particular interest.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

A well-chosen graph is able to transform a complex table of numbers into meaningful results. You know that such graphs are used to illustrate papers, reports and thesis, as well as providing the basis for presentation material in the form of slides and overhead transparencies. A range of tools and facilities are available to enable users to visualize their data, and this document provides a brief summary and overview. Computer graphics can be used in many disciplines. Charting, Presentations, Drawing, Painting and Design, Image Processing and Scientific Visualization are some among them. 1.1 What is computer graphics? Computer Graphics (CG) is the pictorial representation and manipulation of data by a computer. That is it is the field of visual computing, where one utilizes computers both to generate visual images synthetically and to integrate or alter visual and spatial information sampled from the real world. This field can be divided into several areas: real-time 3D rendering (often used in video games), video capture and video creation rendering, special effects editing (often used for movies and television), image editing, and modeling (often used for engineering and medical purposes). Development in computer graphics was first fueled by academic interests and government sponsorship. However, as real-world applications of computer graphics (CG) in broadcast television and movies proved a viable alternative to more traditional special effects and animation techniques, commercial parties have increasingly funded advances in the field. 1.2 Origin of Computer Graphics Years of research and development were made to achieve the goals in the field of computer graphics. In 1950 the first computer driven display was used to generate only simple pictures. This display made use of a cathode ray tube similar to the one used in television sets. During 1950s interactive computer graphics made little progress because the computers of that period were so unsuited to interactive use. These computers were used to perform only lengthy calculations. The single vent that did the most to promote interactive computer graphics as an important new field was the publication in 1962 of a brilliant thesis by Ivan E. Sutherland. His thesis, entitled Sketchpad: A Man- Machine Graphical Communication System, proved to many readers that interactive computer graphics was a viable, useful, and
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

exciting field of research. By the mid -1960s large computer graphics research projects were under taken at MIT, Bell Telephone Labs and General Motors. Thus the golden age of computer graphics began. In 1970s thee researches began to bear fruit. The instant appeal of computer graphics to users of all ages has helped it to spread into many applications throughout the world. 1.3 Classification of Computer Graphics Computer Graphics can be broadly divided into two a) Non Interactive Computer Graphics b) Interactive Computer Graphics Non Interactive Computer Graphics: In non interactive computer graphics otherwise known as passive computer graphics, the observer has no control over the image. Familiar examples of this type of computer graphics include the titles shown on TV and other forms of computer art. Interactive Computer Graphics: Interactive Computer Graphics involves a two way communication between computer and user. Here the observer is given some control over the image by providing him with an input device for example the video game controller of the ping pong game. This helps him to signal his request to the computer. The computer on receiving signals from the input device can modify the displayed picture appropriately. To the user it appears that the picture is changing instantaneously in response to his commands. He can give a series of commands, each one generating a graphical response from the computer. In this way he maintains a conversation, or dialogue, with the computer. Interactive computer graphics affects our lives in a number of indirect ways. For example, it helps to train the pilots of our airplanes. We can create a flight simulator which may help the pilots to get trained not in a real aircraft but on the grounds at the control of the flight simulator. The flight simulator is a mock up of an aircraft flight deck, containing all the usual controls and surrounded by screens on which we have the projected computer generated views of the terrain visible on take off and landing. Flight simulators have many advantages over the real aircrafts for training purposes, including fuel savings, safety, and the ability to familiarize the trainee with a large number of the worlds airports. 1.4 Working of an Interactive Graphics Display

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

Interactive graphics display consists of three components a) A display controller b) A digital memory or frame buffer c) A television monitor d) A video controller The display controller gets the inputs and commands from the user and determines the image to be displayed on the monitor. The display controller will divide the image into a number of pixels. This image which is to be displayed is stored in the frame buffer. The image will be stored as a matrix of intensity values. The image will be displayed onto the television monitor and the video controller will act as a simple interface that passes the contents of the frame buffer to the monitor. The image must be repeatedly passed to the monitor, 30 or more times a second. This helps you to maintain a steady picture on the screen. In the frame buffer the image is stored as a pattern of binary digital numbers. These binary digital numbers represents a rectangular array of picture elements or pixels (a picture can be divided into a number of picture elements or pixels. You will learn more about pixels in the coming lectures.). So corresponding to each pixel you have a binary digital number in the frame buffer. If your image is a black and white image you can represent the black pixels by 0 s and white pixels by 1s. Therefore a 16 X 16 array of black and white pixels could be represented by the binary values stored in the 32 8-bit bytes. Now what happens to this data? The video controller simply reads each successive byte of data from the frame buffer and converts its 0s and 1s into the corresponding video signal. This signal is then fed into the TV monitor, producing a black and white pattern on the screen. The video controller repeats this operation 30 times a second in order to maintain a steady picture on the TV screen. Now what should be done to change or modify this image? All we need is to modify the frame buffers contents. Set the frame buffer with a new set of values so that it represents the new image. In this way we can achieve effects like a rotating wheel and a wheel that grows and shrinks. The figure given below gives an idea about the graphics display system

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

Graphics display system

1.5 Importance of speed in displaying pictures Why is speed so important in displaying pictures? One reason behind this is that any display based on the CRT must be refreshed by repeatedly passing it to the monitor. The image must be transmitted to the display monitor point by point. If the image is not transmitted at least 25 times per second, the image will start to flicker in an unpleasant manner. If the speed of transmitting each picture element is less, then only fewer elements will be transmitted and only less information will be displayed. The second reason is that the response of a computer program to the actions by its user should be very fast i.e. the response time should be very small. The speed of response depends on two factors. a) The rate at which the computer can generate a fresh image in response to each action by its users. b) The rate at which the image is transmitted to the display monitor. Generally speaking, slow response always makes interactive graphics program more difficult to operate .Perhaps thats the reason why research efforts are made to improve the speed of interactive response.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

1.6 How does a picture grow, shrink and rotate? How are pictures made to rotate? How are pictures made to shrink? How are pictures made to grow? Pictures can be made to change the orientation and size. How are these changes possible? These transformations or changes are based on standard mathematical techniques: coordinate geometry, trigonometry and matrix methods. These techniques tell us how to compute the new coordinates after applying the transformations. We will study more about transformations of objects in the coming lectures. 1.7 Applications of Computer Graphics The following are also considered graphics applications: Paint programs: Allow you to create rough freehand drawings. The images are stored as bit maps and can easily be edited. It is a graphics program that enables you to draw pictures on the display screen which is represented as bit maps (bit-mapped graphics). In contrast, draw programs use vector graphics (object-oriented images), which scale better. Most paint programs provide the tools shown below in the form of icons. By selecting an icon, you can perform functions associated with the tool. In addition to these tools, paint programs also provide easy ways to draw common shapes such as straight lines, rectangles, circles, and ovals. Illustration/design programs: Supports more advanced features than paint programs, particularly for drawing curved lines. The images are usually stored in vector-based formats. Illustration/design programs are often called draw programs. Presentation graphics software: Lets you create bar charts, pie charts, graphics, and other types of images for slide shows and reports. The charts can be based on data imported from spreadsheet applications. A type of business software that enables users to create highly stylized images for slide shows and reports. The software includes functions for creating various types of charts and graphs and for inserting text in a variety of fonts. Most systems enable you to import data from a spreadsheet application to create the charts and graphs. Presentation graphics is often called business graphics.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

Animation software: Enables you to chain and sequence a series of images to simulate movement. Each image is like a frame in a movie. It can be defined as a simulation of movement created by displaying a series of pictures, or frames. A cartoon on television is one example of animation. Animation on computers is one of the chief ingredients of multimedia presentations. There are many software applications that enable you to create animations that you can display on a computer monitor.

An Animated Picture

There is a difference between animation and video. Whereas video takes continuous motion and breaks it up into discrete frames, animation starts with independent pictures and puts them together to form the illusion of continuous motion. CAD software: Enables architects and engineers to draft designs. It is the acronym for computer-aided design. A CAD system is a combination of hardware and software that enables engineers and architects to design everything from furniture to airplanes. In addition to the software, CAD systems require a high-quality graphics monitor; a mouse, light pen, or digitizing tablet for drawing; and a special printer or plotter for printing design specifications. CAD systems allow an engineer to view a design from any angle with the push of a button and to zoom in or out for close-ups and longdistance views. In addition, the computer keeps track of design dependencies so that when the engineer changes one value, all other values that depend on it are automatically changed accordingly.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

10

Multimedia Lab Manual

From pencil sketch to Computer Aided Design to Real Design.

Until the mid 1980s, all CAD systems were specially constructed computers. Now, you can buy CAD software that runs on generalpurpose workstations and personal computers. Desktop publishing: Provides a full set of word-processing features as well as fine control over placement of text and graphics, so that you can create newsletters, advertisements, books, and other types of documents. It means by using a personal computer or workstation high-quality printed documents can be produced. A desktop publishing system allows you to use different typefaces, specify various margins and justifications, and embed illustrations and graphs directly into the text. The most powerful desktop publishing systems enable you to create illustrations; while less powerful systems let you insert illustrations created by other programs. As word-processing programs become more and more powerful, the line separating such programs from desktop publishing systems is becoming blurred. In general, though, desktop publishing applications give you more control over typographical characteristics, such as kerning, and provide more support for full-color output. A particularly important feature of desktop publishing systems is that they enable you to see on the display screen exactly how the document will appear when printed. Systems that support this feature are called WYSIWYGs (what you see is what you get).
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

11

Multimedia Lab Manual

Until recently, hardware costs made desktop publishing systems impractical for most uses. But as the prices of personal computers and printers have fallen, desktop publishing systems have become increasingly popular for producing newsletters, brochures, books, and other documents that formerly required a typesetter. Once you have produced a document with a desktop publishing system, you can output it directly to a printer or you can produce a PostScript file which you can then take to a service bureau. The service bureau has special machines that convert the PostScript file to film, which can then be used to make plates for offset printing. Offset printing produces higher-quality documents, especially if color is used, but is generally more expensive than laser printing. In general, applications that support graphics require a powerful CPU and a large amount of memory. Many graphics applicationsfor example, computer animation systemsrequire more computing power than is available on personal computers and will run only on powerful workstations or specially designed graphics computers. This is true of all three-dimensional computer graphics applications. In addition to the CPU and memory, graphics software requires a graphics monitor and support for one of the many graphics standards. Most PC programs, for instance, require VGA graphics. If your computer does not have built-in support for a specific graphics system, you can insert a video adapter card. The quality of most graphics devices is determined by their resolution how many pixels per square inch they can representand their color capabilities

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

12

Multimedia Lab Manual

2. ESSENTIAL CONCEPTS IN COMPUTER GRAPHICS Let us now discuss about some of the important concepts in Computer Graphics 2.1. Pixel A pixel (short for picture element, using the common abbreviation "pix" for "picture") is one of the many tiny dots that make up the representation of a picture in a computer's memory. Each such information element is not really a dot, nor a square, but an abstract sample. With care, pixels in an image can be reproduced at any size without the appearance of visible dots or squares; but in many contexts, they are reproduced as dots or squares and can be visibly distinct when not fine enough. The intensity of each pixel is variable; in color systems, each pixel has typically three or four dimensions of variability such as red, green and blue, or cyan, magenta, yellow and black.

Representation of a pixel

A 2.2. Bitmap
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

13

Multimedia Lab Manual

A bitmap is a collection of pixels that describes an image, in human terms, a complete picture. A bitmap can be of various bit depth and resolution. Basically, a bitmap is an array of pixels.

A bit mapped graphics enlarged to show detail and individual pixels

A Bitmap is a pixel by pixel image. It is the method of storing information that maps an image pixel, bit by bit. There are many bitmapped file formats, .bmp, .pcx, .pict, .pict-2, tiff, .tif, .gif (89a), and so on. Most image files are bit mapped. Bitmap images are used by all computers. The desktop or screen information for all Windows machines uses .bmp files, while the Macintosh uses pict files. 2.3. Pixel Resolution The term resolution is often used as a pixel count in digital imaging, even though American, Japanese, and international standards specify that it should not be so used, at least in the digital camera field. An image of N pixels high by M pixels wide can have any resolution less than N lines per picture height, or N TV lines. But when the pixel counts are referred to as resolution, the convention is to describe the pixel resolution with the set of two positive integer numbers, where the first number is the number of pixel columns (width) and the second is the number of pixel rows (height), for example as 640 by 480. Another popular convention is to cite resolution as the total number of pixels in the image, typically given as number of mega pixels, which can be calculated by multiplying pixel columns by pixel rows and dividing by one million. Other conventions include describing pixels per length unit or pixels per area unit, such as pixels per inch or per square inch. None of these pixel resolutions are true resolutions, but they are widely referred to as such; they serve as upper bounds on image resolution.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

14

Multimedia Lab Manual

Resolution in computer graphics either refers to the number of pixels per inch or other unit of measure (centimeter for example) on a monitor or printer. It is also sometimes used to describe the total number of pixels on a monitor. Resolution is usually measured in pixels per inch or dots per inch (dpi).Most monitors can display at 72 dpi. Monitors come in a variety of resolutions. They can get as small as 320 pixels by 200 pixels or as large as 1280 by 1024. Printers can also print at many different resolutions. The resolution can be as small as 128 dpi or less, to 300 dpi on inkjet printers, to 720 dpi on laser printer, and up to 2000 dpi on high quality type-setters. Below is an illustration of how the same image might appear at different pixel resolutions, if the pixels were poorly rendered as sharp squares (normally, a smooth image reconstruction from pixels would be preferred, but for illustration of pixels, the sharp squares make the point better).

Resolution in various media a) DVDs have roughly 500 lines (or TV lines, or lines per picture height). b) High definition television has 1,080 lines. c) 35mm movie film is scanned for release on DVD at 1080 or 2000 lines as of 2005. d) 35mm optical camera negative motion picture film can resolve up to 6,000 lines. e) 35mm projection positive motion picture film has about 2,000 lines which results from the analogue printing from the camera negative of an interpositive, and possibly an internegative, then a projection positive. f) Newer films are scanned at 4,000 lines, called 4K scanning, anticipating any advances in digital projection or higher resolution in flat panel display. 2.4. Image Resolution Image resolution describes the detail an image holds. The term applies equally to digital images, film images, and other types of images. Higher resolution means more image detail. Image resolution can be measured in various ways. Basically, resolution quantifies how close lines can be to each other and still be visibly resolved. Resolution units
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

15

Multimedia Lab Manual

can be tied to physical sizes (e.g. lines per mm, lines per inch) or to the overall size of a picture (lines per picture height, also known simply as lines, or TV lines). Furthermore, line pairs are often used instead of lines. A line pair is a pair of adjacent dark and light lines, while a line counts both dark lines and light lines. A resolution of 10 lines per mm means 5 dark lines alternating with 5 light lines, or 5 line pairs per mm. Photographic lens and film resolution are most often quoted in line pairs per mm. 2.5 Display Processors Display processor is sometimes referred to as graphics controller or a display coprocessor. The purpose of the display processor is to free the CPU from the graphics chores. A major task of the display processor is digitizing a picture definition given in an application program into a set of pixel-intensity values for storage in the frame buffer. This digitization process is called scan conversion. 2.6. Refresh Rate A refresh rate is the number of times a screen is redrawn in one second and is measured in Hertz (Hz). Therefore, a monitor with a refresh rate of 85 Hz is redrawn 85 times per second. Today, a refresh rate of 75 Hz or above is considered to be flicker-free 2.7. Frame Buffer A frame buffer is a large, contiguous piece of computer memory. At a minimum there is one memory bit for each pixel in the rater; this amount of memory is called a bit plane. The picture is built up in the frame buffer one bit at a time. You know that a memory bit has only two states, therefore a single bit plane yields a black-and white display. You know that a frame buffer is a digital device and the CRT is an analog device. Therefore, a conversion from a digital representation to an analog signal must take place when information is read from the frame buffer and displayed on the raster CRT graphics device. For this you can use a digital to analog converter (DAC).Each pixel in the frame buffer must be accessed and converted before it is visible on the raster CRT.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

16

Multimedia Lab Manual

A single bit-plane black white frame buffer raster CRT graphics device

N-bit colour Frame buffer Color or gray scales are incorporated into a frame buffer rater graphics device by using additional bit planes. The intensity of each pixel on the CRT is controlled by a corresponding pixel location in each of the N bit planes. The binary value from each of the N bit planes is loaded into corresponding positions in a register. The resulting binary number is interpreted as an intensity level between 0 (dark) and 2n -1 (full intensity). This is converted into an analog voltage between 0 and the maximum voltage of the electron gun by the DAC. A total of 2N intensity levels are possible. Figure given below illustrates a system with 3 bit planes for a total of 8 (23) intensity levels. Each bit plane requires the full complement of memory for a given raster resolution; e.g., a 3-bit plane frame buffer for a 1024 X1024 raster requires 3,145,728 (3 X 1024 X1024) memory bits.

An N- bit plane gray level frame buffer

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

17

Multimedia Lab Manual

An increase in the number of available intensity levels is achieved for a modest increase in required memory by using a lookup table. Upon reading the bit planes in the frame buffer, the resulting number is used as an index into the lookup table. The look up table must contain 2N entries. Each entry in the lookup table is W bit wise. W may be greater than N. When this occurs, 2W intensities are available; but only 2N different intensities are available at one time. To get additional intensities, the lookup table must be changed.

Because there are three primary colours, a simple color frame buffer is implemented with three bit planes, one for each primary color. Each bit plane drives an individual color gun for each of the three primary colors used in color video. These three primaries (red, green, and blue) are combined at the CRT to yield eight colors.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

18

Multimedia Lab Manual

Simple Color frame buffer

2.8. Cathode Ray Tube The primary output device in a graphics system is a video monitor. The operation of most video monitors is based on the standard cathode ray tube (CRT) design.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

19

Multimedia Lab Manual

A CRT works by moving an electron beam back and forth across the back of the screen. Each time the beam makes a pass across the screen, it lights up phosphor dots on the inside of the glass tube, thereby illuminating the active portions of the screen. By drawing many such lines from the top to the bottom of the screen, it creates an entire screen of images. The primary output device in a graphics system is a video monitor. The operation of most video monitors is based on the standard cathode ray tube (CRT) design.

Operation of an electron gun with an accelerating anode

Basic design of a magnetic deflection CRT

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

20

Multimedia Lab Manual

The electron gun emits a beam of electrons which are focused to a point on the screen phosphor. The beam is positioned on the screen by a deflection system which operates in the horizontal and vertical directions. The intensity of the beam is controlled by the intensity signal on the control grid. When the phosphor is hit by the electron beam it absorbs energy and jumps to a higher quantum-energy level. As it returns to its normal level it emits visible light i.e. it phosphoresces. In the phosphors used in graphics devices the persistence of the phosphorescence is typically 10-60 microseconds. Before the human visual system can see a transient image it must be continually redrawn (refreshed) at a rate higher than the critical fusion frequency of the human visual system. To allow the human visual system to see a continuously refreshed image without flicker the refresh rate has to be at least 60 c/s. To allow continuous refreshing of an image there must be some stored representation of the image from which the refresh system can obtain the graphical information required to re-draw the image. This representation nowadays is invariably a set of values of intensity/colour at each of a discrete set of points laid out in a rectangular array covering the screen. While it may seem a disadvantage to continually refresh the image there are some very important advantages of such refresh type systems. For example it is possible to edit an image by changing the
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

21

Multimedia Lab Manual

stored representation between refresh cycles for what appears to be instantaneous updating of the image. Compare this with some earlier systems in which the only way to carry out an edit was to clear the whole screen and then redraw the whole image. Also by changing the stored representation between refresh cycles animation is possible.

Electron gun

The electron gun emits a beam of electrons which are focused to a point on the screen phosphor. The beam is positioned on the screen by a deflection system which operates in the horizontal and vertical directions. The intensity of the beam is controlled by the intensity signal on the control grid. When the phosphor is hit by the electron beam it absorbs energy and jumps to a higher quantum-energy level. As it returns to its normal level it emits visible light i.e. it phosphoresces. In the phosphors used in graphics devices the persistence of the phosphorescence is typically 10-60 microseconds. 2.9. Shadow Mask CRT In Shadow Mask CRT tiny holes in a metal plate separate the colored phosphors in the layer behind the front glass of the screen. The holes are placed in a manner ensuring that electrons from each of the tube's three cathode guns reach only the appropriately-colored phosphors on the display. All three beams pass through the same holes in the mask, but the angle of approach is different for each gun. The spacing of the holes, the spacing of the phosphors, and the placement of the guns is arranged so that for example the blue gun only has an unobstructed path to blue phosphors. The red, green, and blue phosphors for each pixel are generally arranged in a triangular shape (sometimes called a "triad"). All early color televisions and the majority of computer monitors, past and present, use shadow mask technology. Traditionally, shadow masks have been made of materials which temperature variations cause to expand and contract to the point of affecting performance. The energy the shadow mask absorbs from the electron gun in normal operation causes it to heat up and expand, which leads to blurred or discolored (see doming) images. The invar shadow mask is composed of the nickel-iron alloy invar. Therefore it expands and contracts much less than other materials in response to temperature changes. This property allows displays made with this technology to provide a clearer, more accurate picture. It also reduces
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

22

Multimedia Lab Manual

the amount of long-term stress and damage to the shadow mask that can result from repeated expand/contract cycles, thus increasing the display's life expectancy. In other words, In Shadow Mask CRT, before the stream of electrons produced by the CRT's cathode reach the phosphor coated faceplate, it encounters the shadow mask, a sheet of metal etched with a pattern of holes. The mask is positioned in the glass funnel of the CRT during manufacture and the phosphor is coated onto the screen so that electrons coming from the red, green and blue gun positions only land on the appropriate phosphor.

RGB color model

Stray electrons strike the shadow mask and are absorbed by it, generating a great deal of heat, which in turn causes the metal to expand. To allow flatter CRTs to be made, the metal most commonly used now for shadow masks is Invar, an alloy of iron and nickel. The metal has a low coefficient of expansion and its name derives from the supposed invariability of its dimensions when heat is applied. In reality, its dimensions are not completely invariable and the build up of heat in a shadow mask can lead to a form of distortion known as doming, where the centre of the mask bulges towards the faceplate slightly.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

23

Multimedia Lab Manual

An alternative to the shadow mask which is less prone to distortion, the aperture grille , was included as part of the design of Trinitron CRTs by Sony in 1968 and Mitsubishi in its Diamondtron products in the early 1990s. 2.10. Importance of Refresh Rates When choosing a monitor, one of the factors that the customer usually considers is the refresh rate. A high refresh rate is important in providing a clear picture and avoiding eye fatigue. What is a refresh rate and why is a monitor's refresh rate important? An image appears on screen when electron beams strike the surface of the screen in a zig-zag pattern. A refresh rate is the number of times a screen is redrawn in one second and is measured in Hertz (Hz). Therefore, a monitor with a refresh rate of 85 Hz is redrawn 85 times per second. A monitor should be "flicker-free meaning that the image is redrawn quickly enough so that the user cannot detect flicker, a source of eye strain. Today, a refresh rate of 75 Hz or above is considered to be flicker-free 2.11. Aspect Ratio Aspect ratio determines the proportion of width to height of image displayed on screen

1:1

2:1

16:9

2.12. Raster Graphics

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

24

Multimedia Lab Manual

A raster graphics image, digital image, or bitmap, is a data file or structure representing a generally rectangular grid of pixels, or points of color, on a computer monitor, paper, or other display device. The color of each pixel is individually defined; images in the RGB color space, for instance, often consist of colored pixels defined by three bytesone byte each for red, green and blue. Less colorful images require less information per pixel; an image with only black and white pixels requires only a single bit for each pixel. Raster graphics are distinguished from vector graphics in that vector graphics represent an image through the use of geometric objects such as curves and polygons. A colored raster image (or pixmap) will usually have pixels with between one and eight bits for each of the red, green, and blue components, though other color encodings are also used, such as fouror eight-bit indexed representations that use vector quantization on the (R, G, B) vectors. The green component sometimes has more bits than the other two to allow for the human eye's greater discrimination in this component. The quality of a raster image is determined by the total number of pixels (resolution), and the amount of information in each pixel (often called color depth). For example, an image that stores 24 bits of color information per pixel (the standard for all displays since around 1995) can represent smoother degrees of shading than one that only stores 16 bits per pixel, but not as smooth as one that stores 48 bits (technically; this would not be discernible by the human eye). Likewise, an image sampled at 640 x 480 pixels (therefore containing 307,200 pixels) will look rough and blocky compared to one sampled at 1280 x 1024 (1,310,720 pixels). Because it takes a large amount of data to store a high-quality image, data compression techniques are often used to reduce this size for images stored on disk. Some techniques sacrifice information, and therefore image quality, in order to achieve a smaller file size. Compression techniques that lose information are referred to as "lossy" compression. Raster graphics cannot be scaled to a higher resolution without loss of apparent quality. This is in contrast to vector graphics, which easily scale to the quality of the device on which they are rendered. Raster graphics are more practical than vector graphics for photographs and photo-realistic images, while vector graphics are often more practical for typesetting or graphic design. Modern computer monitors typically display about 72 to 130 pixels per inch (PPI), and some modern consumer printers can resolve 2400 dots per inch (DPI) or more; determining the most appropriate image resolution for a given printer

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

25

Multimedia Lab Manual

resolution can be difficult, since printed output may have a greater level of detail than can be discerned on a monitor. Example of a raster To illustrate the matter further, here is the letter "J": A close look at the letter will appear as such, where the "X" and "." characters represent a grid of pixels: .....X .....X .....X .....X .....X .....X X....X X....X .XXX.. A computer sees something more like this, where "." represents a zero and "X" represents a one: 000001 000001 000001 000001 000001 000001 100001 100001 011100 Where a zero appears, the computer software instructs its video hardware to paint the current background color. A one calls for the current foreground color. The software makes a distinction between the colors of adjacent pixels, which together form an image. This is the basic principle behind graphics editing on a computer. Raster graphics was first patented by Texas Instruments in the 1970s, and is now ever-present. 2.12.1. Rasterization Rasterization is the task of taking an image described in a vector graphics format (shapes) and converting it into a raster image (pixels or dots) for output on a video display or printer. 2.12.2. Raster Display
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

26

Multimedia Lab Manual

System Components a) The screen is subdivided into a matrix of pixels (smallest addressable units). b) Raster scan line -- A line of pixels along the screen c) Frame (refresh) buffer -- Block of memory used to store the screen pattern How it works a) The DISPLAY PROCESSOR produces the raster image in the frame buffer from the commands b) The VIDEO CONTROLLER moves the beam row wise across the pixels setting it on and off according to the content of the frame buffer c) The display must be refreshed to avoid flickering (raster image redisplayed 30 to 60 times per second)

Commands in display list after 1 scan line

Frame Buffer

Screen

Screen after 2 scan lines

Screen after 3 scan lines

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

27

Multimedia Lab Manual

Screen after 4 scan lines 2.13. Types of Display Systems

Screen after 5 scan lines

The display systems can be broadly divided into two: a) Raster scan b) Random scan 2.13.1. Raster Scan Systems In commonly used raster systems a fixed area is reserved for the frame buffer, and the video controller is given direct access to the frame buffer memory. Frame buffer locations and the corresponding screen positions are referenced in Cartesian coordinates.

Architecture of a raster system with a fixed portion of the system memory reserved for the frame buffer

For the graphics monitor, the origin I defined at the lower left screen corner. The screen is represented as a two dimensional system i.e. the x values increasing to the right and the y values increasing from bottom to top. Each scan line is labeled as y max at the top of the screen to 0 at the bottom. Along each scan line, screen pixel positions are labeled from 0 to x max. 2.13.2. Raster Scan Display Processor Raster Scan system may contain a separate display processor.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

28

Multimedia Lab Manual

Raster Scan with Display processor

Raster Scan Display processor is sometimes referred to as graphics controller or a display coprocessor. The purpose of this processor is to free the CPU from the graphics tasks. But what is its major task? Its major task is to digitize a picture definition given in an application program into a set of pixel intensity values for storage in the frame buffer. This digitization process is called scan conversion. Graphics commands specifying straight lines and other geometric shapes can be can converted into a set of intensity points. When you scan convert a straight line segment we have to locate the pixel positions closest to the line path and store the intensity for each position in the frame buffer. Characters can be defined with rectangular grids or they can be defined with outlines. The array size for character grids can vary from about 5 by 7 or 9 by 12.

Defined as a grid of pixel position outline

Defined as a curve

Display processor are deigned to perform different other functions. They are To generate various line styles (dashed , dotted, or solid) To display colour areas
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

29

Multimedia Lab Manual

To perform certain manipulations and transformations on displayed objects To interface with interactive input devices, such as mouse How is the frame buffer implemented? It is implemented as a linked list and encodes the intensity information. One way to do this is to store each scan line as a set of integer pairs. One number of each pair indicates an intensity value and the second number specifies the number of adjacent pixels on the scan line that have that intensity. This technique is called run length encoding. 2.13.3. Raster Scan Display Raster Scan methods have increasingly become the dominant technology since about 1975. These methods use the TV type raster scan. The growth in the use of such methods has been dependent on rapidly decreasing memory prices and on the availability of cheap scan generating hardware from the TV industry. The screen is coated with discrete dots of phosphor, usually called pixels, laid out in a rectangular array. The image is then determined by how each pixel is intensified. The representation of the image used in servicing the refresh system is thus an area of memory holding a value for each pixel. This memory area holding the image representation is called the frame buffer. The values in the frame buffer are held as a sequence of horizontal lines of pixel values from the top of the screen down. The scan generator then moves the beam in a series of horizontal lines with flyback (non-intensified) between each line and between the end of the frame and the beginning of the next frame. This is illustrated below.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

30

Multimedia Lab Manual

Unlike random-scan which is a line drawing device, refresh CRT is a point-plotting device. Raster displays store the display primitives (lines, characters, shaded and patterned areas) in a refresh buffer. Refresh buffer (also called frame buffer) stores the drawing primitives in terms of points and pixels components

This scan is synchronized with the access of the intensity values held in the frame buffer. The maximum number of points that can be displayed without overlap by a system is called the resolution and is quoted as the number of points per horizontal line versus the number of horizontal lines. Typical resolutions are 640*480, 1024*768, and 1280*1024. The maximum resolution is determined by the characteristics of the monitor and/or by the memory capacity available for storing the frame buffer. 2.13.4. Random Scan Systems In Random Scan Systems an application program is input and stored in the system memory along with a graphics package. Graphics commands in the application program are translated by the graphics package into a display file stored in the system memory. This display file is then accessed by the display processor to refresh the screen. The display processor cycles through each command in the display file program once during every refresh cycle. Sometimes the display processor in the random scan system is referred to as a display processing unit or a graphics controller. Graphics patterns are drawn on a random scan system by directing the electron beam along the component lines of picture. Lines are defined by the values for their coordinate endpoints, and these input coordinate values are converted

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

31

Multimedia Lab Manual

to x and y deflection voltage. A scene is then drawn one line at a time by positioning the beam to fill in the line between specified endpoints 2.13.5. Random Scan Display Random scan displays, often termed vector Vector, Stroke, and Line drawing displays, came first and are still used in some applications. Here the characters are also made of sequences of strokes (or short lines). The electron gun of a CRT illuminates straight lines in any order. The display processor repeatedly reads a variable 'display file' defining a sequence of X,Y coordinate pairs and brightness or color values, and converts these to voltages controlling the electron gun.

In random scan display an electron beam is deflected from endpoint to end-point. The order of deflection is dictated by the arbitrary order of the display commands. The display must be refreshed at regular intervals minimum of 30 Hz (fps) for flicker-free display.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

32

Multimedia Lab Manual

Ideal line drawing 2.14. Colour in Raster Graphics

Random Scan Display

To handle colour the phosphor is applied to the screen in small triads of red, green and blue phosphor dots, each triad representing one pixel. The CRT then has an electron gun for each of the additive primary colours red, green and blue. When the three primary colour dots are intensified the human visual system combines the triad of primary colours into a single perceived colour.

To ensure the beams hit the correct elements of each triad there is a thin perforated metal sheet (the shadow mask) behind the phosphor that ensures each of the three beams hits the correct element of the triad.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

33

Multimedia Lab Manual

3. FUNDAMENTAL ALGORITHMS IN COMPUTER GRAPHICS In this section we will discuss about the main algorithms used in plotting lines and circles on the screen. We will also discuss about the process of clipping and the algorithms used to implement them. 3.1. Graphics Primitives and Attributes Even the most complex computer-generated graphic images are produced by a relatively small set of Graphics Primitives. The usual sets of basic primitives provided in Graphics Packages are: a) b) c) d) e) A single point. A line with given end-points. A polyline i.e. a line joining a sequence of points. A filled polygonal area with given points as vertices. Text.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

34

Multimedia Lab Manual

There may be additional, but not essential, primitives such as rectangles, circles, curves of various types, images etc. Associated with each graphics primitive is a set of Attributes. The attributes of a primitive determine its appearance on the output device. For example a line commonly has attributes such as colour, width, style (full, dotted, dashed etc.) etc. 3.2. Scan Conversion When the process of rasterization is combined with the process of generating a picture in scan line order, it is known as scan conversion. 3.2.1. Scan converting a point A mathematical point (x, y) where x and y are real numbers within an image area, needs to be scan converted to a pixel at location (x, y). This may be done by making x to be the integer part of x, and y to be the integer part of y. In other words, x = floor(x) and y = floor(y), where function floor returns the largest integer that is less than or equal to the arguments. Doing so in essence places the origin of a continuous coordinate system for (x, y) at the lower left corner of the pixel grid in the image space. All the points that satisfy x x x + 1 and y y y + 1 are mapped to pixel (x, y). Let us take for example a point P1(1.7, 0.8). It will be represented by pixel (1, 0). Points P2 (2.2, 1.3) and P3(2.8, 1.9) are both represented by pixel (2, 1). Let us take another approach to align the integer values in the coordinate system for (x, y) with the pixel coordinates. Here we can convert (x, y) by making x = floor(x + 0.5) and y = floor(y + 0.5). This approach places the origin of the coordinate system for (x, y) at the center of pixel(0,0). All points that satisfy x- 0.5 x x+0.5 and y0.5 y y+0.5 are mapped to pixel (x, y). This means that points P1 and P2 are now both represented by pixel (2, 1), whereas point P3 is represented by pixel (3, 2). 3.2.2. Scan converting a line You know that a line in computer graphics typically refers to a line segment, which is a portion of a straight line that extends indefinitely in opposite directions. You can define a line by its two end points and by the line equation y = mx + c, where m is called the slope and c the y intercept of the line. Let the two end points of a line be P1(x1, y1) and P2(x2, y2). The line equation describes the coordinates of all the points that lie between the two endpoints.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

35

Multimedia Lab Manual

A simple approach to scan convert a line is to first scan convert P1 and P2 to pixel coordinates (x1, y1) and (x2, y2) respectively. Then let us set m = (y2- y1)/(x2- x1) and b = y1-mx1. Find |m| and if |m| 1, then for every integer value of x between and excluding x1 and x2, calculate the corresponding value of y using the equation and scan convert (x, y). If |m| >1, then for every integer value of y between and excluding y1 and y2, calculate the corresponding value of x using the equation and scan convert (x, y). 3.3. Design criteria of straight lines From geometry we know that a line, or line segment, can be uniquely specified by two points. From algebra we also know that a line can be specified by a slope, usually given the name m and a y-axis intercept called b. Generally in computer graphics, a line will be specified by two endpoints. But the slope and y-intercept are often calculated as intermediate results for use by most line-drawing algorithms. The goal of any line drawing algorithm is to construct the best possible approximation of an ideal line given the inherent limitations of a raster display. Before discussing specific line drawing algorithms, it is useful to consider general requirements for such algorithms. Let us see what are the desirable characteristics needed for these lines. The primary design criteria are as follows Straight lines appear as straight lines Straight lines start and end accurately Displayed lines should have constant brightness along their length, independent of the line length and orientation. Lines should be drawn rapidly 3.4. Line Drawing Algorithms Line drawing is our first adventure into the area of scan conversion. The need for scan conversion, or rasterization, techniques is a direct result of scanning nature of raster displays (thus the names). 3.4.1. Digital Differential Analyzer Algorithm DDA algorithm is an incremental scan conversion method. Here we perform calculations at each step using the results from the preceding step. The characteristic of the DDA algorithm is to take unit steps along one coordinate and compute the corresponding values along the other coordinate. The unit steps are always along the coordinate of greatest change, e.g. if dx = 10 and dy = 5, then we would take unit steps along x and compute the steps along y.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

36

Multimedia Lab Manual

Suppose at step i we have calculated (xi, yi) to be a point on the line. Since the next point (x i+1,y i+1) should satisfy y/ x =m where y= y i+1yi and x= x i+1xi , we have y i+1= yi + m x or x i+1=xi+ y/m These formulas are used in DDA algorithm as follows. When |m| 1, we start with x = x1 (assuming that x1 <x2) and y = y1, and set x =1( i.e., unit increment in the x direction). The y coordinate of each successive point on the line is calculated using y i+1= yi + m. When |m| >1, we start with x= x1 and y= y1 (assuming that y1 < y2), set y =1 ( i.e., unit increment in the y direction). The x coordinate of each successive point on the line is calculated using x i+1=xi+ 1/m. This process continues until x reaches x2(for m| 1 case )or y reaches y2 (for m| > 1 case ) and all points are scan converted to pixel points. The explanation is as follows: In DDA algorithm we have to find the new point xi+1 and yi+1 from the existing points xi and yi. As a first step here we identify the major axis and the minor axis of the line to be drawn. Once the major axis is found we sample the major axis at unit intervals and find the value in the other axis by using the slope equation of the line. For example if the end points of the line is given as (x1,y1)= (2,2) and (x2, y2)= (9,5). Here we will calculate y2-y1 and x2-x1 to find which one is greater. Here y2-y1 =3 and x2-x1 =7; therefore here the major axis is the x axis. So here we need to sample the x axis at unit intervals i.e. x = 1 and we will find out the y values for each x in the x axis using the slope equation.

In DDA we need to consider two cases; one is slope of the line less than or equal to one (|m| 1)and slope of the line greater than one (m| > 1). When |m| 1 means y2-y1 = x2-x1 or y2-y1 <x2-x1.In both these cases we assume x to be the major axis. Therefore we sample x axis at unit intervals and find the y values corresponding to each x value. We have the slope equation as y=mx y2-y1 = m (x2-x1) In general terms we can say that y i+1 - yi = m(x i+1 - xi ). But here x = 1; therefore the equation reduces to y i+1= yi + m = yi + dy/dx. When m| > 1 means y2-y1> x2-x1 and therefore we assume y to be the major axis. Here we sample y axis at unit intervals and find the x values corresponding to each y value.We have the slope equation as y=mx
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

37

Multimedia Lab Manual

y2-y1 = m (x2-x1) In general terms we can say that y i+1 - yi = m(x i+1 - xi ). But here y = 1; therefore the equation reduces to 1 = m(x i+1 - xi). Therefore x i+1=xi+ 1/m x i+1=xi+ dx/dy The Algorithm is given below: procedure DDA( x1, y1, x2, y2: integer); var dx, dy, steps: integer; x_inc, y_inc, x, y: real; begin dx := x2 - x1; dy := y2 - y1; if abs(dx) > abs(dy) then steps := abs(dx); {steps is larger of dx, dy} else steps := abs(dy); x_inc := dx/steps; y_inc := dy/steps; {either x_inc or y_inc = 1.0, the other is the slope} x:=x1; y:=y1; set_pixel(round(x), round(y)); for i := 1 to steps do begin x := x + x_inc; y := y + y_inc; set_pixel(round(x), round(y)); end; end; {DDA} The DDA algorithm is faster than the direct use of the line equation since it calculates points on the line without any floating point multiplication. 3.4.2. The Bresenhams Line-Drawing Algorithm Bresenham's Line drawing algorithm is an algorithm that determines which points in an n-dimensional raster should be plotted in order to form a close approximation to a straight line between two given points. The algorithm is explained as follows. Here lets scan convert a line with a positive slope where 0<m<1. Suppose that we have plotted the pixel (xk , yk ) at the kth step. At the k+1th step our aim is to plot the next point (x k+1, y k+1). Once a pixel is chosen at any step, the next pixel is either the one to its right (which constitutes a lower bound for the line)
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

38

Multimedia Lab Manual

or the one to its right and up (which constitutes a upper bound for the line) due to the limit on m. It means that it may plot the point (xk+1, yk) or it may plot the point (xk+1,yk+1). This decision is taken by considering the error term. Now how do you obtain the error term? For this let us consider the figure given below. Let us assume that the last cjosen pixel is (xk, yk). Our aim is to choose the next one between the bottom pixel S and the top pixel T. if S is chosen, we have the pixel as (xk+1, yk) and if T is chosen we have the pixel as (xk+1,yk+1). The actual y coordinate of the line at x = xk +1 is given as y = m (x k+1) + b i.e., y = m (xk+1) + b

Let us assume that the distance from S to the actual line in the y direction is s and s is given as y-yk. Let the distance from T to the actual line in the y direction be t and t is given by t = (yk +1) y. Now lets find the distance between the two terms. Lets find s-t. s-t = (y-yk) ((yk +1) y) = 2y 2yk-1 =2m (xk+1) + 2b - 2yk-1 Substitute m by y/ x = 2 y/ x(xk+1) + 2b - 2yk-1 Here the decision variable Pk is given as x(s-t).By looking into the sign of Pk we will determine which pixel has to be plotted. What gives

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

39

Multimedia Lab Manual

the sign of Pk? Pk is the product of two terms x and (s-t). Since x is always positive, the sign of Pk is determined solely by the term (s-t). If Pk is +ve , it means that s is greater than t. This in turn means that the distance from S to the actual line is greater than the distance between T and the actual line. Here we are looking for a pixel with is closer to the actual line. So now we can conclude that T lies more close to the actual line than S. Therefore we plot T here. If Pk is -ve , it means that t is greater than s. This in turn means that the distance from T to the actual line is greater than the distance between S and the actual line. We can conclude that S lies more close to the actual line than T. Therefore we plot S here. After simplifying the equation for the error term (Pk = x(s-t)), the error term at the k th step is given as Pk = 2 y xk -2 x yk + C where C = 2 y + x(2b -1) Similarly we can find the error term at k+1th step. The error term at the k+1 th step is given as P P P
k+1 k+1 k+1

= 2 y x k+1 -2 x y k+1 + C - Pk = 2 y(x k+1 - xk) - 2 x (y k+1 - yk ) = Pk + 2 y(x k+1 - xk) - 2 x (y k+1 - yk )

Here we know x k+1 = xk + 1, therefore we have P k+1 = Pk + 2 y- 2 x (y k+1 - yk ) Here we have two cases. If Pk is +ve , T is chosen and when T is chosen y k+1 = yk +1. So the equation reduces to P k+1 = Pk + 2 y- 2 x On the other hand, if Pk is -ve , S is chosen and when S is chosen y k+1 = yk. Then the equation reduces to P k+1 = Pk + 2 y Summarizing the above concepts we can say that If Pk is +ve P k+1 = Pk + 2 y- 2 x If Pk is ve P k+1 = Pk + 2 y The algorithm is given as follows Function line(x0, x1, y0, y1) boolean steep := abs(y1 - y0) > abs(x1 - x0) if steep then
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

40

Multimedia Lab Manual

swap(x0, y0) swap(x1, y1) if x0 > x1 then swap(x0, x1) swap(y0, y1) int deltax := x1 - x0 int deltay := abs(y1 - y0) real error := 0 real deltaerr := deltay / deltax int y := y0 if y0 < y1 then ystep := 1 else ystep := -1 for x from x0 to x1 if steep then plot(y,x) else plot(x,y) error := error + deltaerr if error 0.5 y := y + ystep error := error - 1.0

3.5. Scan converting a circle Circles have the property of being highly symmetrical, which is handy when it comes to drawing them on a display screen. We know that there are 360 degrees in a circle. First we see that a circle is symmetrical about the x axis, so only the first 180 degrees need to be calculated. Next we see that it's also symmetrical about the y axis, so now we only need to calculate the first 90 degrees. Finally we see that the circle is also symmetrical about the 45 degree diagonal axis, so we only need to calculate the first 45 degrees We only need to calculate the values on the border of the circle in the first octant. The other values may be determined by symmetry. Assume a circle of radius r with center at (0,0).

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

41

Multimedia Lab Manual

Procedure Circle_Points(x,y: Integer); Begin Plot(x,y); Plot(y,x); Plot(y,-x); Plot(x,-y); Plot(-x,-y); Plot(-y,-x); Plot(-y,x); Plot(-x,y) End;

3.5.1. The Bresenhams Circle-Drawing Algorithm Bresenham's circle algorithm calculates the locations of the pixels in the first 45 degrees. It assumes that the circle is centered on the origin. So for every pixel (x, y) it calculates, we draw a pixel in each of the eight octants of the circle. This is done till when the value of the y coordinate equals the x coordinate. PutPixel PutPixel PutPixel PutPixel PutPixel PutPixel PutPixel PutPixel (CenterX (CenterX (CenterX (CenterX (CenterX (CenterX (CenterX (CenterX + X, Center Y + Y) + X, Center Y - Y) - X, Center Y + Y) - X, Center Y - Y) + Y, Center Y + X) + Y, Center Y - X) - Y, Center Y + X) - Y, Center Y - X)

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

42

Multimedia Lab Manual

The algorithm is given as follows: Given a radius for the circle we perform this initialization: d := 3 - (2 * RADIUS) x := 0 y := RADIUS Now for each pixel we do the following operations: Draw the 8 circle pixels if d < 0 then d := d + (4 * x) + 6 else begin d := d + 4 * (x - y) + 10 y := y - 1; end; 3.5.2. Mid point circle algorithm In midpoint circle algorithm, we sample 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), this algorithm first calculate pixel positions around a circle path centered at the coordinate origin (0, 0). Then each calculated position (x, y) is moved to its proper position by adding xc to x and yc to y. Along the circle section from x = 0 to x = y in the first quadrant, the slope of the curve varies from 0 to -1. Therefore, we can take steps in the positive x direction over this octant and use a decision parameter to determine which of the two possible y positions is closer to the circle path at each step. Positions of the other seven octants are then obtained by symmetry. f circle (x, y) = x2 + y2 r2 Any point on the boundary of the circle with radius r satisfies the equation f circle (x, y) = 0. If the point is in the interior of the circle, the circle function is negative. If the point is outside the circle, the circle function is positive. This test is performed for the mid positions between pixels near the circle path at each sampling step.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

43

Multimedia Lab Manual

Assuming we have plotted the pixel at (Xk, Yk), we next need to determine whether the pixel at position (Xk +1, Yk -1) is closer to the circle. For that we calculate the circle function at the midpoint between these points. Pk = f circle (Xk +1, Yk - ) If Pk < 0, this midpoint is inside the circle and the pixel on the scan line Yk, is closer to the circle boundary, and we select the pixel on the scan line Yk -1. Successive parameters are obtained using incremental calculations. The initial decision parameter is obtained by evaluating the circle function at the staring position (X0, Y0) = (0, r). = f circle (1, r ) = 1 +(r )2 - r 2 = 5/4 - r The algorithm is given as follows: Initialize x=0, y= r and p =1-r For x<=y do the following Plot the pixel (x,y ) If (p <0) p = p+2x + 3 Else p=p + 2(x-y)+ 5 Decrement the value of y

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

44

Multimedia Lab Manual

4. BASIC TRANSFORMATIONS Let us now discuss about the fundamental 2D transformations in computer graphics. 4.1. Transformation Principles You can say that transformations are a fundamental part of computer graphics. Transformations are used to position objects, to shape objects, to change viewing positions, and even to change how something is viewed (e.g. the type of perspective that is used).Putting it in other words a transformation is a function that maps every position (x, y) into a new position (x', y'). Instead of applying the transformation to every point in every line that makes up the object, we simply apply the function to the objects vertices and then draw new lines between the resulting new endpoints. Two aspects emphasized: of the formulation of transformation should be

A transformation is a single mathematical entity and such can be denoted by a single name or symbol. Two transformations can be combined, or concatenated, to yield a single transformation with the same effect as the sequential application of the original two. Thus transformation A might be a translation and transformation B a scaling. The concatenation property allows us to determine a transformation C = AB whose effect is to translate and then scale.

Each of the transformations is used to generate a new point (x, y) from the coordinates of a point to (x, y) in the original picture description. If the original definition includes a line, it suffices to apply the transformation to the endpoints of the line and display the line between the two transformed endpoints. 4.2. World and Modeling Coordinates Before going into details let us discuss on 3D coordinate systems. As you all know in 3D graphics, one uses a coordinate system in order to represent points in space by a series of numbers. Usually Cartesian coordinates are used, as these are the easiest to work with. It defines three straight fixed perpendicular lines called axes (usually referred to as X, Y, and Z). A point in 3D can be described by three numbers, which indicate the distance of the point from each axis. This is represented by an ordered triple: (x,y,z). However, there is not just one
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

45

Multimedia Lab Manual

Cartesian coordinate system. There are many, which have their origins in different places and their axes aligned with different things. 4.2.1. World Coordinates The world coordinate system forms the "base" on which you can think of all other coordinates being defined. Usually, its origin is at the center of your game world, and its axes might be aligned with directions like north/south, east/west, and up/down. (For example, it is very common for the X axis to be east, the Y axis to be north, and the Z axis to be up. Another way is for X to be east, Y to be up, and Z to be south.) This is the coordinate system in which most of your level geometry- as rooms, hallways, and landscapes - will probably be defined 4.2.2. Modeling coordinates Modeling coordinates is the one in all drawing primitives do their drawing. The user can select the position and orientation of the modeling space with regard to the world space by means of translations, rotations, scales, or generalized transformations. The relation between modeling coordinates and world coordinates is determined by the modeling matrix. Modeling coordinates are a useful conceptual device when drawing complex or repetitive scenes. For instance, a paper clip can be defined once in modeling coordinates, and then drawn hundreds of times by moving the modeling coordinate around in world space. 4.3. Basic Types of Transformation There are three basic 2D Transformation functions: Translation Scaling Rotation Now lets consider the figures given below. Here we are trying to transform a picture in the world coordinate into an object in the modeling coordinates.

Modeling Coordinates

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

46

Multimedia Lab Manual

y x

Scale Translate

Scale Rotate Translate

World Coordinates
Figure 1

Modeling Coordinates

y x

Lets look at this in detail.

World Coordinates
Figure 2

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

47

Multimedia Lab Manual

Modeling Coordinates

y x

Initial location at (0, 0) with x- and y-axes aligned

World Coordinates
Figure 3

Modeling Coordinates

y x

Scale .3, .3

World Coordinates
Figure 4 : Scaling Transformation is done

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

48

Multimedia Lab Manual

Modeling Coordinates

y x

Rotate -90

World Coordinates
Figure 5: Rotating the object by 90o

Modeling Coordinates

y x

Translate 5, 3 World Coordinates

Figure 6: Translating the object to a new position


Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

49

Multimedia Lab Manual

4.3.1. Translation Translations with 2 dimensional points are not very difficult. All we need to do is determine how much we want to move the object in the x and y direction, and add those variables to the point's x and y respectively Translation means a shift by Tx in the x direction and Ty in the y direction is x' = x + Tx y' = y + Ty Tx and Ty are translation amounts in the x direction in the y direction respectively. For example let us see the figure given below. An object at position (4,5) and (7,5) has been shifted to a new position (7,1) and (10,1)

4.3.2. Scaling A scaling by Sx in the x direction and Sy in the y directions about the origin is x' = Sx x y' = Sy y If Sx and Sy are not equal this results in a stretching along the axis of the larger scale factor. To scale about a particular point, first translate to the origin, scale, and translate back to the original position. For example, to scale about the point (x0,y0) x' = x0 + Sx ( x - x0 ) y' = y0 + Sy ( y - y0 )
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

50

Multimedia Lab Manual

In other words scaling a coordinate means multiplying each of its components by a scalar. Uniform scaling means this scalar is the same for all components. For example, we have an object initially at (4, 5) and (7, 5). A scaling Factor of is applied to this object. Look at the figure given below

Note that the house changes position, since the scaling is about the origin. If scaling were uniform, the amount of scaling in each dimension would be equal. 4.3.3. Rotation Rotation about the origin by an angle A in a clockwise direction is x' = x cos(A) + y sin(A) y' = y cos(A) - x sin(A) To rotate about a particular point apply the same technique as described for scaling, translate the coordinate system to the origin, rotate, and the translate back. Putting it in other words to rotate about another point, first translate the point to the origin, rotate, and then translate back. The following transforms perform rotation:

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

51

Multimedia Lab Manual

The angle of rotation is about the origin. Positive angles are measured counterclockwise. You should be able to reformulate the rotational transformations for negative angles also. Use the identities:

Proof: Consider:

By simple trigonometry: x = r cos and y= r cos x = r cos( + ) = r cos cos r sin sin y = r sin( + ) = r cos sin + r sin cos By substitution x = x cos - y sin y = x sin + y cos 4.4. Matrix Representation of Transformations The matrix representation of different transformations are given below Translation
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

52

Multimedia Lab Manual

Scaling

Rotation

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

53

Multimedia Lab Manual

5. ANIMATION Computer animation generally refers to any time sequence of visual changes in a scene. In addition to changing object position with translation or rotations, computer-generated animations could display time variations in object size, color, transparency or surface texture.

5.1. Design of an animation sequence In general an animation sequence is designed with the following steps a) Storyboard layout b) Object definitions c) Key-frame specifications
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

54

Multimedia Lab Manual

d) Generation of in between frames The storyboard is an outline of the action. It defines motion sequences as a set of basic events that are to take place. Depending on the type of animation to be produced, the storyboard could consist of a set of rough sketches or it could be a list of basic ideas for the motion. An object definition is given for each participant in the action. Objects can be defined in terms of basic shapes, such as polygon or splines. In addition, associated sets of movements are also specified along with the shape. A key frame is a detailed drawing of the scene at a certain time in the animation sequence. Within each key frame each object is positioned according to the time for that frame. In-betweens are intermediate frames between the key frames. The number of In-betweens needed is determined by the media to be used to display animation. Film requires 24 frames per second, and graphics terminal are refreshed at the rate of 30 to 60 frames per second. Typically time intervals for the motion are set up so that there are from three to five In-betweens for each pair of key frames. When someone creates a 3D animation on a computer, they usually don't specify the exact position of any given object on every single frame. They create key frames. Key frames are important frames during which an object changes its size, direction, shape or other properties. The computer then figures out all the in between frames and saves an extreme amount of time for the animator.

Two key frames drawn by the user

In between frames generated by the computer

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

55

Multimedia Lab Manual

On raster scan systems we can generate real time animation in limited applications using raster operations. A simple method for translation in the xy plane is to transfer a rectangular blocks of pixels through arbitrary angles using anti-aliasing procedures. To rotate a block of pixels we need to determine the percent of area coverage for those pixels that overlap the rotated block. Sequences of raster operations can be executed to produce real time animation of either two-dimensional or three-dimensional objects, as long as we restrict the animation to motions in the projection plane. Then no viewing or visible surface algorithms need be invoked. 5.2. Morphing Transformation of object shapes from one form to another is called morphing. We generate set of in-betweens from the specification of two or more key frames. Given the animation paths we can interpolate the positions of individual objects between any two times or key frames. With complex object transformations the shapes of the object may change over time. If all surfaces are described with polygon meshes then the number of edges per polygon can change from one frame to the next. Thus the total number of line segments can be different in different frames. Transformation of object shapes from one form to another is called morphing. Morphing methods can be applied to any motion or transition involving a change of shape. Given two key frames for an object transformation we first adjust the object specification in one if the frames so that the number of polygon edges (or the number of vertices) is the same for the two frames. This is illustrated below

Frame K

Frame K+1

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

56

Multimedia Lab Manual

Frame K

Halfway Frame

Frame K+1

A straight-line segment in key frame k is transformed into two line segments in key frame k+1. Since key frame k+1 has an extra vertex, we add a vertex between 1 and 2 in key frame K to balance the number of vertices and edges in the two key frames. Using linear interpolation to generate the in betweens we transition the added vertex in key frame k into vertex 3 along the straight-line path as shown.We can state general preprocessing rules for equalizing key frames in terms of either the number of edges or the number of vertices to be added to a key frame. Case 1: Equalizing edge count. Let the parameters Lk and Lk+1 denote the number of line segments in two consecutive frames. We then define Lmax = max(Lk, Lk+1) Lmin = min(Lk, Lk+1) Ne = Lmax mod Lmin Ns = int(Lmax/ Lmin) Then the preprocessing is accomplished by 1. Dividing the Ne edges of keyframemin into Ns sections. 2. Dividing the remaining lines of keyframemin into Ns sections Case 2: Equalizing vertex count Let the parameters be Vk and Vk+1 denote the number of vertices in the two consecutive frames. We define Vmax = max(Vk, Vk+1) Vmin = min(Vk, Vk+1) Nls = (Vmax-1) mod (Vmin-1) Np = int ((Vmax-1) / (Vmin-1)) Preprocessing using vertex count is performed by
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

57

Multimedia Lab Manual

1. 2.

Adding Np points to Nls line sections of keyframemin Adding Np-1 points to the remaining edges of keyframemin

6. GRAPHIC FUNCTIONS Here let us get familiarized with some of the important functions used in graphics.h header. These functions are useful in creating animation sequences. The functions we are going to discuss are listed below:

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

58

Multimedia Lab Manual

arc circle cleardevice closegraph delay detectgraph drawpoly ellipse fillellipse fillpoly floodfill getarccoords getaspectratio getbkcolor getcolor getpixel getx gety graphresult initgraph kbhit line pieslice putpixel rectangle sector setcolor setfillpattern 1. setfillstyle setgraphbufsize setlinestyle Now let us examine each of them in detail. 1. arc
Syntax

#include <graphics.h> void arc(int x, int y, int stangle, int endangle, int radius);
Description

arc draws a circular arc in the current drawing color centered at (x,y) with a radius given by radius. The arc travels from stangle to endangle. If stangle equals 0 and endangle equals 360, the call to arc draws a complete circle.The angle for arc is reckoned counterclockwise, with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

59

Multimedia Lab Manual

The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used.If you are using a CGA in high resolution mode or a monochrome graphics adapter, the examples in online Help that show how to use graphics functions might not produce the expected results. If your system runs on a CGA or monochrome adapter, pass the value 1 to those functions that alter the fill or drawing color (setcolor, setfillstyle, and setlinestyle, for example), instead of a symbolic color constant (defined in graphics.h). 2. circle
Syntax

#include <graphics.h> void circle(int x, int y, int radius);


Description

circle draws a circle in the current drawing color with its center at (x, y) and the radius given by radius. The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used. If your circles are not perfectly round, adjust the aspect ratio.

3. cleardevice
Syntax

#include <graphics.h> void cleardevice(void);


Description

cleardevice erases (that is, fills with the current background color) the entire graphics screen and moves the CP (current position) to home (0,0). 4. closegraph
Syntax

#include <graphics.h> void closegraph(int wid=ALL_WINDOWS);


Description

closegraph deallocates all memory allocated by the graphics system, then restores the screen to the mode it was in before you called initgraph. (The graphics system deallocates memory, such as the drivers, fonts, and an internal buffer, through a call to _graphfreemem.) . It doesnt have a return value.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

60

Multimedia Lab Manual

5. detectgraph
Syntax

#include <graphics.h> void detectgraph(int *graphdriver, int *graphmode);


Description

detectgraph detects your system's graphics adapter and chooses the mode that provides the highest resolution for that adapter. If no graphics hardware is detected, *graphdriver is set to grNotDetected (-2), and graphresult returns grNotDetected (-2). *graphdriver is an integer that specifies the graphics driver to be used. You can give it a value using a constant of the graphics_drivers enumeration type defined in graphics.h and listed as follows:
graphics_drivers constant DETECT CGA MCGA EGA EGA64 EGAMONO IBM8514 HERCMONO ATT400 VGA PC3270 Numeric value 0 (requests autodetect) 1 2 3 4 5 6 7 8 9 10

*graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT; in which case, *graphmode is set to the highest resolution available for the detected driver). You can give *graphmode a value using a constant of the graphics_modes enumeration type defined in graphics.h and listed as follows. Driver CGA graphics_mo Value Palett x Rows de e 320 x CGAC0 0 C0 200 320 x CGAC1 1 C1 200 CGAC2 2 320 x C2 Pages 1 1 1
61

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

CGAC3 CGAHI

3 4

200 320 200 640 200 320 200 320 200 320 200 320 200 640 200 640 480 640 200 640 350 640 200 640 350 640 350 640 350 720 348 320 200 320 200

x x

C3

2 color 1

MCGA

MCGAC0

C0

MCGAC1 MCGAC2 MCGAC3 MCGAMED MCGAHI

1 2 3 4 5

x x x x x

C1 C2 C3

1 1 1

2 color 1 2 color 1

EGA

EGALO

x 16 color x 16 color x 16 color x

EGAHI

EGA64

EGA64LO

EGA64HI

4 color 1

EGA-MONO EGAMONOHI EGAMONOHI

3 3

x x

2 color 1 w/64K 2 color 2 w/256K

HERC

HERCMONOHI 0

2 color 2

ATT400

ATT400C0 ATT400C1

0 1

x x

C0 C1

1 1
62

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

ATT400C2 ATT400C3 ATT400MED ATT400HI

2 3 4 5

320 200 320 200 640 200 640 400 640 200 640 350 640 480 720 350 640 480 1024 768

x x x x

C2 C3

1 1

2 color 1 2 color 1

VGA

VGALO VGAMED VGAHI

0 1 2

x 16 color x 16 color x 16 color x

2 2 1

PC3270

PC3270HI

2 color 1

IBM8514

IBM8514HI IBM8514LO

0 0

x 256 color x 256 color

? ?

Note: The main reason to call detectgraph directly is to override the graphics mode that detectgraph recommends to initgraph. 6. delay
Syntax

#include "graphics.h" void delay(int millisec);


Description

The delay function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function pauses the computation for the specified number of milliseconds. It doesnt have a return value. 7. drawpoly
Syntax

#include <graphics.h> void drawpoly(int numpoints, int *polypoints);

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

63

Multimedia Lab Manual

Description

drawpoly draws a polygon with numpoints points, using the current line style and color. *polypoints points to a sequence of (numpoints * 2) integers. Each pair of integers gives the x- and y-coordinates of a point on the polygon. In order to draw a closed figure with n vertices, you must pass n + 1 coordinates to drawpoly where the nth coordinate is equal to the 0th. 8. ellipse
Syntax

#include <graphics.h> void ellipse(int x, int y, int stangle, int endangle, int xradius, int yradius);
Description

ellipse draws an elliptical arc in the current drawing color with its center at (x,y) and the horizontal and vertical axes given by xradius and yradius, respectively. The ellipse travels from stangle to endangle. If stangle equals 0 and endangle equals 360, the call to ellipse draws a complete ellipse.The angle for ellipse is reckoned counterclockwise, with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on.The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used.

9. fillellipse
Syntax

#include <graphics.h> void fillellipse(int x, int y, int xradius, int yradius);


Description

Draws an ellipse using (x,y) as a center point and xradius and yradius as the horizontal and vertical axes, and fills it with the current fill color and fill pattern. 10. fillpoly
Syntax

#include <graphics.h> void fillpoly(int numpoints, int *polypoints);


Description

fillpoly draws the outline of a polygon with numpoints points in the current line style and color (just as drawpoly does), then fills the polygon using the current fill pattern and fill color.polypoints points to a sequence of (numpoints * 2) integers. Each pair of integers gives the x- and ycoordinates of a point on the polygon.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

64

Multimedia Lab Manual

11. floodfill
Syntax

#include <graphics.h> void floodfill(int x, int y, int border);


Description

floodfill fills an enclosed area on bitmap devices. (x,y) is a "seed point" within the enclosed area to be filled. The area bounded by the color border is flooded with the current fill pattern and fill color. If the seed point is within an enclosed area, the inside will be filled. If the seed is outside the enclosed area, the exterior will be filled. Use fillpoly instead of floodfill whenever possible so that you can maintain code compatibility with future versions.floodfill does not work with the IBM-8514 driver.
Return Value

If an error occurs while flooding a region, graphresult returns a value of -7.

12. getarccoords
Syntax

#include <graphics.h> void getarccoords(struct arccoordstype *arccoords);


Description

getarccoords fills in the arccoordstype structure pointed to by arccoords with information about the last call to arc. The arccoordstype structure is defined in graphics.h as follows: struct arccoordstype { int x, y; int xstart, ystart, xend, yend; }; The members of this structure are used to specify the center point (x,y), the starting position (xstart, ystart), and the ending position (xend, yend) of the arc. These values are useful if you need to make a line meet at the end of an arc.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

65

Multimedia Lab Manual

13. getaspectratio
Syntax

#include <graphics.h> void getaspectratio(int *xasp, int *yasp);


Description

The y aspect factor, *yasp, is normalized to 10,000. On all graphics adapters except the VGA, *xasp (the x aspect factor) is less than *yasp because the pixels are taller than they are wide. On the VGA, which has "square" pixels, *xasp equals *yasp. In general, the relationship between *yasp and *xasp can be stated as *yasp = 10,000 *xasp <= 10,000 getaspectratio gets the values in *xasp and *yasp. 14. getcolor
Syntax

#include <graphics.h> int getcolor(void);


Description

Return Value

getcolor returns the current drawing color. The drawing color is the value to which pixels are set when lines and so on are drawn. For example, in CGAC0 mode, the palette contains four colors: the background color, light green, light red, and yellow. In this mode, if getcolor returns 1, the current drawing color is light green. getcolor returns the current drawing color. 15. getbkcolor
Syntax

#include <graphics.h> int getbkcolor(void);


Description

getbkcolor returns the current background color


Return Value

getbkcolor returns the current background color.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

66

Multimedia Lab Manual

16. getpixel
Syntax

#include <graphics.h> unsigned getpixel(int x, int y);


Description

getpixel gets the color of the pixel located at (x,y).


Return Value

getpixel returns the color of the given pixel.

17. getx
Syntax

#include <graphics.h> int getx(void);


Description

getx finds the current graphics position's x-coordinate. The value is viewport-relative.
Return Value

getx returns the x-coordinate of the current position. 18. gety


Syntax

#include <graphics.h> int gety(void);


Description

gety returns the current graphics position's y-coordinate. The value is viewport-relative. 19. graphresult
Syntax

#include <graphics.h> int graphresult(void);


Description

graphresult returns the error code for the last graphics operation that reported an error and resets the error level to grOk. The following table lists the error codes returned by graphresult. The enumerated type graph_errors defines the errors in this table. graph_errors is declared in graphics.h.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

67

Multimedia Lab Manual

code 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 -12 -13 -14 -15 -18

Corresponding error message string grOk No error (BGI) graphics not installed (use grNoInitGraph initgraph) grNotDetected Graphics hardware not detected grFileNotFound Device driver file not found grInvalidDriver Invalid device driver file Not enough memory to load grNoLoadMem driver grNoScanMem Out of memory in scan fill grNoFloodMem Out of memory in flood fill grFontNotFound Font file not found constant grNoFontMem grInvalidMode Not enough memory to load font Invalid graphics mode for selected driver Graphics error Graphics I/O error Invalid font file

grError grIOerror grInvalidFont grInvalidFontNu Invalid font number m grInvalidDevice Invalid device number Num grInvalidVersion Invalid version number

Note: The variable maintained by graphresult is reset to 0 after graphresult has been called. Therefore, you should store the value of graphresult into a temporary variable and then test it.
Return Value

graphresult returns the current graphics error number, an integer in the range -15 to 0; grapherrormsg returns a pointer to a string associated with the value returned by graphresult. 20. initgraph
Syntax

#include <graphics.h> void initgraph(int *graphdriver, int *graphmode, char *pathtodriver);


Description
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

68

Multimedia Lab Manual

initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver), and putting the system into graphics mode.To start the graphics system, first call the initgraph function. initgraph loads the graphics driver and puts the system into graphics mode. You can tell initgraph to use a particular graphics driver and mode, or to autodetect the attached video adapter at run time and pick the corresponding driver. If you tell initgraph to autodetect, it calls detectgraph to select a graphics driver and mode. initgraph also resets all graphics settings to their defaults (current position, palette, color, viewport, and so on) and resets graphresult to 0.Normally, initgraph loads a graphics driver by allocating memory for the driver (through _graphgetmem), then loading the appropriate .BGI file from disk. As an alternative to this dynamic loading scheme, you can link a graphics driver file (or several of them) directly into your executable program file. pathtodriver specifies the directory path where initgraph looks for graphics drivers. initgraph first looks in the path specified in pathtodriver, then (if they are not there) in the current directory. Accordingly, if pathtodriver is null, the driver files (*.BGI) must be in the current directory. This is also the path settextstyle searches for the stroked character font files (*.CHR). *graphdriver is an integer that specifies the graphics driver to be used. You can give it a value using a constant of the graphics_drivers enumeration type, which is defined in graphics.h and listed below. graphics_drivers constant DETECT CGA MCGA EGA EGA64 EGAMONO IBM8514 HERCMONO ATT400 VGA Numeric value 0 (requests autodetect) 1 2 3 4 5 6 7 8 9
69

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

PC3270

10

*graphmode is an integer that specifies the initial graphics mode (unless *graphdriver equals DETECT; in which case, *graphmode is set by initgraph to the highest resolution available for the detected driver). You can give *graphmode a value using a constant of the graphics_modes enumeration type, which is defined in graphics.h and listed below. graphdriver and graphmode must be set to valid values from the following tables, or you will get unpredictable results. The exception is graphdriver = DETECT. Palette listings C0, C1, C2, and C3 refer to the four predefined four-color palettes available on CGA (and compatible) systems. You can select the background color (entry #0) in each of these palettes, but the other colors are fixed. Palette Number 0 1 2 3 Three Colors LIGHTGREEN LIGHTCYAN GREEN CYAN LIGHTRED LIGHTMAGENTA RED MAGENTA YELLOW WHITE BROWN LIGHTGRAY

After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to the current graphics mode. Graphics Driver CGA Column s graphics_mo Value Palett x Rows de e 320 x CGAC0 0 C0 200 320 x CGAC1 1 C1 200 320 x CGAC2 2 C2 200 320 x CGAC3 3 C3 200 640 x CGAHI 4 2 color 200 Pages 1 1 1 1 1

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

70

Multimedia Lab Manual

MCGA

MCGAC0

320 200 320 200 320 200 320 200 640 200 640 480 640 200 640 350 640 200 640 350 640 350 640 350 720 348 320 200 320 200 320 200 320 200 640

C0

MCGAC1 MCGAC2 MCGAC3 MCGAMED MCGAHI

1 2 3 4 5

x x x x x

C1 C2 C3

1 1 1

2 color 1 2 color 1

EGA

EGALO

x 16 color x 16 color x 16 color x

EGAHI

EGA64

EGA64LO

EGA64HI

4 color 1

EGA-MONO EGAMONOHI EGAMONOHI

3 3

x x

2 color 1 w/64K 2 color 2 w/256K

HERC

HERCMONOHI 0

2 color 2

ATT400

ATT400C0 ATT400C1 ATT400C2 ATT400C3 ATT400MED

0 1 2 3 4

x x x x

C0 C1 C2 C3

1 1 1 1

x 2 color 1
71

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

ATT400HI

200 640 400 640 200 640 350 640 480 720 350 640 480 1024 768

2 color 1

VGA

VGALO VGAMED VGAHI

0 1 2

x 16 color x 16 color x 16 color x

2 2 1

PC3270

PC3270HI

2 color 1

IBM8514

IBM8514HI IBM8514LO

0 0

x 256 color x 256 color

? ?

Return Value

initgraph always sets the internal error code; on success, it sets the code to 0. If an error occurred, *graphdriver is set to -2, -3, -4, or -5, and graphresult returns the same value as listed below: Constant Number Meaning Name Cannot detect a graphics grNotDetected -2 card grFileNotFound -3 Cannot find driver file grInvalidDriver -4 Invalid driver Insufficient memory to grNoLoadMem -5 load driver 21. kbhit
Syntax

#include "graphics.h" int kbhit(void);


Description

The kbhit function is available in the winbgim implementation of BGI graphics. You do not need to include conio.h; just include graphics.h. The function returns true (non-zero) if there is a character in the input buffer ready to read. Otherwise it returns false. In order to work, the user must click in the graphics window (i.e., the Windows focus must be in the graphics window).
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

72

Multimedia Lab Manual

Return Value

True (non-zero) if there is a character in the input buffer, otherwise false. 22. line
Syntax

#include <graphics.h> void line(int x1, int y1, int x2, int y2);
Description

line draws a line in the current color, using the current line style and thickness between the two points specified, (x1,y1) and (x2,y2), without updating the current position (CP). 23. pieslice
Syntax

#include <graphics.h> void pieslice(int x, int y, int stangle, int endangle, int radius);
Description

pieslice draws and fills a pie slice centered at (x,y) with a radius given by radius. The slice travels from stangle to endangle. The slice is outlined in the current drawing color and then filled using the current fill pattern and fill color.The angles for pieslice are given in degrees. They are measured counterclockwise, with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on. If you're using a CGA or monochrome adapter, the examples in online Help that show how to use graphics functions might not produce the expected results. If your system runs on a CGA or monochrome adapter, use the value 1 (one) instead of the symbolic color constant, and see the second example under arc whis shows how to use the pieslice function. 24. putpixel
Syntax

#include <graphics.h> void putpixel(int x, int y, int color);


Description

putpixel plots a point in the color defined by color at (x,y).

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

73

Multimedia Lab Manual

25. rectangle
Syntax

#include <graphics.h> void rectangle(int left, int top, int right, int bottom);
Description

rectangle draws a rectangle in the current line style, thickness, and drawing color.(left,top) is the upper left corner of the rectangle, and (right,bottom) is its lower right corner. 26. sector
Syntax

#include <graphics.h> void sector(int x, int y, int stangle, int endangle, int xradius, int yradius);
Description

Draws and fills an elliptical pie slice using (x,y) as the center point, xradius and yradius as the horizontal and vertical radii, respectively, and drawing from stangle to endangle. The pie slice is outlined using the current color, and filled using the pattern and color defined by setfillstyle or setfillpattern. The angles for sector are given in degrees. They are measured counter-clockwise with 0 degrees at 3 o'clock, 90 degrees at 12 o'clock, and so on.If an error occurs while the pie slice is filling, graphresult returns a value of -6 (grNoScanMem).

27. setfillpattern
Syntax

#include <graphics.h> void setfillpattern(char *upattern, int color);


Description

setfillpattern is like setfillstyle, except that you use it to set a user-defined 8x8 pattern rather than a predefined pattern. upattern is a pointer to a sequence of 8 bytes, with each byte corresponding to 8 pixels in the pattern. Whenever a bit in a pattern byte is set to 1, the corresponding pixel is plotted. 28. setfillstyle
Syntax
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

74

Multimedia Lab Manual

#include <graphics.h> void setfillstyle(int pattern, int color);


Description

setfillstyle sets the current fill pattern and fill color. To set a user-defined fill pattern, do not give a pattern of 12 (USER_FILL) to setfillstyle; instead, call setfillpattern.If invalid input is passed to setfillstyle, graphresult returns -1(grError), and the current fill pattern and fill color remain unchanged. Note: The EMPTY_FILL style is like a solid fill using the current background color (which is set by setbkcolor). 29. setgraphbufsize
Syntax

#include <graphics.h> unsigned setgraphbufsize(unsigned bufsize);


Description

Some of the graphics routines (such as floodfill) use a memory buffer that is allocated when initgraph is called and released when closegraph is called. The default size of this buffer, allocated by _graphgetmem, is 4,096 bytes. You might want to make this buffer smaller (to save memory space) or bigger (if, for example, a call to floodfill produces error -7: Out of flood memory).setgraphbufsize tells initgraph how much memory to allocate for this internal graphics buffer when it calls _graphgetmem. You must call setgraphbufsize before calling initgraph. Once initgraph has been called, all calls to setgraphbufsize are ignored until after the next call to closegraph.
Return Value

setgraphbufsize returns the previous size of the internal buffer. 30. setcolor
Syntax

#include <graphics.h> void setcolor(int color);


Description

setcolor sets the current drawing color to color, which can range from 0 to getmaxcolor. The current drawing color is the value to which pixels are set when lines, and so on are
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

75

Multimedia Lab Manual

drawn. The drawing colors shown below are available for the CGA and EGA, respectively. Palette Three Colors Number 0 LIGHTGREEN LIGHTRED 1 LIGHTCYAN LIGHTMAGENTA 2 GREEN RED 3 CYAN MAGENTA Name Value BLACK 0 BLUE 1 GREEN 2 CYAN 3 RED 4 MAGENTA 5 BROWN 6 LIGHTGRAY 7 DARKGRAY 8 LIGHTBLUE 9 LIGHTGREEN 10 LIGHTCYAN 11 LIGHTRED 12 LIGHTMAGENTA 13 YELLOW 14 WHITE 15

YELLOW WHITE BROWN LIGHTGRAY

You select a drawing color by passing either the color number itself or the equivalent symbolic name to setcolor. For example, in CGAC0 mode, the palette contains four colors: the background color, light green, light red, and yellow. In this mode, either setcolor(3) or setcolor(CGA_YELLOW) selects a drawing color of yellow. 31. setlinestyle
Syntax

#include <graphics.h> void setlinestyle(int linestyle, thickness);


Description

unsigned

upattern,

int

setlinestyle sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

76

Multimedia Lab Manual

The linesettingstype structure is defined in graphics.h as follows: struct linesettingstype { int linestyle; unsigned upattern; int thickness; }; linestyle specifies in which of several styles subsequent lines will be drawn (such as solid, dotted, centered, dashed). The enumeration line_styles, which is defined in graphics.h, gives names to these operators: Name SOLID_LINE DOTTED_LINE CENTER_LINE DASHED_LINE USERBIT_LINE Value 0 1 2 3 4 Description Solid line Dotted line Centered line Dashed line User-defined line style

thickness specifies whether the width of subsequent lines drawn will be normal or thick. Name NORM_WIDTH THICK_WIDTH Value Descripti on 1 pixel 1 wide 3 pixels 3 wide

upattern is a 16-bit pattern that applies only if linestyle is USERBIT_LINE (4). In that case, whenever a bit in the pattern word is 1, the corresponding pixel in the line is drawn in the current drawing color. For example, a solid line corresponds to a upattern of 0xFFFF (all pixels drawn), and a dashed line can correspond to a upattern of 0x3333 or 0x0F0F. If the linestyle parameter to setlinestyle is not
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

77

Multimedia Lab Manual

USERBIT_LINE (in other words, if it is not equal to 4), you must still provide the upattern parameter, but it will be ignored. Note: The linestyle parameter does not affect arcs, circles, ellipses, or pie slices. Only the thickness parameter is used.
Return Value

If invalid input is passed to setlinestyle, graphresult returns -11, and the current line style remains unchanged.

7. WORKED OUT EXERCISES 7.1. DDA algorithm


Problem definition

Implement the DDA line drawing algorithm.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

78

Multimedia Lab Manual

Algorithm

a) Start. b) Get the end points of the line. c) Determine the major axis and the step size. i. if dx=x2-x1>dy=y2-y1, then major axis is x. ii. Then increment x axis by 1 and y axis by m. iii. Else major axis is y. iv. Then increment y axis by 1 and x axis by 1/m. d) Increment the major axis by 1 and determine the corresponding value of the other axis. e) Plot the points to get the exact line.
Program development
#include<iostream.h> #include<conio.h> #include<stdlib.h> #include<graphics.h> void main() { int i,gd,gm; float xi,yi,dx,dy,x1,x2,y1,y2,x,y,l; clrscr(); gd=DETECT; initgraph(&gd,&gm,"c:/tc/bin"); cout<<"\n Enter start Co-ordinates"; cin>>x1>>y1; cout<<\n Enter end co-ordinates"; cin>>x2>>y2; dx=x2-x1; dy=y2-y1; if(abs(dx)>abs(dY)) l=dx; else l=dy; xi=dx/l; yi=dy/l; x=x1; y=y1; putpixel(x,y,225); for(i=1;i<=l;i++) { x=x+xi; y=y+yi; putpixel(x, y,225); } getch(); return 0;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

79

Multimedia Lab Manual

Test Case 1:

Enter start Co-ordinates. 100 100 x2 =300 y2 =300 Enter start Co-ordinates 100 100 Enter end co-ordinates 300 100 Enter start Co-ordinates 100 100 Enter end co-ordinates 100 300

Test Case 2:

Test case 3:

Test case 4:

Enter start Co-ordinates 300 100 Enter end co-ordinates 100 300

Summary of results

Case 1: line with positive slope.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

80

Multimedia Lab Manual

Case 2: horizontal line.

Case 3: vertical line.

Case 4: line with negative slope.

7.2. Bresenhams line drawing algorithm


Problem definition

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

81

Multimedia Lab Manual

Implement the Bresenhams line drawing algorithm.


Algorithm

a) Start. b) Input the two endpoints of the line and store the left end point as (x0, y0). c) Load (x0, y0) into the frame buffer and plot the first point. d) Calculate dx, dy, 2dx, 2dy, 2dx-2dy, and obtain the value p0=2dy-dx. e) At each xk along the line starting from k=0 perform the following. a. if pk<0,then the next point to be plotted is (xk+1,yk) and pk+1=pk+2dy. b. if ok>0, then the next line to be plotted is (xk+1,yk+1) and pk+1=pk+2dy-2dx. f) Repeat the steps dx times. g) End.
Program development
#include<iostream.h> #include<stdio.h> #include<graphics.h> #include<math.h> #include<conio.h> int x1,y1,x2,y2; void brhm(int,int,int,int); main() { int gd=DETECT,gm; initgraph(&gd,&gm,"C:\TC\BIN"); cout<<"enter the value of end points:\n"; cin>>x1>>y1>>x2>>y2; brhm(x1,y1,x2,y2); getch(); return 0; } void brhm(int x1,int y1,int x2,int y2) { int x,y,m,n; float dx,dy,p0; x=x1; y=y1; mx2-x1; ny2-y1; dx=abs(m);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

82

Multimedia Lab Manual

dy=abs(n); err0=2*dx-dy; putpixel(x,y,225); while(x<=x2) { if(p0<0) { p0=p0+2*dy; x=x+1; putpixel(x,y,225); } else { p0=p0+2*dy-2*dx; x=x+1; y=y+1; putpixel(x,y,225); } } }

Testing strategies Test Case 1:

enter the value of end points: 100 100 300 300 enter the value of end points: 100 100 300 100 enter the value of end points: 100 100 100 300

Test Case 2:

Test case 3:

Test case 4:

enter the value of end points: 300 100 100 300

Summary of result

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

83

Multimedia Lab Manual

Case 1: line with positive slope.

Case 2: horizontal line.

Case 3: vertical line.

Case 4: line with negative slope.

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

84

Multimedia Lab Manual

7.3. Bresenhams circle drawing algorithm


Problem definition

Implement the Bresenhams circle drawing algorithm.


Algorithm

a. Input the radius r and the circle centre (0, 0) so that (x 0, y0) = (0, r) b. Calculate the initial value of decision parameters as P0=3-2*r c. At each xk, position starting at k=0, perform the following steps: i. if Pk<0, the next point along the circle centred at (0,0) is (xk+1,yk) Pk+1=Pk+4xk+6 ii. Otherwise if Pk>0, the next point (xk+1,yk+1) Pk+1=Pk+4(xk-yk) +10 d. Determine symmetry point in other seven octants. e. Repeat steps 3 t0 4 until x>=y.
Program development
#include<stdio.h> #include<conio.h> #include<math.h> #include<graphics.h> void brcircle(int,int,int); void circleplotpoints(int,int,int,int); void main() { int xc,yc,r; int gd=DETECT,gm; initgraph(&gd,&gm,c:\\tc\\bgi); printf(enter the values of centre); scanf(%d%d,&xc,&yc); printf(enter the value of radius);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

85

Multimedia Lab Manual

scanf(%d,&r); brcircle(int,int,int); getch(); } void brcircle(int xc,int yc,int r) { int x1=0,y1=r; float p=3-2*r; while(x1<=y1) { circlepplotpoints(int,int,int,int); if(p<0) { p=p+4*x1+6; } else { p=p+4*(x1-y1)+10; y1=y1-1; } x1=x1+1; if(x1==y1) { circleplotpoints(int,int,int,int); } } void circleplotpoints(int xc,int yc,int x1,int y1) { putpixel(xc+x1,yc+y1,225); putpixel(xc-x1,yc+y1,225); putpixel(xc-x1,yc-y1,225); putpixel(xc+x1,yc-y1,225); putpixel(xc+y1,yc+x1,225); putpixel(xc-y1,yc+x1,225); putpixel(xc-y1,yc-x1,225); putpixel(xc+y1,yc-x1,225); }

Testing strategies Test Case 1:

enter the values of centre :200,200 enter the value of radius: 100
Test Case 2:

enter the values of centre : 300,200 enter the value of radius: 100
Summary of result Case 1:
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

86

Multimedia Lab Manual

Case 2:

7.4. A dynamic solar system


Problem definition

Implement a dynamic solar system.


Algorithm

a) start. b) generate the sun, the planets and the orbits of the various planets using functions like circle, ellipse. c) initialise the coordinates of the planet for revolution around the sun placed at the centre. d) for each planet do i. 1.rotate the x axis about the centre of the ellipse. a. x=midx+x-radius*cos(angle). ii. 2.rotate the y axis about the centre of the ellipse.
87

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

a. Y=midy+y-radius*sin(angle). e) 5.redraw the planets and ellipse and all for each angle rotation. f) 6.repeat until a key-press. g) 7.stop.

of

Program development
#include<iostream.h> #include<graphics.h> #include<conio.h> #include<DOS.h> #include<math.h> main() { int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\tc\\bin"); int i=0; float angle=0; while(!kbhit()) { angle=(i*3.14)/180; cleardevice(); setcolor(YELLOW); setfillstyle(1,YELLOW); fillellipse(300,250,18,18); circle(300,250,18); setcolor(WHITE); ellipse(300,250,0,360,50,17); setcolor(RED); setfillstyle(1,RED); fillellipse(300+50*cos(angle+45),250+17*sin(angle+45),3,3); circle(300+50*cos(angle+45),250+17*sin(angle+45),3); setcolor(WHITE); ellipse(300,250,0,360,60,27); setcolor(BROWN); setfillstyle(1,BROWN); fillellipse(300+60*cos(angle+25),250+27*sin(angle+25),10,10); circle(300+60*cos(angle+25),250+27*sin(angle+25),10); setcolor(WHITE); ellipse(300,250,90,450,90,35); setcolor(BLUE); setfillstyle(1,BLUE); fillellipse(300+90*cos(angle-10),250+35*sin(angle-10),7,7); circle(300+90*cos(angle-10),250+35*sin(angle-10),7);

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

88

Multimedia Lab Manual

setcolor(WHITE); ellipse(300,250,90,450,120,65); setcolor(GREEN); setfillstyle(1,GREEN); fillellipse(300+120*cos(angle+5),250+65*sin(angle+5),12,12); circle(300+120*cos(angle+5),250+65*sin(angle+5),12); setcolor(WHITE); ellipse(300,250,90,450,160,105); setcolor(RED); setfillstyle(1,RED); fillellipse(300+160*cos(angle+90),250+105*sin(angle+90),7,7); circle(300+160*cos(angle+90),250+105*sin(angle+90),7); setcolor(WHITE); ellipse(300,250,90,450,180,125); setfillstyle(1,WHITE); fillellipse(300+180*cos(angle-21),250+125*sin(angle-21),8,8); circle(300+180*cos(angle-21),250+125*sin(angle-21),8); ellipse(300,250,90,450,220,165); setcolor(LIGHTGREEN); setfillstyle(1,LIGHTGREEN); fillellipse(300+220*cos(angle+64),250+165*sin(angle+64),6,6); circle(300+220*cos(angle+64),250+165*sin(angle+64),6); setcolor(WHITE); ellipse(305,250,90,450,260,205); setcolor(LIGHTBLUE); setfillstyle(1,LIGHTBLUE); fillellipse(305+260*cos(angle+11),250+205*sin(angle+11),3,3); circle(305+260*cos(angle+11),250+205*sin(angle+11),3); i++; delay(50); } getch(); return 0; }

Result

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

89

Multimedia Lab Manual

7.5. A see-saw in a playground


Problem definition Implement a see-saw in a playground. Algorithm

a) Start. b) Generate the see-saw and the two people on it using lines, circles etc. c) Redraw the objects by changing the coordinates and with proper delay. d) The see-saw is rotated about its centre using the formula i. x1=xc+150*cos(r); ii. y1=yc+150*sin(r); iii. x2=xc+150*cos(s); iv. y2=yc+150*sin(s); e) Stop.
Program development
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

90

Multimedia Lab Manual

#include<graphics.h> #include<iostream.h> #include<conio.h> #include<math.h> #include<dos.h> //the two people void person(int x1,int y1,int x2,int y2,int b) { circle(x1+10,y1-80,15); line(x1+10,y1-65,x1+5,y1); line(x1+5,y1,x1+50,y1); line(x1+50,y1,x1+60,y1+50); line(x1+10,y1-45,x1+45,y1+b); circle(x2-10,y2-80,15); line(x2-10,y2-65,x2-5,y2); line(x2-5,y2,x2-50,y2); line(x2-50,y2,x2-60,y2+50); line(x2-10,y2-45,x2-40,y2-b);

void main() { int driver = DETECT,mode; int i,x1,y1,x2,y2,a[6],b,xc,yc; float r,s; initgraph(&driver,&mode,"c:\\tc\\bin"); x1=100; x2=300; y1=100; y2=300; xc=200; yc=200;b=20; while(!kbhit()) { cleardevice(); setcolor(WHITE); a[0]=200; a[1]=200; a[2]=175; a[3]=300; a[4]=225; a[5]=300; setfillstyle(1,BROWN); fillpoly(3,a); for(i=200;i>150&&!kbhit();i=i-1) { r=3.14/180*i; s=3.14/180*(i+180); x1=xc+150*cos(r); y1=yc+150*sin(r); x2=xc+150*cos(s); y2=yc+150*sin(s); b--; setcolor(WHITE); line(x1,y1,x2,y2); person(x1,y1,x2,y2,b); delay(30); setcolor(BLACK); line(x1,y1,x2,y2); person(x1,y1,x2,y2,b); } for(i=155;i<205&&!kbhit();i=i+1) { r=3.14/180*i;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

91

Multimedia Lab Manual

} } getch(); return 0; }

s=3.14/180*(i+180); x1=xc+150*cos(r); y1=yc+150*sin(r); x2=xc+150*cos(s); y2=yc+150*sin(s); b++; setcolor(WHITE); line(x1,y1,x2,y2); person(x1,y1,x2,y2,b); delay(30); setcolor(BLACK); line(x1,y1,x2,y2); person(x1,y1,x2,y2,b);

Result

7.6. A virtual worship


Problem definition
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

92

Multimedia Lab Manual

Implement a virtual worship which includes twinkling star, burning candle and glowing bulb.
Algorithm

a) Start. b) Generate the lamp on a lamp post, burning candle and stars using functions like circle, rectangle, line, ellipse etc. c) redraw the objects by changing the coordinates and with proper delay. d) Redraw the star color and black filled alternately to show it as blinking. e) Stop.
Program development
#include<iostream.h> #include<dos.h> #include<graphics.h> #include<conio.h> int poly1[12],poly2[12]; main() { int gd=DETECT,gm; initgraph(&gd,&gm,"c:\\tc\\bin"); //candle int j=1; poly1[0]=75; poly1[1]=80; poly1[2]=50; poly1[3]=130; poly1[4]=100; poly1[5]=130; poly2[0]=50; poly2[1]=100; poly2[2]=75; poly2[3]=150; poly2[4]=100; poly2[5]=100; for(int i=0;i<198;i++) { cleardevice(); //star //part1 if(j%2==0) { setcolor(WHITE);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

93

Multimedia Lab Manual

setfillstyle(1,WHITE); fillpoly(3,poly1); fillpoly(3,poly2); } else { setcolor(BLACK); setfillstyle(1,BLACK); fillpoly(3,poly1); fillpoly(3,poly2); } //wick setcolor(WHITE); setfillstyle(1,WHITE); line(350,250+i,350,240+i); //candle body ellipse(350,250+i,0,360,10,5); line(340,250+i,340,450); line(360,250+i,360,450); ellipse(350,450,180,360,10,5); //flame setcolor(YELLOW); setfillstyle(1,YELLOW); fillellipse(350,228+i,5,15); ellipse(350,228+i,0,360,5,15); //lamp setcolor(WHITE); setfillstyle(1,WHITE); rectangle(550,100,555,450); rectangle(520,97,555,100); line(520,100,520,115); rectangle(518,115,522,118); setcolor(YELLOW); setfillstyle(1,YELLOW); fillellipse(520,133,15,15); circle(520,133,15); //lamp ends j++; delay(200); } cleardevice(); //star //part1 setcolor(YELLOW); setfillstyle(1,YELLOW); line(50,50,60,50); line(50,50,55,60); line(60,50,55,60); //part2 line(55,45,50,55); line(50,55,60,55); line(60,55,55,45); //star ends setcolor(WHITE); setfillstyle(1,WHITE); //wick
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

94

Multimedia Lab Manual

line(350,448,350,438); //candle body ellipse(350,448,0,360,10,5); line(340,448,340,450); line(360,448,360,450); ellipse(350,450,180,360,10,5); //candle ends //lamp rectangle(550,100,555,450); rectangle(520,97,555,100); line(520,100,520,115); rectangle(518,115,522,118); setcolor(YELLOW); setfillstyle(1,YELLOW); fillellipse(520,133,15,15); circle(520,133,15); //lamp ends getch(); return 0; }

Result

7.7. A leaky bucket


Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

95

Multimedia Lab Manual

Problem definition

Implement a leaky bucket kept under an open tap.


Algorithm

a) Start. b) Generate the bucket, tap, flowing water etc using functions like circle, rectangle, line, ellipse etc. c) Redraw the objects by changing the coordinates and with proper delay. d) Stop.
Program development
#include<iostream.h> #include<graphics.h> #include<conio.h> #include<stdlib.h> #include<process.h> #include<dos.h> void drops(int y) { setcolor(LIGHTBLUE); setfillstyle(1,LIGHTBLUE); rectangle(395,215,400,y); floodfill(398,225,LIGHTBLUE); } void pipe() { setcolor(BROWN); //floodfill(300,197,BROWN); rectangle(245,195,250,460); line(250,200,395,200); line(250,195,400,195); line(400,195,400,215); line(395,200,395,215); line(395,215,400,215); line(375,190,375,202); line(380,190,380,202); line(375,202,380,202); line(375,190,380,190); rectangle(370,185,385,190);

void bucket() { setcolor(YELLOW); ellipse(400,250,0,360,50,10); arc(400,250,0,180,55);


Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

96

Multimedia Lab Manual

} void fill_bucket() { int ymax=250,ymin=350,y,x1,x2; int poly[8],i,j; y=ymin; i=0; while(!kbhit()) { cleardevice(); pipe(); bucket(); drops(y); setfillstyle(SOLID_FILL,BLUE); fillellipse(405,460,i,5); i=i+2; x1=445-((y-350)/20); x2=355+((y-350)/20); poly[0]=355; poly[1]=ymin; poly[2]=445; poly[3]=ymin; poly[4]=x1; poly[5]=y; poly[6]=x2; poly[7]=y; setfillstyle(SOLID_FILL,BLUE); fillpoly(4,poly); setcolor(WHITE); bucket(); if(y>ymax) y=y-1; else { setfillstyle(SOLID_FILL,BLUE); fillellipse(405,460,i,5); i=i+10; bucket(); } if(y<(ymin-3)) { for(j=360;j<getmaxy();j=j+20) { setcolor(BLACK); rectangle(0,351,getmaxx(),getmaxy()); floodfill(150,360,BLACK); setfillstyle(SOLID_FILL,BLUE); fillellipse(405,j,5,5); delay(5); }
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

line(345,250,355,250); line(455,250,445,250); //line(350,250,450,250); line(355,350,445,350); //ellipse(400,350,0,360,45,8); line(350,250,355,350); line(445,350,450,250);

97

Multimedia Lab Manual

} delay(100); } }

void main() { int gd=DETECT,gm,ec; initgraph(&gd,&gm,"c:\\tc\\bgi"); fill_bucket(); getch(); } return 0;

Result

7.8. A man riding a bicycle


Problem definition

Implement a man riding a bicycle.


Algorithm

a) Start.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

98

Multimedia Lab Manual

b) Generate the man on a bicycle using functions like circle, rectangle, line, ellipse etc. c) Redraw the objects by changing the coordinates and with proper delay. d) Redraw the man and bicycle and the persons leg to show motion. For this the x coordinated is incremented by 1 and the wheels of the cycle are made to rotate along with the incrementing x coordinate. e) Stop.
Program development
#include<iostream.h> #include<conio.h> #include<graphics.h> #include<stdlib.h> #include<math.h> #include<dos.h> int x1,x2,y,yn,xmid; void man(int a,int b,int c,int d) { static int i=0; float rad; int xt,yt; setcolor(BLUE); yn=y-40; circle(xmid,yn-50,10); //face line(xmid,yn-40,xmid,yn); //body line(xmid,yn,xmid+23,yn+15);//leg till knee rad = (3.14/180)*i; //dda loop xt = xmid+4*cos(rad); yt = (y-5)+4*sin(rad); line(xmid+23,yn+15,xt,yt);//moving part of leg setcolor(GREEN); line(xt-5,yt-3,xt+8,yt-2);//pedal line(xt+8,yt-2,xt+3,yt+3); line(xt+3,yt+3,xt-8,yt+3); line(xt-8,yt+3,xt-5,yt-3); i=i+10; line(xmid+8,yn+30,xt,yt);//connection to pedal setcolor(BLUE); line(xmid,yn-27,a,b);//hand line(xmid,yn-30,c,d);//lf hand line(xmid+44,yn-12,xmid+44,yn-10); line(xmid+45,yn-12,xmid+45,yn-10); } void spoke(int x,int y) {
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

99

Multimedia Lab Manual

float rad1,rad2,rad3; int a1,b1,a2,b2,a3,b3,a4,b4,a5,b5,a6,b6,r=22; float h; static int i=0; setcolor(GREEN); h=3.14/180; rad1=h*i; rad2=h*(i+60); rad3=h*(i+120); a1=x+r*cos(rad1); b1=y+r*sin(rad1); a4=x-r*cos(rad1); b4=y-r*sin(rad1); a2=x+r*cos(rad2); b2=y+r*sin(rad2); a5=x-r*cos(rad2); b5=y-r*sin(rad2); a3=x+r*cos(rad3); b3=y+r*sin(rad3); a6=x-r*cos(rad3); b6=y-r*sin(rad3); line(a1,b1,a4,b4); line(a2,b2,a5,b5); line(a3,b3,a6,b6); i++; } void drawcycle() { setcolor(GREEN); if(x2==630) { x1=25; x2=95; } circle(x1,y,25);//1st wheel circle(x1,y,22); circle(x2,y,25);//2nd wheel circle(x2,y,22); spoke(x1,y); spoke(x2,y); line(x1+25,y-10,x2-25,y-10);//Rod b/w wheels line(x1+25,y-12,x2-25,y-12); xmid=x1+(x2-x1)/2; line(xmid,y-12,xmid,y-40);//sprt for seat line(xmid-10,y-40,xmid+10,y-40);//seat line(x2-1,y-25,x2-1,y-50);//handle rod line(x2+1,y-25,x2+1,y-50); line(x2-4,y-49,x2+12,y-51);//handle int j,k,l,m;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

100

Multimedia Lab Manual

j = x2-4; k = y-49; l = x2+12; m = y-51; man(j,k,l,m); delay(5); cleardevice(); x1++; x2++; } main() { int gdriver=DETECT,gmode; clrscr(); initgraph(&gdriver,&gmode,"C:\\tc\\bgi"); x1=25,x2=110,y=435; while(!kbhit()) { setcolor(LIGHTBLUE); line(0,460,640,460); drawcycle(); } getch(); return0; }

Result

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

101

Multimedia Lab Manual

8. UNIVERSITY PRACTICAL EXAMAINATION QUESTIONS 1. Simulate a rotating table fan. 2. Simulate a real time tap. 3. Simulate a bouncing ball. 4. Simulate a pendulum clock. 5. Simulate a dynamic solar system. 6. Simulate a time glass. 7. Simulate see- saw in a playground. 8. Simulate a man riding a bicycle. 9. Simulate a railway cross. 10. Simulate a man walking with an umbrella. 11. Simulate sunrise and sunset. 12. Simulate a flag hoisting scene on an Independence Day. 13. Simulate an arrow striking a flying bird. 14. Simulate a blooming and drooping flower. 15. Simulate ripples formed in the water when a stone is thrown into it. 16. Simulate a scene where a man fetches water from a well. 17. Simulate a moving car which accelerates, decelerates and stops at a junction. 18. Simulate the movements of a knight on a chess board. 19. Simulate a man riding a bicycle on a raining day. 20. Simulate a scene where the lights in a house are switched on when a man enters the house and the lights are switched off when he leaves.. 21. Simulate a scene in which an aeroplane moving in the sky is obstructed by the clouds moving in the opposite direction. 22. Simulate a traffic signal in a four way junction. 23. Simulate a scene of a football ground. 24. Simulate virtual worship which includes twinkling stars, burning candlings, and glowing bulbs. 25. Simulate a car moving in an inclined surface. 26. Simulate a scene where a person moving in a car is bombed by his enemy.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

102

Multimedia Lab Manual

27. Simulate a man landing in a parachute from an aeroplane. 28. Simulate a tree moving in the wind. 29. Simulate a scene in which a man walking with an umbrella is subjected to three different climatic conditions like hot sun, heavy rain and strong wind. 30. Simulate a Leaky bucket kept under an open tap. 31. Simulate a scene in which a soldier lands safely from an aeroplane and kills three enemies resting in a hill valley. 32. Simulate a war scene where an airship is shooting down the enemies who try to intrude into the homeland. 33. Implement a Bezier curve for a given set of control points. 34. Replicate an equilateral triangle six times to form a hexagon. 35. Rig up a program to rotate circle with its centre on another circle. 36. Write a program to generate a spiral. 37. Shade a regular Pentagon and a circle. 38. Simulate a man driving a bicycle over the given bridge. 39. Simulate a man entering into a church on a Christmas night. The church should be well decorated. 40. Simulate filling of a bucket. When the bucket is filled, tap should be automatically closed. After sometime water should be removed from the bucket and the bucket must be empty. Repeat this process n time. 41. Simulate a man opening an umbrella in the rain and also turn off the burning candles in the rain. 42. Simulate two children playing with a ball. 43. Move the ball along the given surface.

44.

Join the above triangles and fill the square cavity

45. You are given a wheel with four sprockets. Imagine a dynamically changing inclination. The wheel has to rotate upward, whichever be the inclination. Inclination will be accepted from the user.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

103

Multimedia Lab Manual

Please note that you will be asked to implement all the above questions without using the inbuilt graphics functions.

9. VIVA QUESTIONS 1. The short form for __________ is pixel. 2. Image to be displayed on the screen is stored in a special part of computers memory called________ . 3. The unit of refresh rate is ___________ . 4. ____________ gives the ratio of vertical points to horizontal points necessary to produce equal length lines in both directions on the screen. 5. The maximum number of points that can be displayed without overlap in a CRT is referred to as ___________ 6. For systems with multiple bits per pixel, the frame buffer is often referred to as _________ . 7. The process in which the object is represented as a collection of discrete pixel is called __________ 8. In putpixel(x, y, 1), the number 1 represents ________. 9. The slope of the line y=mx + c is given by ________. 10. The equation of a line that makes an angle of 45o with the x-axis is given by _______. 11. In Bresenhams algorithm, __________ is used to find the optimum raster location to represent a straight line. 12. The header file for the delay() is _________. 13. Any point (x, y) in the interior of the circle satisfies _________ equation.
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

104

Multimedia Lab Manual

14. If the scaling factor is above _______ value, it denotes magnification. 15. A square ABCD with co-ordinates A(0,0), B(5,0) , C(5,5), D(0,5) is moved by 2 units in the x direction and 3 units in the y direction. The new position of the square ABCD is ________ 16. A line AB on the screen with end points A(0,0) and B(10,0) is rotated 45o .The direction of rotation is __________ . 17. The scaling matrix required for a point P(x, y) to be scaled A units in the x - direction is _______ 18. A _________lies parallel to the axis of WCS and it is used to select the portion of the scene for which an image is to be generated. 19. A point is _________ the window when x min x x max and y min y y max. 20. In Cohen Sutherland algorithm, the MSB in the 4 bit region code represents _________region in the window. 21. Digitizer is a graphical ________ device. 22. Resolution & Pixel Size is ___________ proportional. 23. _________ function initializes the graphics system by loading a graphics driver from disk . 24. _________ function is used to display a string in a viewport . 25. _________ function returns the maximum x value for the current graphics driver and mode. 26. _________ function returns the current position of y coordinate. 27. _________ function displays a string at the specified location. 28. 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 ________. 29. Transformation of object shapes from one form to another is called ________ . 30. The ______________ gets the inputs and commands from the user and determines the image to be displayed on the monitor. 31. An increase in the number of available intensity levels is achieved for a modest increase in required memory by using a________________. 32. In ___________________, the red, green, and blue phosphors for each pixel are generally arranged in a triangular shape 33. The number of times a screen is redrawn in one second is measured in_______________. 34. A 3-bit plane frame buffer for a 1024 X1024 raster requires ______________memory bits. 35. The detail variation in a fractal object can be described with a number called _____________
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

105

Multimedia Lab Manual

36. ____________ defines the details of the object motion for selected positions in the animation. 37. Depth Buffer method is a _______________ type of visible surface detection method which compares surface depths. 38. In spline representations, when polynomial sections are fitted so that the curve passes through each control point, the resulting curve is said to _____________ the set of control points. 39. The _______________ are the key to the behavior of Bezier curies. 40. int gd = DETECT,cm; initgraph( _____, _____, c:\\tc ____ ); 41. getbkcolor returns the current _________ color. 42. ________ function draws an ellipse using (x,y) as a center point and xradius and yradius as the horizontal and vertical axes, and fills it with the current fill color and fill pattern. 43. ________ function gets the color of the pixel located at (x,y). 44. ________ function is like setfillstyle, except that you use it to set a user-defined 8x8 pattern rather than a predefined pattern. 45. ________function draws a circular arc in the current drawing color centered at (x,y) with a radius given by radius. The arc travels from stangle to endangle. If stangle equals 0 and endangle equals 360, the call to arc draws a complete circle. 46. _________function is used to determine how many palette entries can be set for the current graphics mode. 47. _________ function draws and fills an elliptical pie slice using (x,y) as the center point, xradius and yradius as the horizontal and vertical radii, respectively, and drawing from stangle to endangle. 48. __________ function erases (that is, fills with the current background color) the entire graphics screen and moves the CP (current position) to home (0,0). 49. ___________ function draws a rectangle in the current line style, thickness, and drawing color. 50. ___________ function sets the style for all lines drawn by line, lineto, rectangle, drawpoly, and so on.

10. APPENDIX 10.1. Sample codes of the graphic functions


arc /* arc example */ 1. #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h>
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

106

Multimedia Lab Manual

int main(void) { /* int int int int request autodetection */ gdriver = DETECT, gmode, errorcode; midx, midy; stangle = 45, endangle = 135; radius = 100;

/* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw arc */ arc(midx, midy, stangle, endangle, radius); /* clean up */ getch(); closegraph(); return 0; } circle /* circle example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

107

Multimedia Lab Manual

int midx, midy, radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw the circle */ circle(midx, midy, radius); /* clean up */ getch(); closegraph(); return 0; } cleardevice /* cleardevice example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

108

Multimedia Lab Manual

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* for centering screen messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* output a message to the screen */ outtextxy(midx, midy, "Press any key to clear the screen:"); getch(); /* wait for a key */ cleardevice(); /* clear the screen */ /* output another message */ outtextxy(midx, midy, "Press any key to quit:"); /* clean up */ getch(); closegraph(); return 0;

closegraph /* closegraph example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode, x, y; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

109

Multimedia Lab Manual

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output a message */ settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, "Press a key to close the graphics system:"); getch(); /* wait for a key */ /* closes down the graphics system */ closegraph(); printf("We're now back in text mode.\n"); printf("Press any key to halt:"); getch(); return 0; } delay /* delay example */ #include "graphics.h" int main(void) { int midx, midy, i; /* initialize the window size */ initwindow(100, 100); midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns with 4 second delays */ for (i=SOLID_FILL; i<USER_FILL; i++) { /* set the fill style */ setfillstyle(i, getmaxcolor()); /* draw the bar */ bar(midx-50, midy-50, midx+50, midy+50); delay(4000);

/* clean up */
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

110

Multimedia Lab Manual

closegraph(); return 0; } detectgraph /* detectgraph example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> /* the names of the various cards supported */ char *dname[] = { "requests detection", "a CGA", "an MCGA", "an EGA", "a 64K EGA", "a monochrome EGA", "an IBM 8514", "a Hercules monochrome", "an AT&T 6300 PC", "a VGA", "an IBM 3270 PC" }; int main(void) { /* used to return detected hardware info. */ int gdriver, gmode, errorcode; /* detect the graphics hardware available */ detectgraph(&gdriver, &gmode); /* read result of detectgraph call */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* display the information detected */ clrscr(); printf("You have %s video display card.\n", dname[gdriver]); printf("Press any key to halt:"); getch(); return 0;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

111

Multimedia Lab Manual

} drawpoly /* drawpoly example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; int poly[10]; /* our polygon array */ /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk){ /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); poly[0] = 20; poly[1] = maxy / 2; poly[2] = maxx - 20; poly[3] = 20; poly[4] = maxx - 50; poly[5] = maxy - 20; poly[6] = maxx / 2; poly[7] = maxy / 2; poly[8] = poly[0]; automatically close */ poly[9] = poly[1]; */ drawpoly(5, poly); /* clean up */ getch();

/* first vertex */ /* second vertex */ /* third vertex */ /* fourth vertex */ /* drawpoly doesn't /* the polygon, so we close it /* draw the polygon */

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

112

Multimedia Lab Manual

closegraph(); return 0; } ellipse /* ellipse example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 0, endangle = 360; int xradius = 100, yradius = 50; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor()); /* draw ellipse */ ellipse(midx, midy, stangle, endangle, xradius, yradius); /* clean up */ getch(); closegraph(); return 0;

fillellipse

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

113

Multimedia Lab Manual

/* fillellipse example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, i; int xradius = 100, yradius = 50; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns */ for (i = EMPTY_FILL; i < USER_FILL; i++) { /* set fill pattern */ setfillstyle(i, getmaxcolor()); /* draw a filled ellipse */ fillellipse(midx, midy, xradius, yradius); getch();

/* clean up */ closegraph(); return 0; } fillpoly /* fillpoly example */ #include <graphics.h> #include <stdlib.h>
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

114

Multimedia Lab Manual

#include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int i, maxx, maxy; /* our polygon array */ int poly[8]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy(); poly[0] = 20; poly[1] = maxy / 2; poly[2] = maxx - 20; poly[3] = 20; poly[4] = maxx - 50; poly[5] = maxy - 20; poly[6] = maxx / 2; automatically */ poly[7] = maxy / 2;

/* first vertex */ /* second vertex */ /* third vertex */ /* fourth, fillpoly /* closes the polygon */

/* loop through the fill patterns */ for (i=EMPTY_FILL; i<USER_FILL; i++) { /* set fill pattern */ setfillstyle(i, getmaxcolor()); /* draw a filled polygon */ fillpoly(4, poly); getch(); } /* clean up */ closegraph();
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

115

Multimedia Lab Manual

return 0;

floodfill /* floodfill example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy();

/* select drawing color */ setcolor(getmaxcolor()); /* select fill color */ setfillstyle(SOLID_FILL, getmaxcolor()); /* draw a border around the screen */ rectangle(0, 0, maxx, maxy); /* draw some circles */ circle(maxx / 3, maxy /2, 50); circle(maxx / 2, 20, 100); circle(maxx-20, maxy-50, 75); circle(20, maxy-20, 25);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

116

Multimedia Lab Manual

/* wait for a key */ getch(); /* fill in bounded region */ floodfill(2, 2, getmaxcolor()); /* clean up */ getch(); closegraph(); return 0;

getarccoords /* getarccoords example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; struct arccoordstype arcinfo; int midx, midy; int stangle = 45, endangle = 270; char sstr[80], estr[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* draw arc and get coordinates */ setcolor(getmaxcolor()); arc(midx, midy, stangle, endangle, 100);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

117

Multimedia Lab Manual

getarccoords(&arcinfo); /* convert arc information into strings */ sprintf(sstr, "*- (%d, %d)", arcinfo.xstart, arcinfo.ystart); sprintf(estr, "*- (%d, %d)", arcinfo.xend, arcinfo.yend); /* output the arc information */ outtextxy(arcinfo.xstart, arcinfo.ystart, sstr); outtextxy(arcinfo.xend, arcinfo.yend, estr); /* clean up */ getch(); closegraph(); return 0; } getaspectratio /* getaspectratio example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> main() { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int xasp, yasp, midx, midy; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor());

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

118

Multimedia Lab Manual

/* get current aspect ratio settings */ getaspectratio(&xasp, &yasp); /* draw normal circle */ circle(midx, midy, 100); getch(); /* draw wide circle */ cleardevice(); setaspectratio(xasp/2, yasp); circle(midx, midy, 100); getch(); /* draw narrow circle */ cleardevice(); setaspectratio(xasp, yasp/2); circle(midx, midy, 100); /* clean up */ getch(); closegraph(); return 0; } getbkcolor /* getbkcolor example */ #include <graphics.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int bkcolor, midx, midy; char bkname[35]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch();

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

119

Multimedia Lab Manual

exit(1); code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor());

/* terminate with an error

/* for centering text on the display */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* get the current background color */ bkcolor = getbkcolor(); /* convert color value into a string */ itoa(bkcolor, bkname, 10); strcat(bkname, " is the current background color."); /* display a message */ outtextxy(midx, midy, bkname); /* clean up */ getch(); closegraph(); return 0; } getcolor /* getcolor example */ #include <graphics.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int color, midx, midy; char colname[35]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch();
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

120

Multimedia Lab Manual

exit(1); code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; setcolor(getmaxcolor());

/* terminate with an error

/* for centering text on the display */ settextjustify(CENTER_TEXT, CENTER_TEXT); /* get the current drawing color */ color = getcolor(); /* convert color value into a string */ itoa(color, colname, 10); strcat(colname, " is the current drawing color."); /* display a message */ outtextxy(midx, midy, colname); /* clean up */ getch(); closegraph(); return 0;

} getpixel

/* getpixel example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */ int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int i, x, y, color, maxx, maxy, maxcolor, seed; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult();
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

121

Multimedia Lab Manual

if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx() + 1; maxy = getmaxy() + 1; maxcolor = getmaxcolor() + 1; while (!kbhit()) { seed = random(32767); /* seed the random number generator */ srand(seed); for (i=0; i<PIXEL_COUNT; i++) { x = random(maxx); y = random(maxy); color = random(maxcolor); putpixel(x, y, color); } delay(DELAY_TIME); srand(seed); for (i=0; i<PIXEL_COUNT; i++) { x = random(maxx); y = random(maxy); color = random(maxcolor); if (color == getpixel(x, y)) putpixel(x, y, 0); } } /* clean up */ getch(); closegraph(); return 0;

} getx

/* getx example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */


122

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0;

} gety

/* gety example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

123

Multimedia Lab Manual

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* move to the screen center point */ moveto(getmaxx() / 2, getmaxy() / 2); /* create a message string */ sprintf(msg, "<-(%d, %d) is the here.", getx(), gety()); /* display the message */ outtext(msg); /* clean up */ getch(); closegraph(); return 0;

graphresult /* graphresult example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, "");

/* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

124

Multimedia Lab Manual

} /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0;

initgraph /* initgraph example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; /* initialize graphics mode */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* return with error code */ } /* draw a line */ line(0, 0, getmaxx(), getmaxy()); /* clean up */ getch(); closegraph(); return 0; } kbhit #include "graphics.h" #include <stdio.h> // Provides sprintf
125

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

void outintxy(int x, int y, int value); int main( ) { int i; // Initialize the graphics window. init_window(400, 300); // Convert some numbers to strings and draw them in graphics window: outtextxy(20, 130, "Click in this graphics window,"); outtextxy(20, 140, "and then press a key to stop."); outtextxy(10, 10, "Here are some numbers:"); for (i = 0; !kbhit( ); i++) { outintxy(20 + (i/10)*40 , (i % 10)*+10, i); delay(4000); } closegraph( ); } void outintxy(int x, int y, int value) { char digit_string[20]; sprintf(digit_string, "%d", value); outtextxy(x, y, digit_string); } line /* line example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int xmax, ymax; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch();
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

126

Multimedia Lab Manual

exit(1); } setcolor(getmaxcolor()); xmax = getmaxx(); ymax = getmaxy(); /* draw a diagonal line */ line(0, 0, xmax, ymax); /* clean up */ getch(); closegraph(); return 0;

} pieslice

/* pieslice example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy; int stangle = 45, endangle = 135, radius = 100; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* set fill style and draw a pie slice */
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

127

Multimedia Lab Manual

setfillstyle(EMPTY_FILL, getmaxcolor()); pieslice(midx, midy, stangle, endangle, radius); /* clean up */ getch(); closegraph(); return 0;

} putpixel /* putpixel example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #include <dos.h> #define PIXEL_COUNT 1000 #define DELAY_TIME 100 /* in milliseconds */

int main() { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int i, x, y, color, maxx, maxy, maxcolor, seed; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx() + 1; maxy = getmaxy() + 1; maxcolor = getmaxcolor() + 1; while (!kbhit()) { /* seed the random number generator */ seed = random(32767); srand(seed); for (i=0; i<PIXEL_COUNT; i++) { x = random(maxx); y = random(maxy); color = random(maxcolor); putpixel(x, y, color);
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

128

Multimedia Lab Manual

} delay(DELAY_TIME); srand(seed); for (i=0; i<PIXEL_COUNT; i++) { x = random(maxx); y = random(maxy); color = random(maxcolor); if (color == getpixel(x, y)) putpixel(x, y, 0); } } /* clean up */ getch(); closegraph(); return 0;

rectangle /* rectangle example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int left, top, right, bottom; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } left = getmaxx() / 2 - 50; top = getmaxy() / 2 - 50; right = getmaxx() / 2 + 50; bottom = getmaxy() / 2 + 50;
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

129

Multimedia Lab Manual

/* draw a rectangle */ rectangle(left,top,right,bottom); /* clean up */ getch(); closegraph(); return 0;

} sector

/* sector example */ #include <graphics.h< #include <stdlib.h< #include <stdio.h< #include <conio.h< int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int midx, midy, i; int stangle = 45, endangle = 135; int xrad = 100, yrad = 50; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* loop through the fill patterns */ for (i=EMPTY_FILL; i<USER_FILL; i++) { /* set the fill style */ setfillstyle(i, getmaxcolor()); /* draw the sector slice */ sector(midx, midy, stangle, endangle, xrad, yrad); getch();

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

130

Multimedia Lab Manual

} /* clean up */ closegraph(); return 0; } setcolor /* setcolor example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> int main(void) { /* select driver and mode that supports multiple drawing colors */ int gdriver = EGA, gmode = EGAHI, errorcode; int color, maxcolor, x, y; char msg[80]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } /* maximum color index supported */ maxcolor = getmaxcolor(); /* for centering text messages */ settextjustify(CENTER_TEXT, CENTER_TEXT); x = getmaxx() / 2; y = getmaxy() / 2; /* loop through the available colors */ for (color=1; color<=maxcolor; color++) { cleardevice(); /* clear the screen */
131

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

*/

setcolor(color);

/* select new background color

/* output a messsage */ sprintf(msg, "Color: %d", color); outtextxy(x, y, msg); getch();

/* clean up */ closegraph(); return 0; } setfillpattern /* setfillpattern example */ #include #include #include #include <graphics.h> <stdlib.h> <stdio.h> <conio.h>

int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int maxx, maxy; /* a user-defined fill pattern */ char pattern[8] = {0x00, 0x70, 0x20, 0x27, 0x24, 0x24, 0x07, 0x00}; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) /* an error occurred */ { printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } maxx = getmaxx(); maxy = getmaxy();
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

132

Multimedia Lab Manual

setcolor(getmaxcolor()); /* select a user-defined fill pattern */ setfillpattern(pattern, getmaxcolor()); /* fill the screen with the pattern */ bar(0, 0, maxx, maxy); /* clean up */ getch(); closegraph(); return 0; } 1. setfillstyle /* setfillstyle example */ #include <graphics.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <conio.h> /* the names of the fill styles supported */ char *fname[] = { "EMPTY_FILL", "SOLID_FILL", "LINE_FILL", "LTSLASH_FILL", "SLASH_FILL", "BKSLASH_FILL", "LTBKSLASH_FILL", "HATCH_FILL", "XHATCH_FILL", "INTERLEAVE_FILL", "WIDE_DOT_FILL", "CLOSE_DOT_FILL", "USER_FILL" }; int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy; char stylestr[40]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */ printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch();

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

133

Multimedia Lab Manual

exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; for (style = EMPTY_FILL; style < USER_FILL; style++) { /* select the fill style */ setfillstyle(style, getmaxcolor()); /* convert style into a string */ strcpy(stylestr, fname[style]); /* fill a bar */ bar3d(0, 0, midx-10, midy, 0, 0); /* output a message */ outtextxy(midx, midy, stylestr); /* wait for a key */ getch(); cleardevice();

/* clean up */ getch(); closegraph(); return 0;

setgraphbufsize /* setgraphbufsize example */ #include <graphics.h> #include <stdlib.h> #include <stdio.h> #include <conio.h> #define BUFSIZE 1000 /* internal graphics buffer size */ int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int x, y, oldsize; char msg[80]; /* _set size of internal graphics buffer before calling initgraph */ oldsize = setgraphbufsize(BUFSIZE); /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

134

Multimedia Lab Manual

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } x = getmaxx() / 2; y = getmaxy() / 2; /* output some messages */ sprintf(msg, "Graphics buffer size: %d", BUFSIZE); settextjustify(CENTER_TEXT, CENTER_TEXT); outtextxy(x, y, msg); sprintf(msg, "Old graphics buffer size: %d", oldsize); outtextxy(x, y+textheight("W"), msg); /* clean up */ getch(); closegraph(); return 0; }

setlinestyle /* setlinestyle example */ #include <graphics.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <conio.h> /* the names of the line styles supported */ char *lname[] = { "SOLID_LINE", "DOTTED_LINE", "CENTER_LINE", "DASHED_LINE", "USERBIT_LINE" }; int main(void) { /* request autodetection */ int gdriver = DETECT, gmode, errorcode; int style, midx, midy, userpat; char stylestr[40]; /* initialize graphics and local variables */ initgraph(&gdriver, &gmode, ""); /* read result of initialization */ errorcode = graphresult(); if (errorcode != grOk) { /* an error occurred */
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

135

Multimedia Lab Manual

printf("Graphics error: %s\n", grapherrormsg(errorcode)); printf("Press any key to halt:"); getch(); exit(1); /* terminate with an error code */ } midx = getmaxx() / 2; midy = getmaxy() / 2; /* a user-defined line pattern */ /* binary: "0000000000000001" */ userpat = 1; for (style=SOLID_LINE; style<=USERBIT_LINE; style++) { /* select the line style */ setlinestyle(style, userpat, 1); /* convert style into a string */ strcpy(stylestr, lname[style]); /* draw a line */ line(0, 0, midx-10, midy); /* draw a rectangle */ rectangle(0, 0, getmaxx(), getmaxy()); /* output a message */ outtextxy(midx, midy, stylestr); /* wait for a key */ getch(); cleardevice();

} /* clean up */ closegraph(); return 0;

10.2 Key to the viva questions 1. 2. 3. 4. 5. picture element frame buffer hertz, frames per second aspect ratio resolution
136

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

Multimedia Lab Manual

6. pixmap 7. scan conversion) 8. color 9. y2-y1/x2-x1 10. y=x 11. error term 12. dos.h 13. x2 + y2 r2 < 0 14. 1 15. (A - 2,3) , (B - 7,3) , (C - 7,8) , (D - 2,8) 16. anticlockwise 17. a0 01 18. Window 19. Inside 20. Above 21. Input 22. Inversely 23. initgraph 24. outtext(* text string) 25. getmaxx() 26. gety() 27. outtextxy(int x,int y,char * text string)) 28. shear 29. morphing 30. display controller 31. lookup table 32. Shadow Mask CRT 33. Hertz 34. 3X1024 X1024 35. Fractal dimension 36. key frames 37. Image space method 38. Interpolate 39. Blending functions 40. initgraph(&gd,&cm,c:\\tc\\bgi); 41. background 42. fillellipse 43. getpixel 44. setfillpattern 45. arc 46. getpalettesize 47. sector 48. cleardevice 49. rectangle 50. setlinestyle
Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

137

Multimedia Lab Manual

Prepared by Ms. Mary Priya Sebastian & Ms. Neethu P.U., Department of Computer Science & Engineering, RASET

138

Vous aimerez peut-être aussi