learn how to use c

31
Learn how to use C++ code to create basic animated graphics in this chapter from Beginning Game Programming by Michael Morrison. NOTE 1979 was a critical milestone in the evolution of video games because it brought us Asteroids, which is one of the most enduring games ever. Created by Atari, Asteroids was one of the first vector graphics games, which means that it relied solely on lines to draw graphics, as opposed to little square pixels. Asteroids demonstrated that a very simple concept, with even simpler graphics and a soundtrack that gradually builds tension, creates a mix for success. In fact, Asteroids was so successful that arcade operators had to build larger coin boxes for the games—not a bad problem to have! A computer game consists of many different pieces, all of which must come together to form a unique entertainment experience for the player. By far, the most important pieces of any game are the graphics. Graphics are used to represent the characters and creatures in a game, as well as background worlds and other interesting objects that factor into the overall game design. Granted, games have certainly done well because of factors outside of graphics, such as game play and sound quality, but those games are very rare. Besides, nowadays game players expect to see high-quality graphics just as we all expect to see high-quality visual effects in Hollywood movies. So, it's important to develop a solid understanding of graphics programming and how to use graphics wisely in your games. In this chapter, you'll learn The basics of drawing graphics using the Windows Graphics Device Interface What a device context is and why it's important to GDI graphics How to paint text and primitive graphics in Windows How to create a sample program that demonstrates GDI graphics in the context of the game engine Graphics Essentials

Upload: ron-jovaneil-jimenez

Post on 02-Dec-2014

253 views

Category:

Documents


4 download

TRANSCRIPT

Learn how to use C++ code to create basic animated graphics in this chapter from Beginning Game Programming by Michael Morrison.

NOTE

1979 was a critical milestone in the evolution of video games because it brought us Asteroids, which is

one of the most enduring games ever. Created by Atari, Asteroids was one of the first vector graphics

games, which means that it relied solely on lines to draw graphics, as opposed to little square pixels.

Asteroids demonstrated that a very simple concept, with even simpler graphics and a soundtrack that

gradually builds tension, creates a mix for success. In fact, Asteroids was so successful that arcade

operators had to build larger coin boxes for the games—not a bad problem to have!

A computer game consists of many different pieces, all of which must come together to form a unique

entertainment experience for the player. By far, the most important pieces of any game are the graphics.

Graphics are used to represent the characters and creatures in a game, as well as background worlds

and other interesting objects that factor into the overall game design. Granted, games have certainly done

well because of factors outside of graphics, such as game play and sound quality, but those games are

very rare. Besides, nowadays game players expect to see high-quality graphics just as we all expect to

see high-quality visual effects in Hollywood movies. So, it's important to develop a solid understanding of

graphics programming and how to use graphics wisely in your games.

In this chapter, you'll learn

The basics of drawing graphics using the Windows Graphics Device Interface

What a device context is and why it's important to GDI graphics

How to paint text and primitive graphics in Windows

How to create a sample program that demonstrates GDI graphics in the context of the game engine

Graphics Essentials

Before jumping into the details of how graphics work in Windows and how they are applied to games, it's

important to establish some ground rules and gain an understanding of how computer graphics work in

general. More specifically, you need to have a solid grasp on what a graphics coordinate system is, as

well as how color is represented in computer graphics. The next couple of sections provide you with this

knowledge, which you'll put to practical use a little later in the chapter.

Understanding the Graphics Coordinate System

All graphical computing systems use some sort of graphics coordinate system to specify how points are

arranged in a window or on the screen. Graphics coordinate systems typically spell out the origin (0, 0) of

the system, as well as the axes and directions of increasing value for each of the axes. If you're not a big

math person, this simply means that a coordinate system describes how to pinpoint any location on the

screen as an XY value. The traditional mathematical coordinate system familiar to most of us is shown

in Figure 3.1.

Figure 3.1 The traditional XY coordinate system is commonly used in math.

Windows graphics relies on a similar coordinate system to specify how and where

drawing operations take place. Because all drawing in Windows takes place within the

confines of a window, the Windows coordinate system is applied relative to a particular window. The

Windows coordinate system has an origin that is located in the upper-left corner of the window, with

positive X values increasing to the right and positive Y values increasing down. All values in the Windows

coordinate system are positive integers. Figure 3.2shows how this coordinate system looks.

Figure 3.2 The Windows XY coordinate system is similar to the traditional

coordinate system except that it applies to the client area of windows.

NOTE

When I talk about drawing graphics in a window, I'm actually referring to theclient area of a window, which

doesn't include the title bar, menus, scrollbars, and so on. In the case of games, you can think of the

client area of the main game window as the game screen. You learn more about the client area of a

window later in this chapter in the section titled, "Painting Windows."

If the Windows graphics coordinate system sounds a little complicated, just think of it in terms of a classic

game of Battleship. In Battleship, you try to sink enemy ships by firing torpedoes at specific locations on a

grid. Battleship uses its own coordinate system to allow you to specify locations on the grid where ships

might be located. Similarly, when you draw graphics in Windows, you specify locations in the client area

of a window, which is really just a grid of little squares called pixels.

Learning the Basics of Color

A topic that impacts almost every area of game graphics is color. Fortunately, most computer systems

take a similar approach to representing color. The main function of color in a computer system is to

accurately reflect the physical nature of color within the confines of a computer. This physical nature isn't

hard to figure out; anyone who has experienced the joy of Play-Doh can tell you that colors react in

different ways when they are combined with each other. Like Play-Doh, a computer color system needs to

be capable of mixing colors with accurate, predictable results.

Color computer monitors provide possibly the most useful insight into how software systems implement

color. A color monitor has three electron guns: red, green, and blue. The output from these three guns

converges on each pixel on the screen, stimulating phosphors to produce the appropriate color. The

combined intensities of each gun determine the resulting pixel color. This convergence of different colors

from the monitor guns is very similar to the convergence of different colored Play-Doh.

NOTE

Technically speaking, the result of combining colors on a monitor is different from that of combining

similarly colored Play-Doh. The reason for this is that color combinations on a monitor are additive,

meaning that mixed colors are added together to become white; Play-Doh color combinations

aresubtractive, meaning that mixed colors are subtracted from each other to become black. Whether the

color combination is additive or subtractive depends on the physical properties of the particular medium

involved.

The Windows color system is very similar to the physical system used by color monitors; it forms unique

colors by using varying intensities of the colors red, green, and blue. Therefore, Windows colors are

represented by the combination of the numeric intensities of the primary colors (red, green, and blue).

This color system is known as RGB (Red Green Blue) and is standard across most graphical computer

systems.

NOTE

RGB isn't the only color system used by computers. Another color system used heavily in desktop

publishing applications is CMYK, which stands for Cyan-Magenta-Yellow-Black. Colors in the CMYK color

system are expressed in terms of the color components cyan, magenta, yellow, and black, as opposed to

red, green, and blue in RGB. The CMYK color system is used heavily in printing because CMYK printing

inks are subtractive in nature, making it easier to print using a four-color ink combination (cyan, magenta,

yellow, and black); hence the term four-color printing.

Table 3.1 shows the numeric values for the red, green, and blue components of some basic colors. Notice

that the intensities of each color component range from 0 to 255 in value.

Table 3.1 Numeric RGB Color Component Values for Commonly Used Colors

Color Red Green Blue

White 255 255 255

Black 0 0 0

Light Gray 192 192 192

Medium

Gray

128 128 128

Dark Gray 64 64 64

Red 255 0 0

Green 0 255 0

Blue 0 0 255

Yellow 255 255 0

Purple 255 0 255

The Win32 API defines a structure named COLORREF that combines the red, green, and blue components

of an RGB color into a single value. The COLORREF structure is important because it is used throughout

the Win32 API to represent RGB colors. To create a color as a COLORREFstructure, you use

the RGB() macro, which accepts red, green, and blue color components as arguments. Here is an

example of creating a solid green color using RGB():

COLORREF green = RGB(0, 255, 0);

The color created in this line of code is green because the green component (the middle argument) is

specified as 255, whereas the red and blue components are specified as 0. Changing the values of these

three arguments alters the mix of the color—with lower numbers resulting in darker colors and higher

numbers resulting in brighter colors.

You can experiment with RGB color combinations in the standard Paint program that comes with

Windows. Double-click one of the colors in the color palette in the lower left corner of the Paint window.

Then, click the Define Custom Colors button in the Edit Colors dialog box. You can then either type

numbers into the Red, Green, and Blue edit fields or click to select a color and intensity (see Figure 3.3).

Figure 3.3 The standard Windows Paint program allows you to specify colors via

RGB values.

WAJ

05-09-02, 09:51 AMRight, I'm new to C++ and I have been given a chellenge, and I have no idea how to go about doing it. I'm using Microsoft Visual C++ and I need to know the easiest way to create graphics on screen.

Specifically, a square. A 2d outlined square.

I know it's lame but I haven't done anything graphical before and I want to work up from the easiest :)

I'm going into a Computer Games Technology course this year and I want a head start (as far as programming knowledge goes).

Thanks for any help guys!

Rick05-09-02, 02:08 PM

WAJ,ZION TO RESCUE!!;)

#include"stdio.h"#include"conio.h"#include"graphics.h"#include"alloc.h"void main(){int gd=DETECT,gm;initgraph(&gd,&gm," c:\\turboc2\\bgi"); /*you can give your path,this function basically initializes the graphics mode,gm is for graphics mode,i had set gd=DETECT in previous statement to autodetect the mode you"re using,wether CGA,VGAHI etc...*/rectangle(100,100,100,100);//the above coordinates are the two opposite points of a rectangle,manipulate them to your own useclosegraph();}

anything else you wanna ask,like how to make GUI,point 'n shoot menus,some simple 2D games like Pacman,Mario etc,i"ll help you out...(That is if i find time from my Multi-processor ordeal)

bye!

raphics in C Language

We will restrict our discussion on Graphics in C Language to 16 bit C programming and MS DOS environment. In a C Program first of all you need to initialize the graphics drivers on the computer. This is done using the initgraph method provided in graphics.h library. In the next few pages we will discuss graphics.h library in details. Important functions in graphic.h library will be discuees in details and samples programmes will be provided to show the power of C programming language.

Graphics mode Initialization

First of all we have to call the initgraph function that will intialize the graphics mode on the computer. initigraph have the following prototype.

void initgraph(int far *graphdriver, int far *graphmode, char far *pathtodriver);

Initgraph initializes the graphics system by loading a graphics driver from disk (or validating a registered driver) then putting the system into

graphics mode.Initgraph also resets all graphics settings (color, palette, current position, viewport, etc.) to their defaults, then resets graphresult to 0.

*graphdriver

Integer that specifies the graphics driver to be used. You can give graphdriver a value using a constant of the graphics_drivers enumeration type.

*graphmode

Integer that specifies the initial graphics mode (unless *graphdriver = DETECT). If *graphdriver = DETECT, initgraph sets *graphmode to the highest resolution available for the detected driver. You can give *graphmode a value using a constant of the graphics_modes enumeration type.

*pathtodriver

Specifies the directory path where initgraph looks for graphics drivers (*.BGI) first.

1. If they’re not there, initgraph looks in the current directory.

2. If pathtodriver is null, the driver files must be in the current directory.

*graphdriver and *graphmode must be set to valid graphics_drivers and graphics_mode values or you’ll get unpredictable results. (The exception is graphdriver = DETECT.)

After a call to initgraph, *graphdriver is set to the current graphics driver, and *graphmode is set to the current 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.

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.

Here is a sample program that initializes the graphics mode in C Language.

#include <graphics.h>

#include <stdlib.h>

#include <stdio.h>

#include <conio.h>

int main(void)

{

/* request auto detection */

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;

}

The graphics programming in c language is discussed in brief to provide an over view to the beginner.

/* Sample program to draw a circle*/

#include<graphics.h>

#include<conio.h>

main()

{

int gd=DETECT,gm;

initgraph(&gd,&gm,""); /* initialization of graphic mode */

circle(150,150,100);

getch();

closegraph(); /* Restore orignal screen mode */

}

/* End of program */

Normally the screen which u view in DOS is in the text mode which means it is meant for text. And for graphics u need to initialize graphics mode. And for this to happen u need to include graphics.h?.

circle(x coordinate ,y coordinate , radius);

The circle command takes a X coordinate which means Vertical axis and Y coordinate which means Horizontal axis. And the last one is the radius of the circle. closegraph();

With out this function the screen mode will still remain in graphic mode and when u come out, to DOS u will see a different screen, which is not in the text mode.

/*A program to draw a space with stars*/

#include<graphics.h>

main()

{

int gd=DETECT,gm;

int i,x,y;

initgraph(&gd,&gm,"");

line(0,0,640,0);

line(0,0,0,480);

line(639,0,639,480);

line(639,479,0,479);

for(i=0;i<=1000;i++)

{

x=rand()%639;

y=rand()%480;

putpixel(x,y,15);

}

getch();

closegraph();

}

/* End of program */

/*Here a sample program to illustrate how to use BARS which are used for visual

statistics */

#include<graphics.h>

main() {

int gd=DETECT,gm,maxx,maxy,x,y,button;

initgraph(&gd,&gm,"");

line(80,150,200,150);

line(80,150,80,50);

settextstyle(1,HORIZ_DIR,1);

outtextxy(100,153,"<-X axis");

settextstyle(1,VERT_DIR,1);

outtextxy(60,50,"<-Y axis");

bar(100,100,120,150);

bar(130,120,150,150);

getch();

closegraph();

}

PNGwriter is a C++ library for creating PNG images.

(If you can't see the navigation frame at the left of the page, then click here). 

Latest News: 

New! - PNGwriter version 0.5.4 is available! Download it here and read about it here. 

PNGwriter has been included in the Debian Linux distribution, thanks to

the hard work of Miguel Gea Milvaques! Read about it here! 

Want to keep up to date? Have a question or a problem? Browse the forums (The mailing lists are no longer being used as a support method). 

Do you have an interesting image, program or implementation you created with PNGwriter's help? Send it in, or tell the world about in the forum. 

Take a look at the poster that I presented at the Second Simposium of Chilean Physics Students (21, 22 and 23 of July, 2004). (PDF, about 6 MB, in spanish, TGZ | ZIP) 

Visit PNGwriter's SourceForge.net Project Page and Freshmeat.net Project Page.

Summary 

PNGwriter is a very easy to use open source graphics library that uses PNG as its output format. The interface has been designed to be as simple and intuitive as possible. It supports plotting and reading in the RGB (red, green, blue), HSV (hue, saturation, value/brightness) and CMYK (cyan, magenta, yellow, black) colour spaces, basic shapes, scaling, bilinear interpolation, full TrueType antialiased and rotated text support, bezier curves, opening existing PNG images and more. Documentation in English and Spanish. Runs under Linux, Unix, Mac OS X and Windows. Requires libpng and optionally FreeType2 for the text support.

Frequently Asked Questions: 

Why use the PNGwriter library?

What can I do with PNGwriter?

What *can't* I do with PNGwriter?

Why use PNG images?

Who might benefit from this C++ library?

What do I need to use this library?

Sounds interesting, how do I use it?

Can PNGwriter draw text and graph axes?

How can I use PNGwriter under Windows?

What's in the PNGwriter package?

What can I do if I can't/don't want to install libpng?

What is PNGwriter's current development status?

How can I link to the PNGwriter project from my page?

If your questions are not answered here, then post on the PNGwriter Forums, or send me an email.

Why use the PNGwriter library? 

Because it is a fast and easy way of plotting directly from your C++ program.

PNGwriter lets you focus on your program, and saves you the trouble of learning how to create, use and read PNG images from scratch. You just need to specify what size you want your image, and then you go plotting pixel by pixel in a given colour with the plot function. 

PNGwriter was originally written with scientists in mind. The need to create an image from the result of a scientific computer simulation arises as a natural part of scientific programming. Getting the data out of the program and into a high quality image in an efficient way can sometimes be hard, especially if the user is not a very experienced programmer. The methods used can often be highly inefficient or too complex to be feasible. 

If the data is in (x, y) form, then one can use any of the many plotting programs out there, like gnuplot, R. Brühl's excellentAbscissa and so on. 

If, on the other hand, the data is in (x, y, z) form, one must choose how to represent the third variable. Software such asMathematica offers many alternatives in this respect, but if the amount of data points is considerable, rendering an image using Mathematica as an array of pixels using text-based data is many, many times slower than rendering the

image to disk from the C++ program itself. Consider the bottlenecks involved: the program must produce a file, writing the data in ASCII mode. This is about two orders of magnitude slower than outputting the data in binary mode. It must then be rendered by Mathematica, using vector graphics (one object per pixel, though newer versions of Mathematica have better graphics handling capabilities). It is only at this stage that one can convert the image to a lossless bitmap image format such as PNG or TIFF. Another possibility is to use ImageMagick or Netpbm to process the data, but again, one is limited by the fact that the data must be written in ASCII format first, and support for 24-bit colour in the PPM file format is not standardized (i.e., mostly non-existent) and is endian-dependent. 

PNGwriter was written as a possible solution to this issue. Its interface is extremely intuitive, there is only one new object to learn about (the PNGwriter class), in other words, no classes and subclasses for pixels, colours, bitmaps, filenames, etc. As long as you know what colour you want the pixel at position (x, y) to be, you can implement any algorithm you want. Want to play with cellular automata but are tired of seeing you results as an array of 1s and 0s in text? Want to have a go at exploring fractals yourself? Need a quick way to implement that image-recognition algorithm you are working on for your autonomous rover, driverless vehicle or robot arm? Want to simulate gravitational lensing but haven't yet been able to create an actual image from your algorithm? Need to simulate an object moving on an energy surface, using interpolation between the available data points? PNGwriter can help! 

What can I do with PNGwriter? 

PNGwriter enables you to do the following with an image:

o       Ploto       Get the colour of a pixelo       Open an already-existing PNG file.o       Plot in the HSV and CMYK colour spaces.o       Get the colour of a pixel in the HSV and CMYK colour spaces.o       Plot lines, filled or hollow circles and rectangles, opaque and translucent.o       Plot text, using any TrueType font.o       Adjust the image's gamma.o       Choose the level of compression.o       Change the file name.o       Scale the image.o       Get the height, width and bit depth of an image.o       and much more!.

Since one can generate an arbitrary number of PNG images with only one run of your

program, and given that PNGwriter provides an easy way of renaming files given just an index number, creating movies of sequential images is now extremely easy. For this, one would just use MEncoder, or Apple's Quicktime Player. 

What *can't* I do with PNGwriter? 

There are certain things that PNGwriter will not do. For example, though PNGwriter (as of version 0.5.4) can read a very wide variety of PNG images, there are some variants that it has problems with. In summary: 

Alpha channel information is completely discarded when reading PNG images. Images with GIF-style transparency will not be read properly. Some images will be read with a slightly different chromatic quality.

Despite these limitations, PNGwriter will most likely read the vast majority of PNGs that you throw at it. Please see the Examples section for a detailed list of test images and how PNGwriter deals with them. 

Why use PNG images? Because they are widely known and they use lossless compression.

They share some characteristics with GIF images, but unlike this format, PNG images are not tied by the copyright of the LZW compression that GIFs use.

The PNG format is open, free, and good.

They offer the possibility of using Alpha Channels (better than simple transparency, though please note that PNGwriter supports neither) and a whole lot of other useful and interesting things.

You don't even have to convert the PNG images your program can make with PNGwriter if you want to use them on a web page, for example: as a matter of fact, PNG stands for Portable Network Graphics-- they were designed for internet use and any decent browser can view them. Most of the graphics on this site are PNG images. 

For more information, please visit www.libpng.org. 

Who might benefit from using this C++ library? 

I wrote PPMWriter (see below) because I wanted something that would allow me to plot pixel by pixel to an image, giving the coordinates and colour coefficients. It was useful (though PNGwriter has come far, far further than PPMWriter) yet limited and not entirely bug-free :-), but there werent many programs that could open PPM images properly. So I wrote PNGwriter.

In principle it could be useful to anyone that needs to plot images of high quality generated by their C++ programs (simulations, calculations, etc.), and not diagrams or (x, y) line plots.

What do I need to be able to use PNGwriter? 

A C++ compiler, and libpng. libpng works on Unix, DOS, OS/2, Windows, Mac OS, BeOS, Amiga, etc. If your compiler is old, my personal recommendation is to get GCC. See www.cplusplus.com/info/compilers/#free for some information on free compilers. Also, if you wish to compile PNGwriter with text support, you will need FreeType2. If you're on Windows, check the How can I use PNGwriter under Windows? section.

Sounds interesting, how is it used? 

If you want to see an example of the simplest possible use of PNGwriter, go to Quickstart. That is the bare minimum that you need to know to be able to use PNGwriter (and all you need to know, in most cases).

If you want to see more examples of PNGwriter in use, go to Examples. If you want to have a look at the PNGwriter manual go to Manual. The PNGwriter

package available inDownloads contains two complete examples and a PDF Manual. The header file for the library is also extensively commented.

If you want to ask a question, you can send an email to the email you'll find in Contacts, or you can post a messasge on the forum.

Can PNGwriter draw text and graph axes? 

Yes, PNGwriter now has full text support capabilities (including UTF-8 support), but it does not do axes. Here is the official reason: PNGwriter is aimed at the fast and intuitive creation of high quality images in scientific and image processing contexts. Any bitmap image requiring axes and that must be published at publication-

quality should be using vector graphics for the axes (and maybe the text), not bitmap, and combine both in an EPS.

So, is all lost? Is there nothing that can be done? Of course not! Here's a solution: Create PNG images of the graph axes you want to add using your method of choice (The Gimp, Photoshop, etc.). Make it black on white, for example. From your program, open this file with PNGwriter. Write a simple routine that takes all black pixels, and plots them onto your image, at the position you specify, and in whatever colour you want. This can be automated so that it is done after every image has been completed. 

How do I use PNGwriter under Windows? 

Please note: Though there are guides on this site for compiling PNGwriter under Windows using some popular compilers, I cannot offer support for this task.

You should get hold of a Windows implementation of GCC, the free GNU C/C++ compiler (two possible ways to do this are www.mingw.org and www.cygwin.com). You can also use the Borland C++ Builder or Microsoft Visual C++ .NET on Windows XP. Here are two clear, step-by-step HowTos: " Setting Up PNGWriter for Borland C++ Builder Version 6 on Windows XP" and "Setting Up PNGWriter for Microsoft Visual C++ .NET on Windows XP".

Also, using PNGwriter with Bloodshed Dev C++ is quite easy, as pointed out by Siva Chandra: "You can download the pre-compiled libraries for freetype from the GnuWin32 web-site: gnuwin32.sf.net. To build PNGwriter itself, create a new C++ library project called libpngwriter. Include the PNGwriter header file and the implementation file into this new project. Then compile. And thats it. You will have a libpngwriter.a file ready for use. Note that this will by default assume availability of freetype. To remove such assumption, you will have to compile with this option: -DNO_FREETYPE".

Please note: pngwriter.cc has to be renamed to pngwiter.cpp for MSVC7. If the extension is not changed then the C/C++ folder for the project property does not become visible and hence the MSVC7's default of using compiled headers in its project build will always return an error about being unable to find some precompiled header. It is necessary to change that feature in the project property in order to successfully build the PNGwriter library using this compiler.

What's in the PNGwriter package? The source tarball/zip file contains the following items:

pngwriter-x.y.z       .       |-- Makefile

       |-- README       |-- configure       |-- doc       |   |-- english       |   |   |-- CHANGES       |   |   |-- EXAMPLES       |   |   |-- LICENSE       |   |   |-- PNGwriterQuickReference_EN.pdf       |   |   `-- README       |   `-- espaniol       |       |-- CAMBIOS       |       |-- EJEMPLOS       |       |-- LEAME       |       |-- LICENCIA       |       `-- PNGwriterQuickReference_ES.pdf       |-- examples       |   |-- Makefile       |   |-- burro.png       |   |-- lyapunov.cc       |   |-- lyapunov.espaniol.cc       |   |-- pngtest.cc       |   `-- pngtest.espaniol.cc       |-- fonts       |   |-- FreeMonoBold.ttf       |   `-- FreeSansBold.ttf       |-- make.include -> make.include.linux       |-- make.include.linux       |-- make.include.linux.oldcpp       |-- make.include.osx       `-- src           |-- Makefile           |-- pngwriter.cc           `-- pngwriter.h

What can I do if I don't want to/can't install libpng? 

In principle, everyone should be able to use PNGwriter, even Windows users (see "How do I use PNGwriter under Windows?").

If they don't wish to, then there is always PPMWriter. It's a C++ class to make PPM images. They are simpler than PNG images, and less programs will correctly display them, but you can use this class on ANY computer and it is entirely self-contained. More information can be found at ket.dyndns.org/ppmwriter. Please Note: Development of PPMWriter ceased quite a while ago, and has only a fraction of the functions that PNGwriter has. I cannot offer support for PPMWriter. 

How can I link to the PNGwriter project from my page? 

Did you find PNGwriter useful? If so, spread the word, and tell others about it, by placing the following button on you project page. You never know, it might be just what someone was looking for!

If you want, you can link directly to the image on the PNGwriter site. In that case, the code to add to your page would be: 

<a href="http://pngwriter.sourceforge.net/"><img src="http://pngwriter.sourceforge.net/site_images/madewith.png" width="88" height="31" alt="Made With PNGwriter" BORDER="0" target="_blank"></a> 

What is PNGwriter's current development status? 

Though I consider PNGwriter to be in active development, versions are not rushed out the door just to increase the version number. In fact, you can expect quite some time to elapse between releases. This is due partly to my own time constraints but also because I do not want to turn PNGwriter into a do-it-all library. There are already enough libraries that offer full PNG support.

I do, however, pledge to not let so much time pass between releases when I have been notified of bugs (as happened with the 0.5.3 -> 0.5.4 update). 

About the Author 

I live in Santiago, Chile and Albuquerque, New Mexico. You might want to take a look at my blog, if you're into photography (or just nice photographs) or motorcycling. There's an English edition (The Flight of the Platypus) and a Spanish edition (El Cantar De La Lluvia), the latter of which is far larger.

Update (9/12/2006):It's been quite some time since I've updated this page; in fact, I lost track of it for awhile. In the hopes that it may still be useful, I've updated this tutorial to be current with the latest version of Dev-C++ (as of this writing, Version 5 Beta 9--a.k.a. Version 4.9.9.2). ‹‹ Mike ››

What is Dev-C++?   Click picture to enlarge.

Dev-C++, developed by Bloodshed Software, is a fully featured graphical IDE (Integrated Development Environment), which is able to create Windows or console-based C/C++ programs using the MinGW compiler system. MinGW (Minimalist GNU* for Windows) uses GCC (the GNU g++ compiler collection), which is essentially the same compiler system that is in Cygwin (the unix environment program for Windows) and most versions of Linux. There are, however, differences between Cygwin and MinGW; link to Differences between Cygwin and MinGW for more information.

*GNU is a recursive acronym for "GNU's Not Unix"; it is pronounced "guh-NEW". The GNU Project was launched in 1984 to develop a free and complete Unix-like operating system.

Bloodshed!?I'll be the first to say that the name Bloodshed won't give you warm and fuzzies, but I think it's best if the creator of Bloodshed explains:

First I would like to say that I am not a satanist, that I hate violence/war and that I don't like heavy metal / hard-rock music. I am french, but I do know the meaning of the "Bloodshed" word, and I use this name because I think it sounds well. If you are offended by the name, I am very sorry but it would be a big mess to change the name now.

There's also a reason why I keep the Bloodshed name. I don't want people to think Bloodshed is a company, because it isn't. I'm just doing this to help people.

Here is a good remark on the Bloodshed name I received from JohnS:I assumed that this was a reference to the time and effort it requires of you to make these nice software programs, a la "Blood, Sweat and Tears".

Peace and freedom,

Colin Laplace

Getting Dev-C++The author has released Dev-C++ as free software (under GPL) but also offers a CD for purchase which can contain all Bloodshed software (it's customizable), including Dev-C++ with all updates/patches.

Link to Bloodshed Dev-C++ for a list of Dev-C++ download sites.

You should let the installer put Dev-C++ in the default directory of C:\Dev-Cpp, as it will make it easier to later install add-ons or upgrades.

Using Dev-C++This section is probably why you are here.

All programming done for CSC161 will require separate compilation projects (i.e. class header file(s), class implementation file(s) and a main/application/client/driver file). This process is relatively easy as long as you know what Dev-C++ requires to do this.

Step 1: Configure Dev-C++.We need to modify one of the default settings to allow you to use the debugger with your programs.

Go to the "Tools" menu and select "Compiler Options". In the "Settings" tab, click on "Linker" in the left panel, and change "Generate

debugging information" to "Yes":

Click "OK".

Step 2: Create a new project. A "project" can be considered as a container that is used to store all the elements that are required to compile a program.

Go to the "File" menu and select "New", "Project...". Choose "Empty Project" and make sure "C++ project" is selected.

Here you will also give your project a name. You can give your project any valid filename, but keep in mind that the name of your project will also be the name of your final executable.

Once you have entered a name for your project, click "OK". Dev-C++ will now ask you where to save your project.

Step 3: Create/add source file(s). You can add empty source files one of two ways:

Go to the "File" menu and select "New Source File" (or just press CTRL+N) OR Go to the "Project" menu and select "New File".

Note that Dev-C++ will not ask for a filename for any new source file until you attempt to:

1. Compile2. Save the project3. Save the source file4. Exit Dev-C++

You can add pre-existing source files one of two ways:

Go to the "Project" menu and select "Add to Project" OR Right-click on the project name in the left-hand panel and select "Add to

Project". 

EXAMPLE: Multiple source files 

In this example, more than 3 files are required to compile the program; The "driver.cpp" file references "Deque.h" (which requires "Deque.cpp") and "Deque.cpp" references "Queue.h" (which requires "Queue.cpp").

Step 4: Compile.Once you have entered all of your source code, you are ready to compile.

Go to the "Execute" menu and select "Compile" (or just press CTRL+F9).

It is likely that you will get some kind of compiler or linker error the first time you attempt to compile a project. Syntax errors will be displayed in the "Compiler" tab at the bottom of the screen. You can double-click on any error to take you to the place in the source code where it occurred. The "Linker" tab will flash if there are any linker errors. Linker errors are generally the result of syntax errors not allowing one of the files to compile.

Once your project successfully compiles, the "Compile Progress" dialog box will have a status of "Done". At this point, you may click "Close".

Step 5: Execute.You can now run your program.

Go to the "Execute" menu, choose "Run".

Note: to pass command-line parameters to your program, go to the "Execute" menu, choose "Parameters" and type in any paramaters you wish to pass.

Disappearing windowsIf you execute your program (with or without parameters), you may notice something peculiar; a console window will pop up, flash some text and disappear. The problem is that, if directly executed, console program windows close after the program exits. You can solve this problem one of two ways:

Method 1 - Scaffolding:Add the following code before any return statement in main() or any exit() or abort() statement (in any function):

/* Scaffolding code for testing purposes */ cin.ignore(256, '\n');cout << "Press ENTER to continue..." << endl;cin.get();/* End Scaffolding */ 

This will give you a chance to view any output before the program terminates and the window closes.

Method 2 - Command-prompt:Alternatively, instead of using Dev-C++ to invoke your program, you can just open an MS-DOS Prompt, go to the directory where your program was compiled (i.e. where you saved the project) and enter the program name (along with any parameters). The command-prompt window will not close when the program terminates.

For what it's worth, I use the command-line method.

Step 6: Debug.When things aren't happening the way you planned, a source-level debugger can be a great tool in determining what really is going on. Dev-C++'s basic debugger functions are controlled via the "Debug" tab at the bottom of the screen; more advanced functions are available in the "Debug" menu.

Using the debugger:The various features of the debugger are pretty obvious. Click the "Run to cursor" icon to run your program and pause at the current source code cursor location; Click "Next Step" to step through the code; Click "Add Watch" to monitor variables.Setting breakpoints is as easy as clicking in the black space next to the line in the source code.See the Dev-C++ help topic "Debugging Your Program" for more information.

Dev-C++ User F.A.Q.

Why do I keep getting errors about "cout", "cin", and "endl" being undeclared?It has to do with namespaces. You need to add the following line after the includes of your implementation (.cpp) files:

using namespace std;

How do I use the C++ string class?Again, it probably has to do with namespaces. First of all, make sure you "#include <string>" (not string.h). Next, make sure you add "using namespace std;" after your includes.

Example:

#include <iostream> #include <string> using namespace std;

int main() { string s; s = "This is a test"; cout << s << endl; system("PAUSE"); return 0;

}

How do I use Borland Graphics Interface (graphics.h)?For those of you migrating from Borland, you may be wondering where graphics.h is. Unfortunately, graphics.h is a Borland specific library and cannot be used with Dev-C++. Fortunately, a benevolent soul by the name of Michael Main has modified a BGI emulation library for Windows applications to be used under MinGW (and therefore Dev-C++) which he has aptly named WinBGIm.

The files we need are:

graphics.h (download to C:\Dev-Cpp\include)libbgi.a (download to C:\Dev-Cpp\lib)

After you have downloaded the files to the correct locations, you can now use WinBGIm's graphic.h as you would Borland's graphics.h with a few caveats.

Using library files:First, you have to tell Dev-C++ where to find the library functions that WinBGIm references--this is done in the "Project Options" dialog box.Here are instructions on how to do this with a new project:

Follow step 2 and step 3 of "Using Dev-C++". Go to "Project" menu and choose "Project Options" (or just press ALT+P). Go to the "Parameters" tab In the "Linker" field, enter the following text:

-lbgi-lgdi32-lcomdlg32-luuid-loleaut32-lole32

Project Options -> Parameters:

Click "OK". Follow step 4, step 5 and step 6 of "Using Dev-C++".

BGI and WinBGIm differences:WinBGIm is a superset of BGI and as such may have functions and features with which you are unfamiliar. See Michael Main's BGI Documentation for more information.

Test code:Just to make sure you've got everything set up correctly, try this test code in a new Dev-C++ WinBGIm project:

#include <graphics.h>

int main() { initwindow(400,300); //open a 400x300 graphics window moveto(0,0); lineto(50,50); while(!kbhit()); //wait for user to press a key closegraph(); //close graphics window return 0; }

If you've done everything correctly, you should get a simple graphic that closes when the user presses a key.

Where is <sstream> (string streams)?In previous versions of Dev-C++, the included compiler did not implement sstream. Fortunately, new versions of Dev-C++ do not have this problem. Upgrade to the latest version of Dev-C++.