Debian Codegraph @

editor/specialty/pbmlife.c

raw
1 /* pbmlife.c - read a portable bitmap and apply Conway's rules of Life to it
2 **
3 ** Copyright (C) 1988,1 1991 by Jef Poskanzer.
4 **
5 ** Permission to use, copy, modify, and distribute this software and its
6 ** documentation for any purpose and without fee is hereby granted, provided
7 ** that the above copyright notice appear in all copies and that both that
8 ** copyright notice and this permission notice appear in supporting
9 ** documentation. This software is provided "as is" without express or
10 ** implied warranty.
11 */
12
13 #include "pbm.h"
14
15 int
16 main(int argc, char * argv []) {
17
18 FILE* ifp;
19 bit* prevrow;
20 bit* thisrow;
21 bit* nextrow;
22 bit* temprow;
23 bit* newrow;
24 int rows, cols, row;
25 int col, count;
26 int format;
27
28
29 pbm_init( &argc, argv );
30
31 if ( argc > 2 )
32 pm_usage( "[pbmfile]" );
33
34 if ( argc == 2 )
35 ifp = pm_openr( argv[1] );
36 else
37 ifp = stdin;
38
39 pbm_readpbminit( ifp, &cols, &rows, &format );
40 prevrow = pbm_allocrow( cols );
41 thisrow = pbm_allocrow( cols );
42 nextrow = pbm_allocrow( cols );
43
44 pbm_writepbminit( stdout, cols, rows, 0 );
45 newrow = pbm_allocrow( cols );
46
47 pbm_readpbmrow( ifp, nextrow, cols, format );
48
49 for ( row = 0; row < rows; ++row )
50 {
51 temprow = prevrow;
52 prevrow = thisrow;
53 thisrow = nextrow;
54 nextrow = temprow;
55 if ( row < rows - 1 )
56 pbm_readpbmrow( ifp, nextrow, cols, format );
57
58 for ( col = 0; col < cols; ++col )
59 {
60 /* Check the neighborhood, with an unrolled double loop. */
61 count = 0;
62 if ( row > 0 )
63 {
64 /* upper left */
65 if ( col > 0 && prevrow[col - 1] == PBM_WHITE )
66 ++count;
67 /* upper center */
68 if ( prevrow[col] == PBM_WHITE )
69 ++count;
70 /* upper right */
71 if ( col < cols - 1 && prevrow[col + 1] == PBM_WHITE )
72 ++count;
73 }
74 /* left */
75 if ( col > 0 && thisrow[col - 1] == PBM_WHITE )
76 ++count;
77 /* right */
78 if ( col < cols - 1 && thisrow[col + 1] == PBM_WHITE )
79 ++count;
80 if ( row < rows - 1 )
81 {
82 /* lower left */
83 if ( col > 0 && nextrow[col - 1] == PBM_WHITE )
84 ++count;
85 /* lower center */
86 if ( nextrow[col] == PBM_WHITE )
87 ++count;
88 /* lower right */
89 if ( col < cols - 1 && nextrow[col + 1] == PBM_WHITE )
90 ++count;
91 }
92
93 /* And compute the new value. */
94 if ( thisrow[col] == PBM_WHITE )
95 if ( count == 2 || count == 3 )
96 newrow[col] = PBM_WHITE;
97 else
98 newrow[col] = PBM_BLACK;
99 else
100 if ( count == 3 )
101 newrow[col] = PBM_WHITE;
102 else
103 newrow[col] = PBM_BLACK;
104 }
105 pbm_writepbmrow( stdout, newrow, cols, 0 );
106 }
107
108 pm_close( ifp );
109 pm_close( stdout );
110
111 exit( 0 );
112 }
113
114
115