Added ability to set fg/bg color in WolframAutomata.
[screensavers] / hacks / WolframAutomata / WolframAutomata.c
CommitLineData
0c731d4a
AT
1/* (c) 2021 Aaron Taylor <ataylor at subgeniuskitty dot com> */
2/* See LICENSE.txt file for copyright and license details. */
3
4
5/* TODO: Write description explaining that this simulates all 1D NN CAs, and explain briefly what all those terms imply. */
6/* TODO: Explain things like the topology of the space. */
7/* TODO: Explain how the numbering for a CA expands to the actual rules. */
8/* TODO: Briefly explain the four different classes of behavior and their implications. */
9/* TODO: Include a link to Wikipedia. */
10/* TODO: I suppose a lot of this stuff goes in the README instead. */
11/* TODO: Explain the data structures in detail. */
12/* TODO: Explain all the options, like the various starting conditions. */
13
14
15/* TODO: Check manpage for all functions I use and ensure my includes are correct. I don't want to depend on picking up includes via screenhack.h. */
16/* TODO: Verify everything in this file is C89. Get rid of things like '//' comments, pack all my declarations upfront, no stdint, etc. */
0c731d4a 17
d0f3b852 18#include <X11/Intrinsic.h>
0c731d4a
AT
19#include "screenhack.h"
20
d0f3b852
AT
21/*
22 * We do a few manual manipulations of X resources in this hack, like picking
23 * random colors. In order to ensure our manual manipulations always use the
24 * same X resource specification as Xscreensaver, we pass HACKNAME to
25 * Xscreensaver via the XSCREENSAVER_MODULE() line at the bottom of this file,
26 * and then always use HACKNAME or MAKE_STRING(HACKNAME) as the base of the
27 * resource specification when making manual manipulations.
28 */
29#define HACKNAME WolframAutomata
30#define MAKE_STRING_X(s) #s
31#define MAKE_STRING(s) MAKE_STRING_X(s)
32
0c731d4a 33// Command line options
7ce88c8e 34// directory to output XBM files of each run (and call an external command to convert to PNGs?)
2b742550 35// -save-dir STRING
7ce88c8e 36// number of generations to simulate
2b742550 37// -num-generations N
7ce88c8e 38// delay time (speed of simulation)
2b742550 39// -delay-usec N
7ce88c8e 40// foreground and background color
d0f3b852
AT
41// -random-colors (highest precedence)
42// -foreground "COLORNAME"
43// -background "COLORNAME"
44// (default is black and white)
45// (mention sample color combinations in manpage, and link to: https://en.wikipedia.org/wiki/X11_color_names)
7ce88c8e 46// display info overlay with CA number and start conditions?
2b742550 47// -overlay
7ce88c8e 48// which ruleset number to use? Or random? Or random from small set of hand-selected interesting examples?
80cfe219 49// In order of precedence:
14d68c5b 50// -rule-random (select a random rule on each run)
80cfe219
AT
51// -rule N (always simulate Rule N on each run)
52// (if neither of the above two are specified, then a random CURATED rule is selected on each run)
14d68c5b
AT
53// which starting population to use, random or one bit? (for random: allow specifying a density)
54// In order of precedence:
55// -population-single
56// -population-random DENSITY
57// (the two options above only apply to the simulation under the -rule-random or -rule N options. in curated mode, starting population is defined in the curation array)
58// TODO: In the future, add the option for user to pass list of cell IDs to turn ON.
2b742550
AT
59// size of pixel square (e.g. 1x1, 2x2, 3x3, etc)
60// -pixel-size N
0c731d4a 61
14d68c5b
AT
62/* -------------------------------------------------------------------------- */
63/* Data Structures */
64/* -------------------------------------------------------------------------- */
65
0c731d4a 66struct state {
7ce88c8e
AT
67 /* Various X resources */
68 Display * dpy;
69 Window win;
70 GC gc;
71
72 // TODO: Explain that this holds the whole evolution of the CA and the actual displayed visualization is simply a snapshot into this pixmap.
73 Pixmap evolution_history;
7ce88c8e
AT
74
75 // TODO: Explain all of these.
7ce88c8e
AT
76 unsigned long fg, bg;
77 int xlim, ylim, ypos; // explain roughly how and where we use these. Note: I'm not thrilled xlim/ylim since they are actually the width of the display, not the limit of the index (off by one). Change those names.
78 Bool display_info;
7ce88c8e
AT
79
80 Bool * current_generation;
80cfe219
AT
81
82 // TODO: Describe these.
83 uint8_t rule_number; // Note: This is not a CLI option. You're thinking of rule_requested.
84 uint8_t rule_requested; // Note: Repurposing Rule 0 as a null value.
85 Bool rule_random;
c428f3d5 86
14d68c5b
AT
87 // TODO: Describe these.
88 int population_density;
89 Bool population_single;
90
c428f3d5
AT
91 /* Misc Commandline Options */
92 int pixel_size; /* Size of CA cell in pixels (e.g. pixel_size=3 means 3x3 pixels per cell). */
93 int delay_microsec; /* Requested delay to screenhack framework before next call to WolframAutomata_draw(). */
7969381e 94 int num_generations; /* Number of generations of the CA to simulate before restarting. */
c428f3d5
AT
95
96 /* Expository Variables - Not strictly necessary, but makes some code easier to read. */
97 size_t number_of_cells;
0c731d4a
AT
98};
99
14d68c5b
AT
100// TODO: Decorations
101enum seed_population {
1f5d1274
AT
102 random_cell,
103 middle_cell,
104 edge_cell
14d68c5b
AT
105};
106
107// TODO: Decorations
108struct curated_ruleset {
109 uint8_t rule;
110 enum seed_population seed;
111};
112
1f5d1274 113// TODO: Decorations
14d68c5b 114static const struct curated_ruleset curated_ruleset_list[] = {
1f5d1274
AT
115 {18, middle_cell},
116 {30, middle_cell},
117 {45, middle_cell},
118 {54, middle_cell},
119 {57, middle_cell},
120 {73, middle_cell},
121 {105, middle_cell},
122 {109, middle_cell},
123 {129, middle_cell},
124 {133, middle_cell},
125 {135, middle_cell},
126 {150, middle_cell},
127 {30, edge_cell},
128 {45, edge_cell},
129 {57, edge_cell},
130 {60, edge_cell},
131 {75, edge_cell},
132 {107, edge_cell},
133 {110, edge_cell},
134 {133, edge_cell},
135 {137, edge_cell},
136 {169, edge_cell},
137 {225, edge_cell},
138 {22, random_cell},
139 {30, random_cell},
140 {54, random_cell},
141 {62, random_cell},
142 {90, random_cell},
143 {105, random_cell},
144 {108, random_cell},
145 {110, random_cell},
146 {126, random_cell},
147 {146, random_cell},
148 {150, random_cell},
149 {182, random_cell},
150 {184, random_cell},
151 {225, random_cell},
152 {240, random_cell}
80cfe219
AT
153};
154
d0f3b852
AT
155// TODO: Decorations
156struct color_pair {
157 char * fg;
158 char * bg;
159};
160
161// TODO: Decorations
162// TODO: Populate this table with more examples.
163static const struct color_pair color_list[] = {
164 {"white", "black"},
165};
166
14d68c5b
AT
167/* -------------------------------------------------------------------------- */
168/* Helper Functions */
169/* -------------------------------------------------------------------------- */
170
171// TODO: decorations? inline?
172void
173generate_random_seed(struct state * state)
174{
175 int i;
176 for (i = 0; i < state->number_of_cells; i++) {
177 state->current_generation[i] = ((random() % 100) < state->population_density) ? True : False;
178 }
179}
180
181// TODO: function decorations?
182// TODO: Explain why this santizes the index for accessing current_generation (i.e. it creates a circular topology).
183size_t
184sindex(struct state * state, int index)
185{
186 while (index < 0) {
187 index += state->number_of_cells;
188 }
189 while (index >= state->number_of_cells) {
190 index -= state->number_of_cells;
191 }
192 return (size_t) index;
193}
194
195// TODO: function decorations?
196// TODO: At least give a one-sentence explanation of the algorithm since this function is the core of the simulation.
197Bool
198calculate_cell(struct state * state, int cell_id)
199{
200 uint8_t cell_pattern = 0;
201 int i;
202 for (i = -1; i < 2; i++) {
203 cell_pattern = cell_pattern << 1;
204 if (state->current_generation[sindex(state, cell_id+i)] == True) {
205 cell_pattern |= 1;
206 }
207 }
208 if ((state->rule_number >> cell_pattern) & 1) {
209 return True;
210 } else {
211 return False;
212 }
213}
214
215// TODO: function decorations?
216void
217render_current_generation(struct state * state)
218{
219 size_t xpos;
220 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
221 if (state->current_generation[xpos] == True) {
222 XFillRectangle(state->dpy, state->evolution_history, state->gc, xpos*state->pixel_size, state->ypos, state->pixel_size, state->pixel_size);
223 }
224 }
225}
226
227/* -------------------------------------------------------------------------- */
228/* Screenhack API Functions */
229/* -------------------------------------------------------------------------- */
230
0c731d4a
AT
231static void *
232WolframAutomata_init(Display * dpy, Window win)
233{
7ce88c8e
AT
234 struct state * state = calloc(1, sizeof(*state)); // TODO: Check calloc() call
235 XGCValues gcv;
236 XWindowAttributes xgwa;
14d68c5b 237 const struct curated_ruleset * curated_ruleset = NULL;
7ce88c8e
AT
238
239 state->dpy = dpy;
240 state->win = win;
241
242 XGetWindowAttributes(state->dpy, state->win, &xgwa);
243 state->xlim = xgwa.width;
244 state->ylim = xgwa.height;
245 state->ypos = 0; // TODO: Explain why.
246
d0f3b852
AT
247 if (get_boolean_resource(state->dpy, "random-colors", "Boolean")) {
248 XrmDatabase db = XtDatabase(state->dpy);
249 size_t rand_i = random() % sizeof(color_list)/sizeof(color_list[0]);
250 XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".background", color_list[rand_i].bg);
251 XrmPutStringResource(&db, MAKE_STRING(HACKNAME) ".foreground", color_list[rand_i].fg);
252 }
253
7ce88c8e
AT
254 state->fg = gcv.foreground = get_pixel_resource(state->dpy, xgwa.colormap, "foreground", "Foreground");
255 state->bg = gcv.background = get_pixel_resource(state->dpy, xgwa.colormap, "background", "Background");
256 state->gc = XCreateGC(state->dpy, state->win, GCForeground, &gcv);
257
c428f3d5 258 state->delay_microsec = get_integer_resource(state->dpy, "delay-usec", "Integer");
7ce88c8e
AT
259 if (state->delay_microsec < 0) state->delay_microsec = 0;
260
c428f3d5
AT
261 state->pixel_size = get_integer_resource(state->dpy, "pixel-size", "Integer");
262 if (state->pixel_size < 1) state->pixel_size = 1;
263 if (state->pixel_size > state->xlim) state->pixel_size = state->xlim;
264
265 state->number_of_cells = state->xlim / state->pixel_size;
14d68c5b 266 // TODO: Do we want to enforce that number_of_cells > 0?
c428f3d5 267
80cfe219
AT
268 /* The minimum number of generations is 2 since we must allocate enough */
269 /* space to hold the seed generation and at least one pass through */
270 /* WolframAutomata_draw(), which is where we check whether or not we've */
271 /* reached the end of the pixmap. */
7969381e
AT
272 state->num_generations = get_integer_resource(state->dpy, "num-generations", "Integer");
273 if (state->num_generations < 0) state->num_generations = 2;
274
80cfe219
AT
275 /* Time to figure out which rule to use for this simulation. */
276 /* We ignore any weirdness resulting from the following cast since every */
277 /* bit pattern is also a valid rule; if the user provides weird input, */
278 /* then we'll return weird (but well-defined!) output. */
279 state->rule_requested = (uint8_t) get_integer_resource(state->dpy, "rule-requested", "Integer");
280 state->rule_random = get_boolean_resource(state->dpy, "rule-random", "Boolean");
281 /* Through the following set of branches, we enforce CLI flag precedence. */
282 if (state->rule_random) {
283 /* If this flag is set, the user wants truly random rules rather than */
284 /* random rules from a curated list. */
285 state->rule_number = (uint8_t) random();
286 } else if (state->rule_requested != 0) {
287 /* Rule 0 is terribly uninteresting, so we are reusing it as a 'null' */
288 /* value and hoping nobody notices. Finding a non-zero value means */
289 /* the user requested a specific rule. Use it. */
290 state->rule_number = state->rule_requested;
291 } else {
292 /* No command-line options were specified, so select rules randomly */
293 /* from a curated list. */
14d68c5b
AT
294 size_t number_of_array_elements = sizeof(curated_ruleset_list)/sizeof(curated_ruleset_list[0]);
295 curated_ruleset = &curated_ruleset_list[random() % number_of_array_elements];
296 state->rule_number = curated_ruleset->rule;
297 }
298
299 /* Time to construct the seed generation for this simulation. */
300 state->population_single = get_boolean_resource(state->dpy, "population-single", "Boolean");
301 state->population_density = get_integer_resource(state->dpy, "population-density", "Integer");
302 if (state->population_density < 0 || state->population_density > 100) state->population_density = 50;
303 state->current_generation = calloc(1, sizeof(*state->current_generation)*state->number_of_cells);
304 if (!state->current_generation) {
305 fprintf(stderr, "ERROR: Failed to calloc() in WolframAutomata_init().\n");
306 exit(EXIT_FAILURE);
307 }
308 if (curated_ruleset) {
309 /* If we're using a curated ruleset, ignore any CLI flags related to */
310 /* setting the seed generation, instead drawing that information from */
311 /* the curated ruleset. */
312 switch (curated_ruleset->seed) {
1f5d1274
AT
313 case random_cell: generate_random_seed(state); break;
314 case middle_cell: state->current_generation[state->number_of_cells/2] = True; break;
315 case edge_cell : state->current_generation[0] = True; break;
14d68c5b
AT
316 }
317 } else {
318 /* If we're not using a curated ruleset, process any relevant flags */
319 /* from the user, falling back to a random seed generation if nothing */
320 /* else is specified. */
321 if (state->population_single) {
322 state->current_generation[0] = True;
323 } else {
324 generate_random_seed(state);
325 }
80cfe219
AT
326 }
327
7ce88c8e
AT
328 // TODO: These should be command-line options, but I need to learn how the get_integer_resource() and similar functions work first.
329 state->display_info = True;
7ce88c8e 330
c428f3d5 331 state->evolution_history = XCreatePixmap(state->dpy, state->win, state->xlim, state->num_generations*state->pixel_size, xgwa.depth);
7ce88c8e
AT
332 // Pixmap contents are undefined after creation. Explicitly set a black
333 // background by drawing a black rectangle over the entire pixmap.
334 XSetForeground(state->dpy, state->gc, state->bg);
c428f3d5 335 XFillRectangle(state->dpy, state->evolution_history, state->gc, 0, 0, state->xlim, state->num_generations*state->pixel_size);
7ce88c8e 336 XSetForeground(state->dpy, state->gc, state->fg);
14d68c5b
AT
337 render_current_generation(state);
338 state->ypos += state->pixel_size;
7ce88c8e
AT
339
340 return state;
0c731d4a
AT
341}
342
0c731d4a
AT
343static unsigned long
344WolframAutomata_draw(Display * dpy, Window win, void * closure)
345{
346// TODO: Mark these basic sections of the function
347//draw()
7ce88c8e
AT
348// calculate (and store) new generation
349// draw new generation as line of pixels on pixmap
350// calculate current 'viewport' into pixmap
351// display on screen
0c731d4a
AT
352// check for termination condition
353
354 struct state * state = closure;
355 int xpos;
7ce88c8e 356 int window_y_offset;
0c731d4a 357
7ce88c8e 358 Bool new_generation[state->xlim];
c428f3d5 359 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
360 new_generation[xpos] = calculate_cell(state, xpos);
361 }
c428f3d5 362 for (xpos = 0; xpos < state->number_of_cells; xpos++) {
7ce88c8e
AT
363 state->current_generation[xpos] = new_generation[xpos];
364 }
365 render_current_generation(state);
366
367 // Was this the final generation of this particular simulation? If so, give
368 // the user a moment to bask in the glory of our output and then start a
369 // new simulation.
c428f3d5
AT
370 if (state->ypos/state->pixel_size < state->num_generations-1) {
371 state->ypos += state->pixel_size;
7ce88c8e
AT
372 } else {
373 // TODO: Wait for a second or two, clear the screen and do a new iteration with suitably changed settings.
374 // Note: Since we can't actually loop or sleep here, we need to add a flag to the state struct to indicate that we're in an 'admiration timewindow' (and indicate when it should end)
c428f3d5 375 printf("infinite hamster wheel\n");
7ce88c8e
AT
376 while (1) continue;
377 }
378
379 // Calculate the vertical offset of the current 'window' into the history
380 // of the CA. After the CA's evolution extends past what we can display, have
381 // the window track the current generation and most recent history.
382 if (state->ypos < state->ylim) {
383 window_y_offset = 0;
384 } else {
385 window_y_offset = state->ypos - (state->ylim - 1);
386 }
387
388 // Render everything to the display.
389 XCopyArea(state->dpy, state->evolution_history, state->win, state->gc, 0, window_y_offset, state->xlim, state->ylim, 0, 0);
390 // TODO: Print info on screen if display_info is true. Will need fonts/etc. Do I want to create a separate pixmap for this during the init() function and then just copy the pixmap each time we draw the screen in draw()?
0c731d4a
AT
391
392 return state->delay_microsec;
393}
394
c428f3d5 395// TODO: Fix formatting
0c731d4a
AT
396static const char * WolframAutomata_defaults[] = {
397 ".background: black",
398 ".foreground: white",
d0f3b852 399 "*random-colors: False",
80cfe219 400 "*delay-usec: 25000",
7969381e
AT
401 // TODO: Difference between dot and asterisk? Presumably the asterisk matches all resouces of attribute "pixelsize"? Apply answer to all new options.
402 "*pixel-size: 2",
403 "*num-generations: 5000",
80cfe219
AT
404 "*rule-requested: 0",
405 "*rule-random: False",
14d68c5b
AT
406 "*population-density: 50",
407 "*population-single: False",
0c731d4a
AT
408 0
409};
410
c428f3d5 411// TODO: Fix formatting
0c731d4a 412static XrmOptionDescRec WolframAutomata_options[] = {
d0f3b852
AT
413 { "-background", ".background", XrmoptionSepArg, 0},
414 { "-foreground", ".foreground", XrmoptionSepArg, 0},
415 { "-random-colors", ".random-colors", XrmoptionNoArg, "True"},
c428f3d5
AT
416 { "-delay-usec", ".delay-usec", XrmoptionSepArg, 0 },
417 { "-pixel-size", ".pixel-size", XrmoptionSepArg, 0 },
7969381e 418 { "-num-generations", ".num-generations", XrmoptionSepArg, 0 },
80cfe219
AT
419 { "-rule", ".rule-requested", XrmoptionSepArg, 0 },
420 { "-rule-random", ".rule-random", XrmoptionNoArg, "True" },
14d68c5b
AT
421 { "-population-density", ".population-density", XrmoptionSepArg, 0 },
422 { "-population-single", ".population-single", XrmoptionNoArg, "True" },
0c731d4a
AT
423 { 0, 0, 0, 0 }
424};
425
426static Bool
427WolframAutomata_event(Display * dpy, Window win, void * closure, XEvent * event)
428{
429 return False;
430}
431
432static void
433WolframAutomata_free(Display * dpy, Window win, void * closure)
434{
435 struct state * state = closure;
436 XFreeGC(state->dpy, state->gc);
7ce88c8e
AT
437 XFreePixmap(state->dpy, state->evolution_history);
438 free(state->current_generation);
0c731d4a
AT
439 free(state);
440}
441
442static void
443WolframAutomata_reshape(Display * dpy, Window win, void * closure, unsigned int w, unsigned int h)
444{
7ce88c8e 445 WolframAutomata_free(dpy, win, closure);
b0ea929b 446 closure = WolframAutomata_init(dpy, win);
0c731d4a
AT
447}
448
d0f3b852 449XSCREENSAVER_MODULE ("1D Nearest-Neighbor Cellular Automata", HACKNAME)
0c731d4a 450