/[cvs]/joko/Uni/BSArch/04/bmp_fractal.c
ViewVC logotype

Diff of /joko/Uni/BSArch/04/bmp_fractal.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.1 by joko, Fri Jun 30 20:39:33 2006 UTC revision 1.8 by joko, Sat Jul 1 22:10:42 2006 UTC
# Line 4  Line 4 
4   *   *
5   * Uebung 4.4   * Uebung 4.4
6   */   */
7    
8    // $Id$
9    
10    #include <windows.h>
11  #include <stdio.h>  #include <stdio.h>
12  #include <errno.h>  #include <errno.h>
13    
# Line 11  Line 15 
15  #define YSIZE 500  #define YSIZE 500
16  #include "algorithm.h"  #include "algorithm.h"
17    
18  /* BMP Header  
19    /* BMP Header */
20  unsigned char header[54]={0x42,0x4d,              // signature BM  unsigned char header[54]={0x42,0x4d,              // signature BM
21                              0xe6,0x71,0x0b,0x0,   // filesize 750054                              0xe6,0x71,0x0b,0x0,   // filesize 750054
22                              0x0,0x0,0x0,0x0,      // reserved                              0x0,0x0,0x0,0x0,      // reserved
# Line 28  unsigned char header[54]={0x42,0x4d, Line 33  unsigned char header[54]={0x42,0x4d,
33                              0x0,0x0,0x0,0x0,      // number of colortables                                  0x0,0x0,0x0,0x0,      // number of colortables    
34                              0x0,0x0,0x0,0x0       // number of important colors                              0x0,0x0,0x0,0x0       // number of important colors
35                          };                          };
 */  
36    
37  int main(int argc, char *argv[])  
38  {  void printErrorAndExit(const char *msg, DWORD err) {
39      FILE *fd;          LPSTR lpMsgBuf;
40      int len,x,y;          if(FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|
41      char bgr[3];                                    FORMAT_MESSAGE_FROM_SYSTEM |
42      short svalue;                                            FORMAT_MESSAGE_IGNORE_INSERTS,
43      int   lvalue;                                                  NULL,
44      unsigned char header[54],*ptr=&header[0];                                                  err,
45                                              MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
46                                              (LPTSTR) &lpMsgBuf,
47                                              0,
48                                              NULL ))
49            {
50                    fprintf(stderr,"%s : %s\n",msg,lpMsgBuf);
51                    LocalFree(lpMsgBuf);
52            }
53            else
54            {
55                    fprintf(stderr,"Error at FormatMesage: %d\n",err=GetLastError());
56            }
57            exit(err);
58    }
59    
60    
61    void write_blank_file(char *filename) {
62    
63      FILE *fd;
64      int len, i, img_size;
65    
66      // open file handle
67      fd = fopen(filename, "wb+");
68      if (NULL == fd) {
69        perror("open");
70        exit(1);
71      }
72    
73      // write bmp header to file
74      len = fwrite(header, 1, sizeof(header), fd);
75      
76      // error checking
77      if (-1 == len || len != sizeof(header)) {
78        perror("write");
79        exit(2);
80      }
81      
82      // write three null-bytes for each pixel to file to create a black picture
83      img_size = XSIZE * YSIZE;
84      for (i = 0; i < img_size; i++) {
85        len = fwrite("\0\0\0", 1, 3, fd);
86        if (-1 == len || len != 3) {
87          perror("write");
88          exit(4);
89        }
90      }
91      
92      // close file handle
93      fclose(fd);
94    }
95    
96    
97    // arguments for each thread
98    typedef struct _WorkerArguments {
99      int start_row;
100      int number_of_rows;
101      unsigned char * pBitmap;
102    } WORKERARGS, *PWORKERARGS;
103    
104    // worker thread - main entry function
105    DWORD WINAPI fractal_thread (LPVOID lpParam) {
106      
107      // thread stuff
108      int thread_id;
109      PWORKERARGS args;
110      unsigned char *pDataBitmapSegment;
111    
112      // fractal calculation
113      int x, y;
114      char bgr[3];
115    
116      thread_id = GetCurrentThreadId();
117      
118      // get worker arguments
119      args = (PWORKERARGS)lpParam;
120      
121      printf("----------------------------------------------\n");
122      printf("thread_id: %i\n", thread_id);
123      printf("arg.start_row: %i\n", args->start_row);
124      printf("arg.number_of_rows: %i\n", args->number_of_rows);
125    
126      // calculate pointer to beginning of segment
127      pDataBitmapSegment = (unsigned char *)((INT_PTR)args->pBitmap + (YSIZE - (args->start_row + args->number_of_rows)) * 3 * XSIZE);
128      printf("segment_start: %p\n", pDataBitmapSegment);
129      
130      // calculate fractal
131      for (y = (args->start_row + args->number_of_rows) - 1; y >= args->start_row; y--) {
132        //printf("calc: thread=%i; y=%i            limits: %i,%i    p: %p\n", thread_id, y, args->start_row, args->number_of_rows, pDataBitmapSegment);
133        for (x = 0; x < XSIZE; x++) {
134          getColorValuesAt(x * (2.0 / XSIZE) - 1.5, y * (2.0 / YSIZE) - 1.0, &bgr[2], &bgr[1], &bgr[0]);
135          
136          // debugging
137          //printf("pointer: %p\n", pDataBitmapCurrent);
138          
139          // transfer color values to current pixel
140          pDataBitmapSegment[0] = bgr[0];
141          pDataBitmapSegment[1] = bgr[1];
142          pDataBitmapSegment[2] = bgr[2];
143          
144          // move pointer to next pixel
145          pDataBitmapSegment += 3;
146                
     fd=fopen("test.bmp","wb+");  
     if(NULL==fd)  
     {  
         perror("open"); exit(1);  
147      }      }
148  /* Der folgende Abschnitt dient nur zur information und kann durch      //no padding required because 1500%4 =0
149      schreiben der auskommentierten Variable header ersetzt werden */        }
150      svalue=0x4d42;  
151      memcpy(ptr,&svalue,2);//signatur    printf("thread finished: %i\n", thread_id);
152      ptr+=2;    return 0;
153      lvalue=XSIZE*YSIZE*3+54;  
154      memcpy(ptr,&lvalue,4); //filesize  }
155      ptr+=4;  
156      lvalue=0;  
157      memcpy(ptr,&lvalue,4);//reserved  int main(int argc, char *argv[]) {
158      ptr+=4;  
159      lvalue=54;    // MMF support
160      memcpy(ptr,&lvalue,4);//image offset    DWORD err;
161      ptr+=4;    HANDLE hMap, hFile;
162      lvalue=40;    LPVOID pData;
163      memcpy(ptr,&lvalue,4);//size of header follows    unsigned char *pDataBitmap, *pDataBitmapCurrent;
164      ptr+=4;  
165      lvalue=XSIZE;    // workers
166      memcpy(ptr,&lvalue,4);//with of image    int workers = 5;
167      ptr+=4;    int worker_index, worker_rows, worker_startrow;
168      lvalue=YSIZE;    HANDLE *worker_handles;
169      memcpy(ptr,&lvalue,4); //height of image    //struct WorkerArguments *worker_args;
170      ptr+=4;    PWORKERARGS worker_args;
171      svalue=1;  
172      memcpy(ptr,&svalue,2); //number of planes    
173      ptr+=2;    // create empty bmp-file (black background)
174      svalue=24;    write_blank_file("test.bmp");
175      memcpy(ptr,&svalue,2); //number of pixel  
176      ptr+=2;    /* open file for reading and writing */
177      lvalue=0; //compression    hFile = CreateFile("test.bmp", GENERIC_WRITE|GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
178      memcpy(ptr,&lvalue,4); //compression    if (INVALID_HANDLE_VALUE == hFile) {
179      ptr+=4;      err = GetLastError();
180      lvalue=XSIZE*YSIZE*3;      printErrorAndExit("Error at CreateFile",err);
181      memcpy(ptr,&lvalue,4); //size of image    }
182      ptr+=4;  
183      lvalue=0;    /* create the file mapping object */
184      memcpy(ptr,&lvalue,4); //xres      hMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
185      ptr+=4;    if (NULL == hMap) {
186      lvalue=0;      printErrorAndExit("Error at CreateFileMapping", GetLastError());
187      memcpy(ptr,&lvalue,4); //yres    }
188      ptr+=4;    
189      lvalue=0;    /* map the whole file into the process context */
190      memcpy(ptr,&lvalue,4); //number of colortables    pData = MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);
191      ptr+=4;    if (NULL == pData) {
192      lvalue=0;      printErrorAndExit("Error at MapViewOfFile", GetLastError());
193      memcpy(ptr,&lvalue,4); //number of important colors    }
194      ptr+=4;  
195  /* Ende Information */    
196      // calculate pointer to beginning of bitmap
197      len=fwrite(header,1,sizeof(header),fd); //write header    pDataBitmap = (unsigned char *)((INT_PTR)pData + sizeof(header));
198          
199      if(-1==len || len!=sizeof(header))    // debugging
200      {    printf("pos. of file: %p\n", pData);
201          perror("write");    printf("pos. of bitmap: %p\n", pDataBitmap);
202          exit(2);  
203      // pointer to current pixel
204      pDataBitmapCurrent = pDataBitmap;
205    
206      /*
207      // turn bitmap into white wand
208      for (offset = 0; offset < 500 * 500 * 3; offset++) {
209        //pDataBitmap[offset] = 255;
210        *pDataBitmapCurrent = 255;
211        pDataBitmapCurrent++;
212      }
213      */
214    
215    
216      // allocate memory for table of all worker handles
217      if ((worker_handles = malloc(workers * sizeof worker_handles[0])) == NULL)
218        perror("malloc"), exit(1);
219    
220      // allocate memory for table of all worker arguments
221      if ((worker_args = malloc(workers * sizeof worker_args[0])) == NULL)
222        perror("malloc"), exit(1);
223      
224      // allocate memory for table of all worker arguments
225      /*
226      worker_args = (PWORKERARGS) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY | HEAP_NO_SERIALIZE, workers * sizeof(WORKERARGS));
227    
228      if (worker_args == NULL) {
229        printErrorAndExit("Failed to allocate on heap", GetLastError());
230      }
231      */
232      
233      // calculate segments of bitmap for worker threads/processes and start them
234      worker_rows = YSIZE / workers;
235      printf("rows for each worker: %i\n", worker_rows);
236      for (worker_index = 0; worker_index < workers; worker_index++) {
237        
238        // debugging: just run with single thread
239        //if (worker_index == 1)
240        //  continue;
241        
242        // number of row to start for each worker
243        worker_startrow = worker_index * worker_rows;
244        
245        // recalculate number of rows for last worker if (YSIZE mod workers) != 0
246        if (worker_index == workers - 1) {
247          worker_rows = YSIZE - worker_startrow;
248          printf("rows for last worker: %i\n", worker_rows);
249      }      }
250            
251      for(y=YSIZE-1;y>=0;y--)      worker_args[worker_index].start_row = worker_startrow;
252      {      worker_args[worker_index].number_of_rows = worker_rows;
253              for(x=0;x<XSIZE;x++)      worker_args[worker_index].pBitmap = pDataBitmap;
254              {      
255                  getColorValuesAt(x * (2.0 / XSIZE) - 1.5, y * (2.0 / YSIZE) - 1.0,&bgr[2],&bgr[1],&bgr[0]);      worker_handles[worker_index] = CreateThread(
256                          NULL,                          // LPSECURITY_ATTRIBUTES lpThreadAttributes,
257                  len=fwrite(bgr,1,3,fd);        0,                             // SIZE_T dwStackSize,
258                  if(-1==len || len!=3)        fractal_thread,                // LPTHREAD_START_ROUTINE lpStartAddress,
259                  {        &worker_args[worker_index],    // LPVOID lpParameter,
260                      perror("write");        0,                             // DWORD dwCreationFlags,
261                      exit(4);        NULL                           // LPDWORD lpThreadId
262                  }      );
             }  
             /*no padding required because 1500%4 =0*/  
     }          
     fclose(fd);  
263            
264      }
265    
266      // wait for all threads
267      if (WaitForMultipleObjects(workers, worker_handles, TRUE, INFINITE) == WAIT_FAILED)
268        perror("WaitForMultipleObjects");
269    
270      // debugging: just run with single thread
271      //if (WaitForSingleObject(worker_handles[0], INFINITE) == WAIT_FAILED)
272      //  perror("WaitForSingleObject");
273    
274      // close all worker handles
275      for (worker_index = 0; worker_index < workers; worker_index++)
276        CloseHandle(worker_handles[worker_index]);
277        
278      /* write the result into the file */
279      if (!FlushViewOfFile(pData, 0)) {
280        err = GetLastError();
281        printErrorAndExit("Error at UnmapViewOfFile", err);
282      }
283    
284      /* remove the mapped file */
285      if (!UnmapViewOfFile(pData)) {
286        err = GetLastError();
287        printErrorAndExit("Error at UnmapViewOfFile", err);
288        exit(err);
289      }
290      
291      /* cleanup handles */
292      if (!CloseHandle(hMap) || !CloseHandle(hFile) ) {
293        err = GetLastError();
294        printErrorAndExit("Error at CloseHandle", err);
295      }
296    
297      /*
298      if (HeapFree(GetProcessHeap(), HEAP_ZERO_MEMORY | HEAP_NO_SERIALIZE, worker_args) != TRUE) {
299        printErrorAndExit("Call to HeapFree has failed", GetLastError());
300      }
301      */
302      
303      
304      return 0;
305      
306  }  }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.8

MailToCvsAdmin">MailToCvsAdmin
ViewVC Help
Powered by ViewVC 1.1.26 RSS 2.0 feed