home *** CD-ROM | disk | FTP | other *** search
/ Windows Game Programming for Dummies (2nd Edition) / WinGamProgFD.iso / mac / Source / GPCHAP10 / PROG10_6.CPP < prev    next >
C/C++ Source or Header  |  2002-04-27  |  16KB  |  558 lines

  1. // PROG10_6.CPP - a 640x480x8 bitmap loader
  2.  
  3. // INCLUDES ///////////////////////////////////////////////
  4. #define WIN32_LEAN_AND_MEAN  
  5. #define INITGUID
  6.  
  7.  
  8. #include <windows.h>   // include important windows stuff
  9. #include <windowsx.h> 
  10. #include <mmsystem.h>
  11. #include <iostream.h> // include important C/C++ stuff
  12. #include <conio.h>
  13. #include <stdlib.h>
  14. #include <malloc.h>
  15. #include <memory.h>
  16. #include <string.h>
  17. #include <stdarg.h>
  18. #include <stdio.h>
  19. #include <math.h>
  20. #include <io.h>
  21. #include <fcntl.h>
  22.  
  23. #include <ddraw.h>  // directX includes
  24.  
  25. // DEFINES ////////////////////////////////////////////////
  26.  
  27. // defines for windows 
  28. #define WINDOW_CLASS_NAME "WINXCLASS"  // class name
  29.  
  30. #define WINDOW_WIDTH  640         // size of window
  31. #define WINDOW_HEIGHT 480
  32. #define SCREEN_WIDTH  640         // size of screen
  33. #define SCREEN_HEIGHT 480
  34. #define SCREEN_BPP    8          // bits per pixel
  35.  
  36. #define BITMAP_ID     0x4D42      // universal id for a bitmap
  37.  
  38. // MACROS /////////////////////////////////////////////////
  39.  
  40. // these read the keyboard asynchronously
  41. #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
  42. #define KEY_UP(vk_code)   ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)
  43.  
  44. // this builds a 16 bit color value in 5.5.5 format (1-bit alpha mode)
  45. #define _RGB16BIT555(r,g,b) ((b & 31) + ((g & 31) << 5) + ((r & 31) << 10))
  46.  
  47. // this builds a 16 bit color value in 5.6.5 format (green dominate mode)
  48. #define _RGB16BIT565(r,g,b) ((b & 31) + ((g & 63) << 5) + ((r & 31) << 11))
  49.  
  50.  
  51. // TYPES //////////////////////////////////////////////////
  52.  
  53. typedef unsigned short USHORT;
  54. typedef unsigned short WORD;
  55. typedef unsigned char  UCHAR;
  56. typedef unsigned char  BYTE;
  57.  
  58. // container structure for bitmaps .BMP file
  59. typedef struct BITMAP_FILE_TAG
  60.         {
  61.         BITMAPFILEHEADER bitmapfileheader;  // this contains the bitmapfile header
  62.         BITMAPINFOHEADER bitmapinfoheader;  // this is all the info including the palette
  63.         PALETTEENTRY     palette[256];      // we will store the palette here
  64.         UCHAR            *buffer;           // this is a pointer to the data
  65.  
  66.         } BITMAP_FILE, *BITMAP_FILE_PTR;
  67.  
  68. // PROTOTYPES /////////////////////////////////////////////
  69.  
  70. int Game_Init(void *parms=NULL);
  71. int Game_Shutdown(void *parms=NULL);
  72. int Game_Main(void *parms=NULL);
  73.  
  74. int Load_Bitmap_File(BITMAP_FILE_PTR bitmap, char *filename);
  75. int Unload_Bitmap_File(BITMAP_FILE_PTR bitmap);
  76. int Flip_Bitmap(UCHAR *image, int bytes_per_line, int height);
  77.  
  78. // GLOBALS ////////////////////////////////////////////////
  79.  
  80. HWND main_window_handle = NULL; // save the window handle
  81. HINSTANCE main_instance = NULL; // save the instance
  82. char buffer[80];                // used to print text
  83.  
  84. LPDIRECTDRAW7        lpdd         = NULL;  // dd object
  85. LPDIRECTDRAWSURFACE7 lpddsprimary = NULL;  // dd primary surface
  86. LPDIRECTDRAWSURFACE7 lpddsback    = NULL;  // dd back surface
  87. LPDIRECTDRAWPALETTE  lpddpal      = NULL;  // a pointer to the created dd palette
  88. PALETTEENTRY         palette[256];         // color palette
  89. DDSURFACEDESC2       ddsd;                 // a direct draw surface description struct
  90. DDSCAPS2             ddscaps;              // a direct draw surface capabilities struct
  91. HRESULT              ddrval;               // result back from dd calls
  92. UCHAR                *primary_buffer = NULL; // primary video buffer
  93. BITMAP_FILE          bitmap16bit,            // a 16 bit bitmap file
  94.                      bitmap8bit;             // a 8 bit bitmap file
  95.  
  96. // FUNCTIONS //////////////////////////////////////////////
  97.  
  98. LRESULT CALLBACK WindowProc(HWND hwnd, 
  99.                             UINT msg, 
  100.                             WPARAM wparam, 
  101.                             LPARAM lparam)
  102. {
  103. // this is the main message handler of the system
  104. PAINTSTRUCT    ps;           // used in WM_PAINT
  105. HDC            hdc;       // handle to a device context
  106.  
  107. // what is the message 
  108. switch(msg)
  109.     {    
  110.     case WM_CREATE: 
  111.         {
  112.         // do initialization stuff here
  113.         return(0);
  114.         } break;
  115.  
  116.     case WM_PAINT:
  117.          {
  118.          // start painting
  119.          hdc = BeginPaint(hwnd,&ps);
  120.  
  121.          // end painting
  122.          EndPaint(hwnd,&ps);
  123.          return(0);
  124.         } break;
  125.  
  126.     case WM_DESTROY: 
  127.         {
  128.         // kill the application            
  129.         PostQuitMessage(0);
  130.         return(0);
  131.         } break;
  132.  
  133.     default:break;
  134.  
  135.     } // end switch
  136.  
  137. // process any messages that we didn't take care of 
  138. return (DefWindowProc(hwnd, msg, wparam, lparam));
  139.  
  140. } // end WinProc
  141.  
  142. // WINMAIN ////////////////////////////////////////////////
  143.  
  144. int WINAPI WinMain(    HINSTANCE hinstance,
  145.                     HINSTANCE hprevinstance,
  146.                     LPSTR lpcmdline,
  147.                     int ncmdshow)
  148. {
  149.  
  150. WNDCLASS winclass;    // this will hold the class we create
  151. HWND     hwnd;        // generic window handle
  152. MSG         msg;        // generic message
  153. HDC      hdc;       // generic dc
  154. PAINTSTRUCT ps;     // generic paintstruct
  155.  
  156. // first fill in the window class stucture
  157. winclass.style            = CS_DBLCLKS | CS_OWNDC | 
  158.                           CS_HREDRAW | CS_VREDRAW;
  159. winclass.lpfnWndProc    = WindowProc;
  160. winclass.cbClsExtra        = 0;
  161. winclass.cbWndExtra        = 0;
  162. winclass.hInstance        = hinstance;
  163. winclass.hIcon            = LoadIcon(NULL, IDI_APPLICATION);
  164. winclass.hCursor        = LoadCursor(NULL, IDC_ARROW);
  165. winclass.hbrBackground    = (HBRUSH)GetStockObject(BLACK_BRUSH);
  166. winclass.lpszMenuName    = NULL; 
  167. winclass.lpszClassName    = WINDOW_CLASS_NAME;
  168.  
  169. // register the window class
  170. if (!RegisterClass(&winclass))
  171.     return(0);
  172.  
  173. // create the window, note the use of WS_POPUP
  174. if (!(hwnd = CreateWindow(WINDOW_CLASS_NAME, // class
  175.                           "WinX Game Console",     // title
  176.                           WS_POPUP | WS_VISIBLE,
  177.                            0,0,       // x,y
  178.                           WINDOW_WIDTH,  // width
  179.                           WINDOW_HEIGHT, // height
  180.                           NULL,       // handle to parent 
  181.                           NULL,       // handle to menu
  182.                           hinstance,// instance
  183.                           NULL)))    // creation parms
  184. return(0);
  185.  
  186. // hide the mouse
  187. ShowCursor(FALSE);
  188.  
  189. // save the window handle and instance in a global
  190. main_window_handle = hwnd;
  191. main_instance      = hinstance;
  192.  
  193. // perform all game console specific initialization
  194. Game_Init();
  195.  
  196. // enter main event loop
  197. while(1)
  198.     {
  199.     if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
  200.         { 
  201.         // test if this is a quit
  202.         if (msg.message == WM_QUIT)
  203.            break;
  204.     
  205.         // translate any accelerator keys
  206.         TranslateMessage(&msg);
  207.  
  208.         // send the message to the window proc
  209.         DispatchMessage(&msg);
  210.         } // end if
  211.     
  212.     // main game processing goes here
  213.     Game_Main();
  214.  
  215.     } // end while
  216.  
  217. // shutdown game and release all resources
  218. Game_Shutdown();
  219.  
  220. // return to Windows like this
  221. return(msg.wParam);
  222.  
  223. } // end WinMain
  224.  
  225. // WINX GAME PROGRAMMING CONSOLE FUNCTIONS ////////////////
  226.  
  227. int Game_Init(void *parms)
  228. {
  229. // this function is where you do all the initialization 
  230. // for your game
  231.  
  232. // create object and test for error
  233. if (DirectDrawCreateEx(NULL, (void **)&lpdd, IID_IDirectDraw7, NULL)!=DD_OK)
  234.    return(0);
  235.  
  236.  
  237. // set cooperation level to windowed mode normal
  238. if (lpdd->SetCooperativeLevel(main_window_handle,
  239.            DDSCL_ALLOWMODEX | DDSCL_FULLSCREEN | 
  240.            DDSCL_EXCLUSIVE | DDSCL_ALLOWREBOOT)!=DD_OK)
  241.     return(0);
  242.  
  243. // set the display mode
  244. if (lpdd->SetDisplayMode(SCREEN_WIDTH,SCREEN_HEIGHT,SCREEN_BPP,0,0)!=DD_OK)
  245.    return(0);
  246.  
  247. // Create the primary surface
  248. memset(&ddsd,0,sizeof(ddsd));
  249. ddsd.dwSize         = sizeof(ddsd);
  250. ddsd.dwFlags        = DDSD_CAPS;
  251. ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
  252.  
  253. if (lpdd->CreateSurface(&ddsd,&lpddsprimary,NULL)!=DD_OK)
  254.    return(0);
  255.  
  256. // create and attach palette
  257.  
  258. // create palette data
  259. // first clear out all the entries, defensive programming
  260. memset(palette,0,256*sizeof(PALETTEENTRY));
  261.  
  262. // create a R,G,B,GR gradient palette
  263. for (int index=0; index < 256; index++)
  264.     {
  265.     // set flags
  266.     palette[index].peFlags = PC_NOCOLLAPSE;
  267.     } // end for index
  268.  
  269. // now create the palette object
  270. if (lpdd->CreatePalette(DDPCAPS_8BIT | DDPCAPS_INITIALIZE | DDPCAPS_ALLOW256,
  271.                          palette,&lpddpal,NULL)!=DD_OK)
  272.    return(0);
  273.  
  274. // attach the palette to the primary
  275. if (lpddsprimary->SetPalette(lpddpal)!=DD_OK)
  276.    return(0);
  277.  
  278. // now load the 8 bit color bitmap
  279. Load_Bitmap_File(&bitmap8bit, "ANDRE8.BMP");
  280.  
  281. // now load the palette into the directdraw
  282. lpddpal->SetEntries(0,0,256,bitmap8bit.palette);
  283.  
  284. // return success
  285. return(1);
  286.  
  287. } // end Game_Init
  288.  
  289. ///////////////////////////////////////////////////////////
  290.  
  291. int Game_Shutdown(void *parms)
  292. {
  293. // this function is where you shutdown your game and
  294. // release all resources that you allocated
  295.  
  296. // first release the primary surface
  297. if (lpddsprimary!=NULL)
  298.    lpddsprimary->Release();
  299.        
  300. // release the directdraw object
  301. if (lpdd!=NULL)
  302.    lpdd->Release();
  303.  
  304. // delete the bitmap 
  305. Unload_Bitmap_File(&bitmap8bit);
  306.  
  307. // return success
  308. return(1);
  309. } // end Game_Shutdown
  310.  
  311. ///////////////////////////////////////////////////////////
  312.  
  313. int Game_Main(void *parms)
  314. {
  315. // this is the workhorse of your game it will be called
  316. // continuously in real-time this is like main() in C
  317. // all the calls for you game go here!
  318.  
  319. // check of user is trying to exit
  320. if (KEY_DOWN(VK_ESCAPE) || KEY_DOWN(VK_SPACE))
  321.     PostMessage(main_window_handle, WM_DESTROY,0,0);
  322.  
  323. // set up the surface description to lock the surface
  324. memset(&ddsd,0,sizeof(ddsd)); 
  325. ddsd.dwSize = sizeof(ddsd);
  326.  
  327. // lock the primary surface, note in a real game you would
  328. lpddsprimary->Lock(NULL,&ddsd, 
  329.                    DDLOCK_SURFACEMEMORYPTR | DDLOCK_WAIT,NULL);
  330.  
  331. // get video pointer
  332. primary_buffer = (UCHAR *)ddsd.lpSurface;
  333.  
  334. // copy each bitmap line into primary buffer 
  335. // taking into consideration non-linear video 
  336. // cards and the memory pitch lPitch
  337. for (int y=0; y < SCREEN_HEIGHT; y++)
  338.     {
  339.     // copy the line
  340.     memcpy(&primary_buffer[y*ddsd.lPitch], // dest address
  341.            &bitmap8bit.buffer[y*SCREEN_WIDTH],   // src address
  342.            SCREEN_WIDTH);                        // bytes to copy
  343.     } // end for y
  344.  
  345. // unlock the surface
  346. lpddsprimary->Unlock(NULL);
  347.  
  348. // return success
  349. return(1);
  350.  
  351. } // end Game_Main
  352.  
  353. ///////////////////////////////////////////////////////////
  354.  
  355. int Load_Bitmap_File(BITMAP_FILE_PTR bitmap, char *filename)
  356. {
  357. // this function opens a bitmap file and loads the data into bitmap
  358.  
  359. int file_handle,  // the file handle
  360.     index;        // looping index
  361.  
  362. UCHAR *temp_buffer = NULL; // used to convert 24 bit images to 16 bit
  363. OFSTRUCT file_data;        // the file data information
  364.  
  365. // open the file if it exists
  366. if ((file_handle = OpenFile(filename,&file_data,OF_READ))==-1)
  367.    return(0);
  368.  
  369. // now load the bitmap file header
  370. _lread(file_handle, &bitmap->bitmapfileheader,sizeof(BITMAPFILEHEADER));
  371.  
  372. // test if this is a bitmap file
  373. if (bitmap->bitmapfileheader.bfType!=BITMAP_ID)
  374.    {
  375.    // close the file
  376.    _lclose(file_handle);
  377.  
  378.    // return error
  379.    return(0);
  380.    } // end if
  381.  
  382. // now we know this is a bitmap, so read in all the sections
  383.  
  384. // first the bitmap infoheader
  385.  
  386. // now load the bitmap file header
  387. _lread(file_handle, &bitmap->bitmapinfoheader,sizeof(BITMAPINFOHEADER));
  388.  
  389. // now load the color palette if there is one
  390. if (bitmap->bitmapinfoheader.biBitCount == 8)
  391.    {
  392.    _lread(file_handle, &bitmap->palette,256*sizeof(PALETTEENTRY));
  393.  
  394.    // now set all the flags in the palette correctly and fix the reversed 
  395.    // BGR RGBQUAD data format
  396.    for (index=0; index < 256; index++)
  397.        {
  398.        // reverse the red and green fields
  399.        int temp_color = bitmap->palette[index].peRed;
  400.        bitmap->palette[index].peRed  = bitmap->palette[index].peBlue;
  401.        bitmap->palette[index].peBlue = temp_color;
  402.        
  403.        // always set the flags word to this
  404.        bitmap->palette[index].peFlags = PC_NOCOLLAPSE;
  405.        } // end for index
  406.  
  407.     } // end if
  408.  
  409. // finally the image data itself
  410. _lseek(file_handle,-(int)(bitmap->bitmapinfoheader.biSizeImage),SEEK_END);
  411.  
  412. // now read in the image, if the image is 8 or 16 bit then simply read it
  413. // but if its 24 bit then read it into a temporary area and then convert
  414. // it to a 16 bit image
  415.  
  416. if (bitmap->bitmapinfoheader.biBitCount==8 || bitmap->bitmapinfoheader.biBitCount==16)
  417.    {
  418.    // allocate the memory for the image
  419.    if (!(bitmap->buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
  420.       {
  421.       // close the file
  422.       _lclose(file_handle);
  423.  
  424.       // return error
  425.       return(0);
  426.       } // end if
  427.  
  428.    // now read it in
  429.    _lread(file_handle,bitmap->buffer,bitmap->bitmapinfoheader.biSizeImage);
  430.  
  431.    } // end if
  432. else
  433.    {
  434.    // this must be a 24 bit image, load it in and convert it to 16 bit
  435. //   printf("\nconverting 24 bit image...");
  436.  
  437.    // allocate temporary buffer
  438.    if (!(temp_buffer = (UCHAR *)malloc(bitmap->bitmapinfoheader.biSizeImage)))
  439.       {
  440.       // close the file
  441.       _lclose(file_handle);
  442.  
  443.       // return error
  444.       return(0);
  445.       } // end if
  446.    
  447.    // allocate final 16 bit storage buffer
  448.    if (!(bitmap->buffer=(UCHAR *)malloc(2*bitmap->bitmapinfoheader.biWidth*bitmap->bitmapinfoheader.biHeight)))
  449.       {
  450.       // close the file
  451.       _lclose(file_handle);
  452.  
  453.       // release working buffer
  454.       free(temp_buffer);
  455.  
  456.       // return error
  457.       return(0);
  458.       } // end if
  459.  
  460.    // now read it in
  461.    _lread(file_handle,temp_buffer,bitmap->bitmapinfoheader.biSizeImage);
  462.  
  463.    // now convert each 24 bit RGB value into a 16 bit value
  464.    for (index=0; index<bitmap->bitmapinfoheader.biWidth*bitmap->bitmapinfoheader.biHeight; index++)
  465.        {
  466.        // extract RGB components (note they are in memory BGR)
  467.        // also, assume 5.6.5 format, so scale appropriately
  468.        UCHAR red    = (temp_buffer[index*3 + 2] >> 3), // 5 bits
  469.              green  = (temp_buffer[index*3 + 1] >> 2), // 6 bits, change to 3 for 5 bits
  470.              blue   = (temp_buffer[index*3 + 0] >> 3); // 5 bits
  471.  
  472.        // build up 16 bit color word assume 5.6.5 format
  473.        USHORT color = _RGB16BIT565(red,green,blue);
  474.  
  475.        // write color to buffer
  476.        ((USHORT *)bitmap->buffer)[index] = color;
  477.  
  478.        } // end for index
  479.  
  480.    // finally write out the correct number of bits
  481.    bitmap->bitmapinfoheader.biBitCount=16;
  482.  
  483.    } // end if
  484.  
  485. #if 0
  486. // write the file info out 
  487. printf("\nfilename:%s \nsize=%d \nwidth=%d \nheight=%d \nbitsperpixel=%d \ncolors=%d \nimpcolors=%d",
  488.         filename,
  489.         bitmap->bitmapinfoheader.biSizeImage,
  490.         bitmap->bitmapinfoheader.biWidth,
  491.         bitmap->bitmapinfoheader.biHeight,
  492.         bitmap->bitmapinfoheader.biBitCount,
  493.         bitmap->bitmapinfoheader.biClrUsed,
  494.         bitmap->bitmapinfoheader.biClrImportant);
  495. #endif
  496.  
  497. // close the file
  498. _lclose(file_handle);
  499.  
  500. // flip the bitmap
  501. Flip_Bitmap(bitmap->buffer, 
  502.             bitmap->bitmapinfoheader.biWidth*(bitmap->bitmapinfoheader.biBitCount/8), 
  503.             bitmap->bitmapinfoheader.biHeight);
  504.  
  505. // return success
  506. return(1);
  507.  
  508. } // end Load_Bitmap_File
  509.  
  510. ///////////////////////////////////////////////////////////
  511.  
  512. int Unload_Bitmap_File(BITMAP_FILE_PTR bitmap)
  513. {
  514. // this function releases all memory associated with "bitmap"
  515. if (bitmap->buffer)
  516.    {
  517.    // release memory
  518.    free(bitmap->buffer);
  519.  
  520.    // reset pointer
  521.    bitmap->buffer = NULL;
  522.  
  523.    } // end if
  524.  
  525. // return success
  526. return(1);
  527.  
  528. } // end Unload_Bitmap_File
  529.  
  530. ///////////////////////////////////////////////////////////
  531.  
  532. int Flip_Bitmap(UCHAR *image, int bytes_per_line, int height)
  533. {
  534. // this function is used to flip upside down .BMP images
  535.  
  536. UCHAR *buffer; // used to perform the image processing
  537. int index;     // looping index
  538.  
  539. // allocate the temporary buffer
  540. if (!(buffer = (UCHAR *)malloc(bytes_per_line*height)))
  541.    return(0);
  542.  
  543. // copy image to work area
  544. memcpy(buffer,image,bytes_per_line*height);
  545.  
  546. // flip vertically
  547. for (index=0; index < height; index++)
  548.     memcpy(&image[((height-1) - index)*bytes_per_line],
  549.            &buffer[index*bytes_per_line], bytes_per_line);
  550.  
  551. // release the memory
  552. free(buffer);
  553.  
  554. // return success
  555. return(1);
  556.  
  557. } // end Flip_Bitmap
  558.