chiark / gitweb /
Forgot to update devel.but in r6417.
[sgt-puzzles.git] / devel.but
1 \cfg{text-indent}{0}
2 \cfg{text-width}{72}
3 \cfg{text-title-align}{left}
4 \cfg{text-chapter-align}{left}
5 \cfg{text-chapter-numeric}{true}
6 \cfg{text-chapter-suffix}{. }
7 \cfg{text-chapter-underline}{-}
8 \cfg{text-section-align}{0}{left}
9 \cfg{text-section-numeric}{0}{true}
10 \cfg{text-section-suffix}{0}{. }
11 \cfg{text-section-underline}{0}{-}
12 \cfg{text-section-align}{1}{left}
13 \cfg{text-section-numeric}{1}{true}
14 \cfg{text-section-suffix}{1}{. }
15 \cfg{text-section-underline}{1}{-}
16 \cfg{text-versionid}{0}
17
18 \cfg{html-contents-filename}{index.html}
19 \cfg{html-template-filename}{%k.html}
20 \cfg{html-index-filename}{docindex.html}
21 \cfg{html-leaf-level}{1}
22 \cfg{html-contents-depth-0}{1}
23 \cfg{html-contents-depth-1}{3}
24 \cfg{html-leaf-contains-contents}{true}
25
26 \define{dash} \u2013{-}
27
28 \title Developer documentation for Simon Tatham's puzzle collection
29
30 This is a guide to the internal structure of Simon Tatham's Portable
31 Puzzle Collection (henceforth referred to simply as \q{Puzzles}),
32 for use by anyone attempting to implement a new puzzle or port to a
33 new platform.
34
35 This guide is believed correct as of r6190. Hopefully it will be
36 updated along with the code in future, but if not, I've at least
37 left this version number in here so you can figure out what's
38 changed by tracking commit comments from there onwards.
39
40 \C{intro} Introduction
41
42 The Puzzles code base is divided into four parts: a set of
43 interchangeable front ends, a set of interchangeable back ends, a
44 universal \q{middle end} which acts as a buffer between the two, and
45 a bunch of miscellaneous utility functions. In the following
46 sections I give some general discussion of each of these parts.
47
48 \H{intro-frontend} Front end
49
50 The front end is the non-portable part of the code: it's the bit
51 that you replace completely when you port to a different platform.
52 So it's responsible for all system calls, all GUI interaction, and
53 anything else platform-specific.
54
55 The current front ends in the main code base are for Windows, GTK
56 and MacOS X; I also know of a third-party front end for PalmOS.
57
58 The front end contains \cw{main()} or the local platform's
59 equivalent. Top-level control over the application's execution flow
60 belongs to the front end (it isn't, for example, a set of functions
61 called by a universal \cw{main()} somewhere else).
62
63 The front end has complete freedom to design the GUI for any given
64 port of Puzzles. There is no centralised mechanism for maintaining
65 the menu layout, for example. This has a cost in consistency (when I
66 \e{do} want the same menu layout on more than one platform, I have
67 to edit two pieces of code in parallel every time I make a change),
68 but the advantage is that local GUI conventions can be conformed to
69 and local constraints adapted to. For example, MacOS X has strict
70 human interface guidelines which specify a different menu layout
71 from the one I've used on Windows and GTK; there's nothing stopping
72 the OS X front end from providing a menu layout consistent with
73 those guidelines.
74
75 Although the front end is mostly caller rather than the callee in
76 its interactions with other parts of the code, it is required to
77 implement a small API for other modules to call, mostly of drawing
78 functions for games to use when drawing their graphics. The drawing
79 API is documented in \k{drawing}; the other miscellaneous front end
80 API functions are documented in \k{frontend-api}.
81
82 \H{intro-backend} Back end
83
84 A \q{back end}, in this collection, is synonymous with a \q{puzzle}.
85 Each back end implements a different game.
86
87 At the top level, a back end is simply a data structure, containing
88 a few constants (flag words, preferred pixel size) and a large
89 number of function pointers. Back ends are almost invariably callee
90 rather than caller, which means there's a limitation on what a back
91 end can do on its own initiative.
92
93 The persistent state in a back end is divided into a number of data
94 structures, which are used for different purposes and therefore
95 likely to be switched around, changed without notice, and otherwise
96 updated by the rest of the code. It is important when designing a
97 back end to put the right pieces of data into the right structures,
98 or standard midend-provided features (such as Undo) may fail to
99 work.
100
101 The functions and variables provided in the back end data structure
102 are documented in \k{backend}.
103
104 \H{intro-midend} Middle end
105
106 Puzzles has a single and universal \q{middle end}. This code is
107 common to all platforms and all games; it sits in between the front
108 end and the back end and provides standard functionality everywhere.
109
110 People adding new back ends or new front ends should generally not
111 need to edit the middle end. On rare occasions there might be a
112 change that can be made to the middle end to permit a new game to do
113 something not currently anticipated by the middle end's present
114 design; however, this is terribly easy to get wrong and should
115 probably not be undertaken without consulting the primary maintainer
116 (me). Patch submissions containing unannounced mid-end changes will
117 be treated on their merits like any other patch; this is just a
118 friendly warning that mid-end changes will need quite a lot of
119 merits to make them acceptable.
120
121 Functionality provided by the mid-end includes:
122
123 \b Maintaining a list of game state structures and moving back and
124 forth along that list to provide Undo and Redo.
125
126 \b Handling timers (for move animations, flashes on completion, and
127 in some cases actually timing the game).
128
129 \b Handling the container format of game IDs: receiving them,
130 picking them apart into parameters, description and/or random seed,
131 and so on. The game back end need only handle the individual parts
132 of a game ID (encoded parameters and encoded game description);
133 everything else is handled centrally by the mid-end.
134
135 \b Handling standard keystrokes and menu commands, such as \q{New
136 Game}, \q{Restart Game} and \q{Quit}.
137
138 \b Pre-processing mouse events so that the game back ends can rely
139 on them arriving in a sensible order (no missing button-release
140 events, no sudden changes of which button is currently pressed,
141 etc).
142
143 \b Handling the dialog boxes which ask the user for a game ID.
144
145 \b Handling serialisation of entire games (for loading and saving a
146 half-finished game to a disk file, or for handling application
147 shutdown and restart on platforms such as PalmOS where state is
148 expected to be saved).
149
150 Thus, there's a lot of work done once by the mid-end so that
151 individual back ends don't have to worry about it. All the back end
152 has to do is cooperate in ensuring the mid-end can do its work
153 properly.
154
155 The API of functions provided by the mid-end to be called by the
156 front end is documented in \k{midend}.
157
158 \H{intro-utils} Miscellaneous utilities
159
160 In addition to these three major structural components, the Puzzles
161 code also contains a variety of utility modules usable by all of the
162 above components. There is a set of functions to provide
163 platform-independent random number generation; functions to make
164 memory allocation easier; functions which implement a balanced tree
165 structure to be used as necessary in complex algorithms; and a few
166 other miscellaneous functions. All of these are documented in
167 \k{utils}.
168
169 \H{intro-structure} Structure of this guide
170
171 There are a number of function call interfaces within Puzzles, and
172 this guide will discuss each one in a chapter of its own. After
173 that, there will be a section about how to design new games, with
174 some general design thoughts and tips.
175
176 \C{backend} Interface to the back end
177
178 This chapter gives a detailed discussion of the interface that each
179 back end must implement.
180
181 At the top level, each back end source file exports a single global
182 symbol, which is a \c{const struct game} containing a large number
183 of function pointers and a small amount of constant data. This
184 structure is called by different names depending on what kind of
185 platform the puzzle set is being compiled on:
186
187 \b On platforms such as Windows and GTK, which build a separate
188 binary for each puzzle, the game structure in every back end has the
189 same name, \cq{thegame}; the front end refers directly to this name,
190 so that compiling the same front end module against a different back
191 end module builds a different puzzle.
192
193 \b On platforms such as MacOS X and PalmOS, which build all the
194 puzzles into a single monolithic binary, the game structure in each
195 back end must have a different name, and there's a helper module
196 \c{list.c} which contains a complete list of those game structures.
197
198 On the latter type of platform, source files may assume that the
199 preprocessor symbol \c{COMBINED} has been defined. Thus, the usual
200 code to declare the game structure looks something like this:
201
202 \c #ifdef COMBINED
203 \c #define thegame net    /* or whatever this game is called */
204 \e                 iii    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
205 \c #endif
206 \c 
207 \c const struct game thegame = {
208 \c     /* lots of structure initialisation in here */
209 \e     iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
210 \c };
211
212 Game back ends must also internally define a number of data
213 structures, for storing their various persistent state. This chapter
214 will first discuss the nature and use of those structures, and then
215 go on to give details of every element of the game structure.
216
217 \H{backend-structs} Data structures
218
219 Each game is required to define four separate data structures. This
220 section discusses each one and suggests what sorts of things need to
221 be put in it.
222
223 \S{backend-game-params} \c{game_params}
224
225 The \c{game_params} structure contains anything which affects the
226 automatic generation of new puzzles. So if puzzle generation is
227 parametrised in any way, those parameters need to be stored in
228 \c{game_params}.
229
230 Most puzzles currently in this collection are played on a grid of
231 squares, meaning that the most obvious parameter is the grid size.
232 Many puzzles have additional parameters; for example, Mines allows
233 you to control the number of mines in the grid independently of its
234 size, Net can be wrapping or non-wrapping, Solo has difficulty
235 levels and symmetry settings, and so on.
236
237 A simple rule for deciding whether a data item needs to go in
238 \c{game_params} is: would the user expect to be able to control this
239 data item from either the preset-game-types menu or the \q{Custom}
240 game type configuration? If so, it's part of \c{game_params}.
241
242 \c{game_params} structures are permitted to contain pointers to
243 subsidiary data if they need to. The back end is required to provide
244 functions to create and destroy \c{game_params}, and those functions
245 can allocate and free additional memory if necessary. (It has not
246 yet been necessary to do this in any puzzle so far, but the
247 capability is there just in case.)
248
249 \c{game_params} is also the only structure which the game's
250 \cw{compute_size()} function may refer to; this means that any
251 aspect of the game which affects the size of the window it needs to
252 be drawn in must be stored in \c{game_params}. In particular, this
253 imposes the fundamental limitation that random game generation may
254 not have a random effect on the window size: game generation
255 algorithms are constrained to work by starting from the grid size
256 rather than generating it as an emergent phenomenon. (Although this
257 is a restriction in theory, it has not yet seemed to be a problem.)
258
259 \S{backend-game-state} \c{game_state}
260
261 While the user is actually playing a puzzle, the \c{game_state}
262 structure stores all the data corresponding to the current state of
263 play.
264
265 The mid-end keeps \c{game_state}s in a list, and adds to the list
266 every time the player makes a move; the Undo and Redo functions step
267 back and forth through that list.
268
269 Therefore, a good means of deciding whether a data item needs to go
270 in \c{game_state} is: would a player expect that data item to be
271 restored on undo? If so, put it in \c{game_state}, and this will
272 automatically happen without you having to lift a finger. If not
273 \dash for example, the deaths counter in Mines is precisely
274 something that does \e{not} want to be reset to its previous state
275 on an undo \dash then you might have found a data item that needs to
276 go in \c{game_ui} instead.
277
278 During play, \c{game_state}s are often passed around without an
279 accompanying \c{game_params} structure. Therefore, any information
280 in \c{game_params} which is important during play (such as the grid
281 size) must be duplicated within the \c{game_state}. One simple
282 method of doing this is to have the \c{game_state} structure
283 \e{contain} a \c{game_params} structure as one of its members,
284 although this isn't obligatory if you prefer to do it another way.
285
286 \S{backend-game-drawstate} \c{game_drawstate}
287
288 \c{game_drawstate} carries persistent state relating to the current
289 graphical contents of the puzzle window. The same \c{game_drawstate}
290 is passed to every call to the game redraw function, so that it can
291 remember what it has already drawn and what needs redrawing.
292
293 A typical use for a \c{game_drawstate} is to have an array mirroring
294 the array of grid squares in the \c{game_state}; then every time the
295 redraw function was passed a \c{game_state}, it would loop over all
296 the squares, and physically redraw any whose description in the
297 \c{game_state} (i.e. what the square needs to look like when the
298 redraw is completed) did not match its description in the
299 \c{game_drawstate} (i.e. what the square currently looks like).
300
301 \c{game_drawstate} is occasionally completely torn down and
302 reconstructed by the mid-end, if the user somehow forces a full
303 redraw. Therefore, no data should be stored in \c{game_drawstate}
304 which is \e{not} related to the state of the puzzle window, because
305 it might be unexpectedly destroyed.
306
307 The back end provides functions to create and destroy
308 \c{game_drawstate}, which means it can contain pointers to
309 subsidiary allocated data if it needs to. A common thing to want to
310 allocate in a \c{game_drawstate} is a \c{blitter}; see
311 \k{drawing-blitter} for more on this subject.
312
313 \S{backend-game-ui} \c{game_ui}
314
315 \c{game_ui} contains whatever doesn't fit into the above three
316 structures!
317
318 A new \c{game_ui} is created when the user begins playing a new
319 instance of a puzzle (i.e. during \q{New Game} or after entering a
320 game ID etc). It persists until the user finishes playing that game
321 and begins another one (or closes the window); in particular,
322 \q{Restart Game} does \e{not} destroy the \c{game_ui}.
323
324 \c{game_ui} is useful for implementing user-interface state which is
325 not part of \c{game_state}. Common examples are keyboard control
326 (you wouldn't want to have to separately Undo through every cursor
327 motion) and mouse dragging. See \k{writing-keyboard-cursor} and
328 \k{writing-howto-dragging}, respectively, for more details.
329
330 Another use for \c{game_ui} is to store highly persistent data such
331 as the Mines death counter. This is conceptually rather different:
332 where the Net cursor position was \e{not important enough} to
333 preserve for the player to restore by Undo, the Mines death counter
334 is \e{too important} to permit the player to revert by Undo!
335
336 A final use for \c{game_ui} is to pass information to the redraw
337 function about recent changes to the game state. This is used in
338 Mines, for example, to indicate whether a requested \q{flash} should
339 be a white flash for victory or a red flash for defeat; see
340 \k{writing-flash-types}.
341
342 \H{backend-simple} Simple data in the back end
343
344 In this section I begin to discuss each individual element in the
345 back end structure. To begin with, here are some simple
346 self-contained data elements.
347
348 \S{backend-name} \c{name}
349
350 \c const char *name;
351
352 This is a simple ASCII string giving the name of the puzzle. This
353 name will be used in window titles, in game selection menus on
354 monolithic platforms, and anywhere else that the front end needs to
355 know the name of a game.
356
357 \S{backend-winhelp} \c{winhelp_topic}
358
359 \c const char *winhelp_topic;
360
361 This member is used on Windows only, to provide online help.
362 Although the Windows front end provides a separate binary for each
363 puzzle, it has a single monolithic help file; so when a user selects
364 \q{Help} from the menu, the program needs to open the help file and
365 jump to the chapter describing that particular puzzle.
366
367 Therefore, each chapter in \c{puzzles.but} is labelled with a
368 \e{help topic} name, similar to this:
369
370 \c \cfg{winhelp-topic}{games.net}
371
372 And then the corresponding game back end encodes the topic string
373 (here \cq{games.net}) in the \c{winhelp_topic} element of the game
374 structure.
375
376 \H{backend-params} Handling game parameter sets
377
378 In this section I present the various functions which handle the
379 \c{game_params} structure.
380
381 \S{backend-default-params} \cw{default_params()}
382
383 \c game_params *(*default_params)(void);
384
385 This function allocates a new \c{game_params} structure, fills it
386 with the default values, and returns a pointer to it.
387
388 \S{backend-fetch-preset} \cw{fetch_preset()}
389
390 \c int (*fetch_preset)(int i, char **name, game_params **params);
391
392 This function is used to populate the \q{Type} menu, which provides
393 a list of conveniently accessible preset parameters for most games.
394
395 The function is called with \c{i} equal to the index of the preset
396 required (numbering from zero). It returns \cw{FALSE} if that preset
397 does not exist (if \c{i} is less than zero or greater than the
398 largest preset index). Otherwise, it sets \c{*params} to point at a
399 newly allocated \c{game_params} structure containing the preset
400 information, sets \c{*name} to point at a newly allocated C string
401 containing the preset title (to go on the \q{Type} menu), and
402 returns \cw{TRUE}.
403
404 If the game does not wish to support any presets at all, this
405 function is permitted to return \cw{FALSE} always.
406
407 \S{backend-encode-params} \cw{encode_params()}
408
409 \c char *(*encode_params)(game_params *params, int full);
410
411 The job of this function is to take a \c{game_params}, and encode it
412 in a string form for use in game IDs. The return value must be a
413 newly allocated C string, and \e{must} not contain a colon or a hash
414 (since those characters are used to mark the end of the parameter
415 section in a game ID).
416
417 Ideally, it should also not contain any other potentially
418 controversial punctuation; bear in mind when designing a string
419 parameter format that it will probably be used on both Windows and
420 Unix command lines under a variety of exciting shell quoting and
421 metacharacter rules. Sticking entirely to alphanumerics is the
422 safest thing; if you really need punctuation, you can probably get
423 away with commas, periods or underscores without causing anybody any
424 major inconvenience. If you venture far beyond that, you're likely
425 to irritate \e{somebody}.
426
427 (At the time of writing this, all existing games have purely
428 alphanumeric string parameter formats. Usually these involve a
429 letter denoting a parameter, followed optionally by a number giving
430 the value of that parameter, with a few mandatory parts at the
431 beginning such as numeric width and height separated by \cq{x}.)
432
433 If the \c{full} parameter is \cw{TRUE}, this function should encode
434 absolutely everything in the \c{game_params}, such that a subsequent
435 call to \cw{decode_params()} (\k{backend-decode-params}) will yield
436 an identical structure. If \c{full} is \cw{FALSE}, however, you
437 should leave out anything which is not necessary to describe a
438 \e{specific puzzle instance}, i.e. anything which only takes effect
439 when a new puzzle is \e{generated}. For example, the Solo
440 \c{game_params} includes a difficulty rating used when constructing
441 new puzzles; but a Solo game ID need not explicitly include the
442 difficulty, since to describe a puzzle once generated it's
443 sufficient to give the grid dimensions and the location and contents
444 of the clue squares. (Indeed, one might very easily type in a puzzle
445 out of a newspaper without \e{knowing} what its difficulty level is
446 in Solo's terminology.) Therefore. Solo's \cw{encode_params()} only
447 encodes the difficulty level if \c{full} is set.
448
449 \S{backend-decode-params} \cw{decode_params()}
450
451 \c void (*decode_params)(game_params *params, char const *string);
452
453 This function is the inverse of \cw{encode_params()}
454 (\k{backend-encode-params}). It parses the supplied string and fills
455 in the supplied \c{game_params} structure. Note that the structure
456 will \e{already} have been allocated: this function is not expected
457 to create a \e{new} \c{game_params}, but to modify an existing one.
458
459 This function can receive a string which only encodes a subset of
460 the parameters. The most obvious way in which this can happen is if
461 the string was constructed by \cw{encode_params()} with its \c{full}
462 parameter set to \cw{FALSE}; however, it could also happen if the
463 user typed in a parameter set manually and missed something out. Be
464 prepared to deal with a wide range of possibilities.
465
466 When dealing with a parameter which is not specified in the input
467 string, what to do requires a judgment call on the part of the
468 programmer. Sometimes it makes sense to adjust other parameters to
469 bring them into line with the new ones. In Mines, for example, you
470 would probably not want to keep the same mine count if the user
471 dropped the grid size and didn't specify one, since you might easily
472 end up with more mines than would actually fit in the grid! On the
473 other hand, sometimes it makes sense to leave the parameter alone: a
474 Solo player might reasonably expect to be able to configure size and
475 difficulty independently of one another.
476
477 This function currently has no direct means of returning an error if
478 the string cannot be parsed at all. However, the returned
479 \c{game_params} is almost always subsequently passed to
480 \cw{validate_params()} (\k{backend-validate-params}), so if you
481 really want to signal parse errors, you could always have a \c{char
482 *} in your parameters structure which stored an error message, and
483 have \cw{validate_params()} return it if it is non-\cw{NULL}.
484
485 \S{backend-free-params} \cw{free_params()}
486
487 \c void (*free_params)(game_params *params);
488
489 This function frees a \c{game_params} structure, and any subsidiary
490 allocations contained within it.
491
492 \S{backend-dup-params} \cw{dup_params()}
493
494 \c game_params *(*dup_params)(game_params *params);
495
496 This function allocates a new \c{game_params} structure and
497 initialises it with an exact copy of the information in the one
498 provided as input. It returns a pointer to the new duplicate.
499
500 \S{backend-can-configure} \c{can_configure}
501
502 \c int can_configure;
503
504 This boolean data element is set to \cw{TRUE} if the back end
505 supports custom parameter configuration via a dialog box. If it is
506 \cw{TRUE}, then the functions \cw{configure()} and
507 \cw{custom_params()} are expected to work. See \k{backend-configure}
508 and \k{backend-custom-params} for more details.
509
510 \S{backend-configure} \cw{configure()}
511
512 \c config_item *(*configure)(game_params *params);
513
514 This function is called when the user requests a dialog box for
515 custom parameter configuration. It returns a newly allocated array
516 of \cw{config_item} structures, describing the GUI elements required
517 in the dialog box. The array should have one more element than the
518 number of controls, since it is terminated with a \cw{C_END} marker
519 (see below). Each array element describes the control together with
520 its initial value; the front end will modify the value fields and
521 return the updated array to \cw{custom_params()} (see
522 \k{backend-custom-params}).
523
524 The \cw{config_item} structure contains the following elements:
525
526 \c char *name;
527 \c int type;
528 \c char *sval;
529 \c int ival;
530
531 \c{name} is an ASCII string giving the textual label for a GUI
532 control. It is \e{not} expected to be dynamically allocated.
533
534 \c{type} contains one of a small number of \c{enum} values defining
535 what type of control is being described. The meaning of the \c{sval}
536 and \c{ival} fields depends on the value in \c{type}. The valid
537 values are:
538
539 \dt \c{C_STRING}
540
541 \dd Describes a text input box. (This is also used for numeric
542 input. The back end does not bother informing the front end that the
543 box is numeric rather than textual; some front ends do have the
544 capacity to take this into account, but I decided it wasn't worth
545 the extra complexity in the interface.) For this type, \c{ival} is
546 unused, and \c{sval} contains a dynamically allocated string
547 representing the contents of the input box.
548
549 \dt \c{C_BOOLEAN}
550
551 \dd Describes a simple checkbox. For this type, \c{sval} is unused,
552 and \c{ival} is \cw{TRUE} or \cw{FALSE}.
553
554 \dt \c{C_CHOICES}
555
556 \dd Describes a drop-down list presenting one of a small number of
557 fixed choices. For this type, \c{sval} contains a list of strings
558 describing the choices; the very first character of \c{sval} is used
559 as a delimiter when processing the rest (so that the strings
560 \cq{:zero:one:two}, \cq{!zero!one!two} and \cq{xzeroxonextwo} all
561 define a three-element list containing \cq{zero}, \cq{one} and
562 \cq{two}). \c{ival} contains the index of the currently selected
563 element, numbering from zero (so that in the above example, 0 would
564 mean \cq{zero} and 2 would mean \cq{two}).
565
566 \lcont{
567
568 Note that for this control type, \c{sval} is \e{not} dynamically
569 allocated, whereas it was for \c{C_STRING}.
570
571 }
572
573 \dt \c{C_END}
574
575 \dd Marks the end of the array of \c{config_item}s. All other fields
576 are unused.
577
578 The array returned from this function is expected to have filled in
579 the initial values of all the controls according to the input
580 \c{game_params} structure.
581
582 If the game's \c{can_configure} flag is set to \cw{FALSE}, this
583 function is never called and need not do anything at all.
584
585 \S{backend-custom-params} \cw{custom_params()}
586
587 \c game_params *(*custom_params)(config_item *cfg);
588
589 This function is the counterpart to \cw{configure()}
590 (\k{backend-configure}). It receives as input an array of
591 \c{config_item}s which was originally created by \cw{configure()},
592 but in which the control values have since been changed in
593 accordance with user input. Its function is to read the new values
594 out of the controls and return a newly allocated \c{game_params}
595 structure representing the user's chosen parameter set.
596
597 (The front end will have modified the controls' \e{values}, but
598 there will still always be the same set of controls, in the same
599 order, as provided by \cw{configure()}. It is not necessary to check
600 the \c{name} and \c{type} fields, although you could use
601 \cw{assert()} if you were feeling energetic.)
602
603 This function is not expected to (and indeed \e{must not}) free the
604 input \c{config_item} array. (If the parameters fail to validate,
605 the dialog box will stay open.)
606
607 If the game's \c{can_configure} flag is set to \cw{FALSE}, this
608 function is never called and need not do anything at all.
609
610 \S{backend-validate-params} \cw{validate_params()}
611
612 \c char *(*validate_params)(game_params *params, int full);
613
614 This function takes a \c{game_params} structure as input, and checks
615 that the parameters described in it fall within sensible limits. (At
616 the very least, grid dimensions should almost certainly be strictly
617 positive, for example.)
618
619 Return value is \cw{NULL} if no problems were found, or
620 alternatively a (non-dynamically-allocated) ASCII string describing
621 the error in human-readable form.
622
623 If the \c{full} parameter is set, full validation should be
624 performed: any set of parameters which would not permit generation
625 of a sensible puzzle should be faulted. If \c{full} is \e{not} set,
626 the implication is that these parameters are not going to be used
627 for \e{generating} a puzzle; so parameters which can't even sensibly
628 \e{describe} a valid puzzle should still be faulted, but parameters
629 which only affect puzzle generation should not be.
630
631 (The \c{full} option makes a difference when parameter combinations
632 are non-orthogonal. For example, Net has a boolean option
633 controlling whether it enforces a unique solution; it turns out that
634 it's impossible to generate a uniquely soluble puzzle with wrapping
635 walls and width 2, so \cw{validate_params()} will complain if you
636 ask for one. However, if the user had just been playing a unique
637 wrapping puzzle of a more sensible width, and then pastes in a game
638 ID acquired from somebody else which happens to describe a
639 \e{non}-unique wrapping width-2 puzzle, then \cw{validate_params()}
640 will be passed a \c{game_params} containing the width and wrapping
641 settings from the new game ID and the uniqueness setting from the
642 old one. This would be faulted, if it weren't for the fact that
643 \c{full} is not set during this call, so Net ignores the
644 inconsistency. The resulting \c{game_params} is never subsequently
645 used to generate a puzzle; this is a promise made by the mid-end
646 when it asks for a non-full validation.)
647
648 \H{backend-descs} Handling game descriptions
649
650 In this section I present the functions that deal with a textual
651 description of a puzzle, i.e. the part that comes after the colon in
652 a descriptive-format game ID.
653
654 \S{backend-new-desc} \cw{new_desc()}
655
656 \c char *(*new_desc)(game_params *params, random_state *rs,
657 \c                   char **aux, int interactive);
658
659 This function is where all the really hard work gets done. This is
660 the function whose job is to randomly generate a new puzzle,
661 ensuring solubility and uniqueness as appropriate.
662
663 As input it is given a \c{game_params} structure and a random state
664 (see \k{utils-random} for the random number API). It must invent a
665 puzzle instance, encode it in string form, and return a dynamically
666 allocated C string containing that encoding.
667
668 Additionally, it may return a second dynamically allocated string in
669 \c{*aux}. (If it doesn't want to, then it can leave that parameter
670 completely alone; it isn't required to set it to \cw{NULL}, although
671 doing so is harmless.) That string, if present, will be passed to
672 \cw{solve()} (\k{backend-solve}) later on; so if the puzzle is
673 generated in such a way that a solution is known, then information
674 about that solution can be saved in \c{*aux} for \cw{solve()} to
675 use.
676
677 The \c{interactive} parameter should be ignored by almost all
678 puzzles. Its purpose is to distinguish between generating a puzzle
679 within a GUI context for immediate play, and generating a puzzle in
680 a command-line context for saving to be played later. The only
681 puzzle that currently uses this distinction (and, I fervently hope,
682 the only one which will \e{ever} need to use it) is Mines, which
683 chooses a random first-click location when generating puzzles
684 non-interactively, but which waits for the user to place the first
685 click when interactive. If you think you have come up with another
686 puzzle which needs to make use of this parameter, please think for
687 at least ten minutes about whether there is \e{any} alternative!
688
689 Note that game description strings are not required to contain an
690 encoding of parameters such as grid size; a game description is
691 never separated from the \c{game_params} it was generated with, so
692 any information contained in that structure need not be encoded
693 again in the game description.
694
695 \S{backend-validate-desc} \cw{validate_desc()}
696
697 \c char *(*validate_desc)(game_params *params, char *desc);
698
699 This function is given a game description, and its job is to
700 validate that it describes a puzzle which makes sense.
701
702 To some extent it's up to the user exactly how far they take the
703 phrase \q{makes sense}; there are no particularly strict rules about
704 how hard the user is permitted to shoot themself in the foot when
705 typing in a bogus game description by hand. (For example, Rectangles
706 will not verify that the sum of all the numbers in the grid equals
707 the grid's area. So a user could enter a puzzle which was provably
708 not soluble, and the program wouldn't complain; there just wouldn't
709 happen to be any sequence of moves which solved it.)
710
711 The one non-negotiable criterion is that any game description which
712 makes it through \cw{validate_desc()} \e{must not} subsequently
713 cause a crash or an assertion failure when fed to \cw{new_game()}
714 and thence to the rest of the back end.
715
716 The return value is \cw{NULL} on success, or a
717 non-dynamically-allocated C string containing an error message.
718
719 \S{backend-new-game} \cw{new_game()}
720
721 \c game_state *(*new_game)(midend *me, game_params *params,
722 \c                         char *desc);
723
724 This function takes a game description as input, together with its
725 accompanying \c{game_params}, and constructs a \c{game_state}
726 describing the initial state of the puzzle. It returns a newly
727 allocated \c{game_state} structure.
728
729 Almost all puzzles should ignore the \c{me} parameter. It is
730 required by Mines, which needs it for later passing to
731 \cw{midend_supersede_game_desc()} (see \k{backend-supersede}) once
732 the user has placed the first click. I fervently hope that no other
733 puzzle will be awkward enough to require it, so everybody else
734 should ignore it. As with the \c{interactive} parameter in
735 \cw{new_desc()} (\k{backend-new-desc}), if you think you have a
736 reason to need this parameter, please try very hard to think of an
737 alternative approach!
738
739 \H{backend-states} Handling game states
740
741 This section describes the functions which create and destroy
742 \c{game_state} structures.
743
744 (Well, except \cw{new_game()}, which is in \k{backend-new-game}
745 instead of under here; but it deals with game descriptions \e{and}
746 game states and it had to go in one section or the other.)
747
748 \S{backend-dup-game} \cw{dup_game()}
749
750 \c game_state *(*dup_game)(game_state *state);
751
752 This function allocates a new \c{game_state} structure and
753 initialises it with an exact copy of the information in the one
754 provided as input. It returns a pointer to the new duplicate.
755
756 \S{backend-free-game} \cw{free_game()}
757
758 \c void (*free_game)(game_state *state);
759
760 This function frees a \c{game_state} structure, and any subsidiary
761 allocations contained within it.
762
763 \H{backend-ui} Handling \c{game_ui}
764
765 \S{backend-new-ui} \cw{new_ui()}
766
767 \c game_ui *(*new_ui)(game_state *state);
768
769 This function allocates and returns a new \c{game_ui} structure for
770 playing a particular puzzle. It is passed a pointer to the initial
771 \c{game_state}, in case it needs to refer to that when setting up
772 the initial values for the new game.
773
774 \S{backend-free-ui} \cw{free_ui()}
775
776 \c void (*free_ui)(game_ui *ui);
777
778 This function frees a \c{game_ui} structure, and any subsidiary
779 allocations contained within it.
780
781 \S{backend-encode-ui} \cw{encode_ui()}
782
783 \c char *(*encode_ui)(game_ui *ui);
784
785 This function encodes any \e{important} data in a \c{game_ui}
786 structure in string form. It is only called when saving a
787 half-finished game to a file.
788
789 It should be used sparingly. Almost all data in a \c{game_ui} is not
790 important enough to save. The location of the keyboard-controlled
791 cursor, for example, can be reset to a default position on reloading
792 the game without impacting the user experience. If the user should
793 somehow manage to save a game while a mouse drag was in progress,
794 then discarding that mouse drag would be an outright \e{feature},
795
796 A typical thing that \e{would} be worth encoding in this function is
797 the Mines death counter: it's in the \c{game_ui} rather than the
798 \c{game_state} because it's too important to allow the user to
799 revert it by using Undo, and therefore it's also too important to
800 allow the user to revert it by saving and reloading. (Of course, the
801 user could edit the save file by hand... But if the user is \e{that}
802 determined to cheat, they could just as easily modify the game's
803 source.)
804
805 \S{backend-decode-ui} \cw{decode_ui()}
806
807 \c void (*decode_ui)(game_ui *ui, char *encoding);
808
809 This function parses a string previously output by \cw{encode_ui()},
810 and writes the decoded data back into the provided \c{game_ui}
811 structure.
812
813 \S{backend-changed-state} \cw{changed_state()}
814
815 \c void (*changed_state)(game_ui *ui, game_state *oldstate,
816 \c                       game_state *newstate);
817
818 This function is called by the mid-end whenever the current game
819 state changes, for any reason. Those reasons include:
820
821 \b a fresh move being made by \cw{interpret_move()} and
822 \cw{execute_move()}
823
824 \b a solve operation being performed by \cw{solve()} and
825 \cw{execute_move()}
826
827 \b the user moving back and forth along the undo list by means of
828 the Undo and Redo operations
829
830 \b the user selecting Restart to go back to the initial game state.
831
832 The job of \cw{changed_state()} is to update the \c{game_ui} for
833 consistency with the new game state, if any update is necessary. For
834 example, Same Game stores data about the currently selected tile
835 group in its \c{game_ui}, and this data is intrinsically related to
836 the game state it was derived from. So it's very likely to become
837 invalid when the game state changes; thus, Same Game's
838 \cw{changed_state()} function clears the current selection whenever
839 it is called.
840
841 When \cw{anim_length()} or \cw{flash_length()} are called, you can
842 be sure that there has been a previous call to \cw{changed_state()}.
843 So \cw{changed_state()} can set up data in the \c{game_ui} which will
844 be read by \cw{anim_length()} and \cw{flash_length()}, and those
845 functions will not have to worry about being called without the data
846 having been initialised.
847
848 \H{backend-moves} Making moves
849
850 This section describes the functions which actually make moves in
851 the game: that is, the functions which process user input and end up
852 producing new \c{game_state}s.
853
854 \S{backend-interpret-move} \cw{interpret_move()}
855
856 \c char *(*interpret_move)(game_state *state, game_ui *ui,
857 \c                         game_drawstate *ds,
858 \c                         int x, int y, int button);
859
860 This function receives user input and processes it. Its input
861 parameters are the current \c{game_state}, the current \c{game_ui}
862 and the current \c{game_drawstate}, plus details of the input event.
863 \c{button} is either an ASCII value or a special code (listed below)
864 indicating an arrow or function key or a mouse event; when
865 \c{button} is a mouse event, \c{x} and \c{y} contain the pixel
866 coordinates of the mouse pointer relative to the top left of the
867 puzzle's drawing area.
868
869 \cw{interpret_move()} may return in three different ways:
870
871 \b Returning \cw{NULL} indicates that no action whatsoever occurred
872 in response to the input event; the puzzle was not interested in it
873 at all.
874
875 \b Returning the empty string (\cw{""}) indicates that the input
876 event has resulted in a change being made to the \c{game_ui} which
877 will require a redraw of the game window, but that no actual
878 \e{move} was made (i.e. no new \c{game_state} needs to be created).
879
880 \b Returning anything else indicates that a move was made and that a
881 new \c{game_state} must be created. However, instead of actually
882 constructing a new \c{game_state} itself, this function is required
883 to return a string description of the details of the move. This
884 string will be passed to \cw{execute_move()}
885 (\k{backend-execute-move}) to actually create the new
886 \c{game_state}. (Encoding moves as strings in this way means that
887 the mid-end can keep the strings as well as the game states, and the
888 strings can be written to disk when saving the game and fed to
889 \cw{execute_move()} again on reloading.)
890
891 The return value from \cw{interpret_move()} is expected to be
892 dynamically allocated if and only if it is not either \cw{NULL}
893 \e{or} the empty string.
894
895 After this function is called, the back end is permitted to rely on
896 some subsequent operations happening in sequence:
897
898 \b \cw{execute_move()} will be called to convert this move
899 description into a new \c{game_state}
900
901 \b \cw{changed_state()} will be called with the new \c{game_state}.
902
903 This means that if \cw{interpret_move()} needs to do updates to the
904 \c{game_ui} which are easier to perform by referring to the new
905 \c{game_state}, it can safely leave them to be done in
906 \cw{changed_state()} and not worry about them failing to happen.
907
908 (Note, however, that \cw{execute_move()} may \e{also} be called in
909 other circumstances. It is only \cw{interpret_move()} which can rely
910 on a subsequent call to \cw{changed_state()}.)
911
912 The special key codes supported by this function are:
913
914 \dt \cw{LEFT_BUTTON}, \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}
915
916 \dd Indicate that one of the mouse buttons was pressed down.
917
918 \dt \cw{LEFT_DRAG}, \cw{MIDDLE_DRAG}, \cw{RIGHT_DRAG}
919
920 \dd Indicate that the mouse was moved while one of the mouse buttons
921 was still down. The mid-end guarantees that when one of these events
922 is received, it will always have been preceded by a button-down
923 event (and possibly other drag events) for the same mouse button,
924 and no event involving another mouse button will have appeared in
925 between.
926
927 \dt \cw{LEFT_RELEASE}, \cw{MIDDLE_RELEASE}, \cw{RIGHT_RELEASE}
928
929 \dd Indicate that a mouse button was released.  The mid-end
930 guarantees that when one of these events is received, it will always
931 have been preceded by a button-down event (and possibly some drag
932 events) for the same mouse button, and no event involving another
933 mouse button will have appeared in between.
934
935 \dt \cw{CURSOR_UP}, \cw{CURSOR_DOWN}, \cw{CURSOR_LEFT},
936 \cw{CURSOR_RIGHT}
937
938 \dd Indicate that an arrow key was pressed.
939
940 \dt \cw{CURSOR_SELECT}
941
942 \dd On platforms which have a prominent \q{select} button alongside
943 their cursor keys, indicates that that button was pressed.
944
945 In addition, there are some modifiers which can be bitwise-ORed into
946 the \c{button} parameter:
947
948 \dt \cw{MOD_CTRL}, \cw{MOD_SHFT}
949
950 \dd These indicate that the Control or Shift key was pressed
951 alongside the key. They only apply to the cursor keys, not to mouse
952 buttons or anything else.
953
954 \dt \cw{MOD_NUM_KEYPAD}
955
956 \dd This applies to some ASCII values, and indicates that the key
957 code was input via the numeric keypad rather than the main keyboard.
958 Some puzzles may wish to treat this differently (for example, a
959 puzzle might want to use the numeric keypad as an eight-way
960 directional pad), whereas others might not (a game involving numeric
961 input probably just wants to treat the numeric keypad as numbers).
962
963 \dt \cw{MOD_MASK}
964
965 \dd This mask is the bitwise OR of all the available modifiers; you
966 can bitwise-AND with \cw{~MOD_MASK} to strip all the modifiers off
967 any input value.
968
969 \S{backend-execute-move} \cw{execute_move()}
970
971 \c game_state *(*execute_move)(game_state *state, char *move);
972
973 This function takes an input \c{game_state} and a move string as
974 output from \cw{interpret_move()}. It returns a newly allocated
975 \c{game_state} which contains the result of applying the specified
976 move to the input game state.
977
978 This function may return \cw{NULL} if it cannot parse the move
979 string (and this is definitely preferable to crashing or failing an
980 assertion, since one way this can happen is if loading a corrupt
981 save file). However, it must not return \cw{NULL} for any move
982 string that really was output from \cw{interpret_move()}: this is
983 punishable by assertion failure in the mid-end.
984
985 \S{backend-can-solve} \c{can_solve}
986
987 \c int can_solve;
988
989 This boolean field is set to \cw{TRUE} if the game's \cw{solve()}
990 function does something. If it's set to \cw{FALSE}, the game will
991 not even offer the \q{Solve} menu option.
992
993 \S{backend-solve} \cw{solve()}
994
995 \c char *(*solve)(game_state *orig, game_state *curr,
996 \c                char *aux, char **error);
997
998 This function is called when the user selects the \q{Solve} option
999 from the menu.
1000
1001 It is passed two input game states: \c{orig} is the game state from
1002 the very start of the puzzle, and \c{curr} is the current one.
1003 (Different games find one or other or both of these convenient.) It
1004 is also passed the \c{aux} string saved by \cw{new_desc()}
1005 (\k{backend-new-desc}), in case that encodes important information
1006 needed to provide the solution.
1007
1008 If this function is unable to produce a solution (perhaps, for
1009 example, the game has no in-built solver so it can only solve
1010 puzzles it invented internally and has an \c{aux} string for) then
1011 it may return \cw{NULL}. If it does this, it must also set
1012 \c{*error} to an error message to be presented to the user (such as
1013 \q{Solution not known for this puzzle}); that error message is not
1014 expected to be dynamically allocated.
1015
1016 If this function \e{does} produce a solution, it returns a move
1017 string suitable for feeding to \cw{execute_move()}
1018 (\k{backend-execute-move}).
1019
1020 \H{backend-drawing} Drawing the game graphics
1021
1022 This section discusses the back end functions that deal with
1023 drawing.
1024
1025 \S{backend-new-drawstate} \cw{new_drawstate()}
1026
1027 \c game_drawstate *(*new_drawstate)(drawing *dr, game_state *state);
1028
1029 This function allocates and returns a new \c{game_drawstate}
1030 structure for drawing a particular puzzle. It is passed a pointer to
1031 a \c{game_state}, in case it needs to refer to that when setting up
1032 any initial data.
1033
1034 This function may not rely on the puzzle having been newly started;
1035 a new draw state can be constructed at any time if the front end
1036 requests a forced redraw. For games like Pattern, in which initial
1037 game states are much simpler than general ones, this might be
1038 important to keep in mind.
1039
1040 The parameter \c{dr} is a drawing object (see \k{drawing}) which the
1041 function might need to use to allocate blitters. (However, this
1042 isn't recommended; it's usually more sensible to wait to allocate a
1043 blitter until \cw{set_size()} is called, because that way you can
1044 tailor it to the scale at which the puzzle is being drawn.)
1045
1046 \S{backend-free-drawstate} \cw{free_drawstate()}
1047
1048 \c void (*free_drawstate)(drawing *dr, game_drawstate *ds);
1049
1050 This function frees a \c{game_drawstate} structure, and any
1051 subsidiary allocations contained within it.
1052
1053 The parameter \c{dr} is a drawing object (see \k{drawing}), which
1054 might be required if you are freeing a blitter.
1055
1056 \S{backend-preferred-tilesize} \c{preferred_tilesize}
1057
1058 \c int preferred_tilesize;
1059
1060 Each game is required to define a single integer parameter which
1061 expresses, in some sense, the scale at which it is drawn. This is
1062 described in the APIs as \cq{tilesize}, since most puzzles are on a
1063 square (or possibly triangular or hexagonal) grid and hence a
1064 sensible interpretation of this parameter is to define it as the
1065 size of one grid tile in pixels; however, there's no actual
1066 requirement that the \q{tile size} be proportional to the game
1067 window size. Window size is required to increase monotonically with
1068 \q{tile size}, however.
1069
1070 The data element \c{preferred_tilesize} indicates the tile size
1071 which should be used in the absence of a good reason to do otherwise
1072 (such as the screen being too small, or the user explicitly
1073 requesting a resize if that ever gets implemented).
1074
1075 \S{backend-compute-size} \cw{compute_size()}
1076
1077 \c void (*compute_size)(game_params *params, int tilesize,
1078 \c                      int *x, int *y);
1079
1080 This function is passed a \c{game_params} structure and a tile size.
1081 It returns, in \c{*x} and \c{*y}, the size in pixels of the drawing
1082 area that would be required to render a puzzle with those parameters
1083 at that tile size.
1084
1085 \S{backend-set-size} \cw{set_size()}
1086
1087 \c void (*set_size)(drawing *dr, game_drawstate *ds,
1088 \c                  game_params *params, int tilesize);
1089
1090 This function is responsible for setting up a \c{game_drawstate} to
1091 draw at a given tile size. Typically this will simply involve
1092 copying the supplied \c{tilesize} parameter into a \c{tilesize}
1093 field inside the draw state; for some more complex games it might
1094 also involve setting up other dimension fields, or possibly
1095 allocating a blitter (see \k{drawing-blitter}).
1096
1097 The parameter \c{dr} is a drawing object (see \k{drawing}), which is
1098 required if a blitter needs to be allocated.
1099
1100 Back ends may assume (and may enforce by assertion) that this
1101 function will be called at most once for any \c{game_drawstate}. If
1102 a puzzle needs to be redrawn at a different size, the mid-end will
1103 create a fresh drawstate.
1104
1105 \S{backend-colours} \cw{colours()}
1106
1107 \c float *(*colours)(frontend *fe, int *ncolours);
1108
1109 This function is responsible for telling the front end what colours
1110 the puzzle will need to draw itself.
1111
1112 It returns the number of colours required in \c{*ncolours}, and the
1113 return value from the function itself is a dynamically allocated
1114 array of three times that many \c{float}s, containing the red, green
1115 and blue components of each colour respectively as numbers in the
1116 range [0,1].
1117
1118 The second parameter passed to this function is a front end handle.
1119 The only things it is permitted to do with this handle are to call
1120 the front-end function called \cw{frontend_default_colour()} (see
1121 \k{frontend-default-colour}) or the utility function called
1122 \cw{game_mkhighlight()} (see \k{utils-game-mkhighlight}). (The
1123 latter is a wrapper on the former, so front end implementors only
1124 need to provide \cw{frontend_default_colour()}.) This allows
1125 \cw{colours()} to take local configuration into account when
1126 deciding on its own colour allocations. Most games use the front
1127 end's default colour as their background, apart from a few which
1128 depend on drawing relief highlights so they adjust the background
1129 colour if it's too light for highlights to show up against it.
1130
1131 Note that the colours returned from this function are for
1132 \e{drawing}, not for printing. Printing has an entirely different
1133 colour allocation policy.
1134
1135 \S{backend-anim-length} \cw{anim_length()}
1136
1137 \c float (*anim_length)(game_state *oldstate, game_state *newstate,
1138 \c                      int dir, game_ui *ui);
1139
1140 This function is called when a move is made, undone or redone. It is
1141 given the old and the new \c{game_state}, and its job is to decide
1142 whether the transition between the two needs to be animated or can
1143 be instant.
1144
1145 \c{oldstate} is the state that was current until this call;
1146 \c{newstate} is the state that will be current after it. \c{dir}
1147 specifies the chronological order of those states: if it is
1148 positive, then the transition is the result of a move or a redo (and
1149 so \c{newstate} is the later of the two moves), whereas if it is
1150 negative then the transition is the result of an undo (so that
1151 \c{newstate} is the \e{earlier} move).
1152
1153 If this function decides the transition should be animated, it
1154 returns the desired length of the animation in seconds. If not, it
1155 returns zero.
1156
1157 State changes as a result of a Restart operation are never animated;
1158 the mid-end will handle them internally and never consult this
1159 function at all. State changes as a result of Solve operations are
1160 also not animated by default, although you can change this for a
1161 particular game by setting a flag in \c{flags} (\k{backend-flags}).
1162
1163 The function is also passed a pointer to the local \c{game_ui}. It
1164 may refer to information in here to help with its decision (see
1165 \k{writing-conditional-anim} for an example of this), and/or it may
1166 \e{write} information about the nature of the animation which will
1167 be read later by \cw{redraw()}.
1168
1169 When this function is called, it may rely on \cw{changed_state()}
1170 having been called previously, so if \cw{anim_length()} needs to
1171 refer to information in the \c{game_ui}, then \cw{changed_state()}
1172 is a reliable place to have set that information up.
1173
1174 Move animations do not inhibit further input events. If the user
1175 continues playing before a move animation is complete, the animation
1176 will be abandoned and the display will jump straight to the final
1177 state.
1178
1179 \S{backend-flash-length} \cw{flash_length()}
1180
1181 \c float (*flash_length)(game_state *oldstate, game_state *newstate,
1182 \c                       int dir, game_ui *ui);
1183
1184 This function is called when a move is completed. (\q{Completed}
1185 means that not only has the move been made, but any animation which
1186 accompanied it has finished.) It decides whether the transition from
1187 \c{oldstate} to \c{newstate} merits a \q{flash}.
1188
1189 A flash is much like a move animation, but it is \e{not} interrupted
1190 by further user interface activity; it runs to completion in
1191 parallel with whatever else might be going on on the display. The
1192 only thing which will rush a flash to completion is another flash.
1193
1194 The purpose of flashes is to indicate that the game has been
1195 completed. They were introduced as a separate concept from move
1196 animations because of Net: the habit of most Net players (and
1197 certainly me) is to rotate a tile into place and immediately lock
1198 it, then move on to another tile. When you make your last move, at
1199 the instant the final tile is rotated into place the screen starts
1200 to flash to indicate victory \dash but if you then press the lock
1201 button out of habit, then the move animation is cancelled, and the
1202 victory flash does not complete. (And if you \e{don't} press the
1203 lock button, the completed grid will look untidy because there will
1204 be one unlocked square.) Therefore, I introduced a specific concept
1205 of a \q{flash} which is separate from a move animation and can
1206 proceed in parallel with move animations and any other display
1207 activity, so that the victory flash in Net is not cancelled by that
1208 final locking move.
1209
1210 The input parameters to \cw{flash_length()} are exactly the same as
1211 the ones to \cw{anim_length()}.
1212
1213 Just like \cw{anim_length()}, when this function is called, it may
1214 rely on \cw{changed_state()} having been called previously, so if it
1215 needs to refer to information in the \c{game_ui} then
1216 \cw{changed_state()} is a reliable place to have set that
1217 information up.
1218
1219 (Some games use flashes to indicate defeat as well as victory;
1220 Mines, for example, flashes in a different colour when you tread on
1221 a mine from the colour it uses when you complete the game. In order
1222 to achieve this, its \cw{flash_length()} function has to store a
1223 flag in the \c{game_ui} to indicate which flash type is required.)
1224
1225 \S{backend-redraw} \cw{redraw()}
1226
1227 \c void (*redraw)(drawing *dr, game_drawstate *ds,
1228 \c                game_state *oldstate, game_state *newstate, int dir,
1229 \c                game_ui *ui, float anim_time, float flash_time);
1230
1231 This function is responsible for actually drawing the contents of
1232 the game window, and for redrawing every time the game state or the
1233 \c{game_ui} changes.
1234
1235 The parameter \c{dr} is a drawing object which may be passed to the
1236 drawing API functions (see \k{drawing} for documentation of the
1237 drawing API). This function may not save \c{dr} and use it
1238 elsewhere; it must only use it for calling back to the drawing API
1239 functions within its own lifetime.
1240
1241 \c{ds} is the local \c{game_drawstate}, of course, and \c{ui} is the
1242 local \c{game_ui}.
1243
1244 \c{newstate} is the semantically-current game state, and is always
1245 non-\cw{NULL}. If \c{oldstate} is also non-\cw{NULL}, it means that
1246 a move has recently been made and the game is still in the process
1247 of displaying an animation linking the old and new states; in this
1248 situation, \c{anim_time} will give the length of time (in seconds)
1249 that the animation has already been running. If \c{oldstate} is
1250 \cw{NULL}, then \c{anim_time} is unused (and will hopefully be set
1251 to zero to avoid confusion).
1252
1253 \c{flash_time}, if it is is non-zero, denotes that the game is in
1254 the middle of a flash, and gives the time since the start of the
1255 flash. See \k{backend-flash-length} for general discussion of
1256 flashes.
1257
1258 The very first time this function is called for a new
1259 \c{game_drawstate}, it is expected to redraw the \e{entire} drawing
1260 area. Since this often involves drawing visual furniture which is
1261 never subsequently altered, it is often simplest to arrange this by
1262 having a special \q{first time} flag in the draw state, and
1263 resetting it after the first redraw.
1264
1265 When this function (or any subfunction) calls the drawing API, it is
1266 expected to pass colour indices which were previously defined by the
1267 \cw{colours()} function.
1268
1269 \H{backend-printing} Printing functions
1270
1271 This section discusses the back end functions that deal with
1272 printing puzzles out on paper.
1273
1274 \S{backend-can-print} \c{can_print}
1275
1276 \c int can_print;
1277
1278 This flag is set to \cw{TRUE} if the puzzle is capable of printing
1279 itself on paper. (This makes sense for some puzzles, such as Solo,
1280 which can be filled in with a pencil. Other puzzles, such as
1281 Twiddle, inherently involve moving things around and so would not
1282 make sense to print.)
1283
1284 If this flag is \cw{FALSE}, then the functions \cw{print_size()}
1285 and \cw{print()} will never be called.
1286
1287 \S{backend-can-print-in-colour} \c{can_print_in_colour}
1288
1289 \c int can_print_in_colour;
1290
1291 This flag is set to \cw{TRUE} if the puzzle is capable of printing
1292 itself differently when colour is available. For example, Map can
1293 actually print coloured regions in different \e{colours} rather than
1294 resorting to cross-hatching.
1295
1296 If the \c{can_print} flag is \cw{FALSE}, then this flag will be
1297 ignored.
1298
1299 \S{backend-print-size} \cw{print_size()}
1300
1301 \c void (*print_size)(game_params *params, float *x, float *y);
1302
1303 This function is passed a \c{game_params} structure and a tile size.
1304 It returns, in \c{*x} and \c{*y}, the preferred size in
1305 \e{millimetres} of that puzzle if it were to be printed out on paper.
1306
1307 If the \c{can_print} flag is \cw{FALSE}, this function will never be
1308 called.
1309
1310 \S{backend-print} \cw{print()}
1311
1312 \c void (*print)(drawing *dr, game_state *state, int tilesize);
1313
1314 This function is called when a puzzle is to be printed out on paper.
1315 It should use the drawing API functions (see \k{drawing}) to print
1316 itself.
1317
1318 This function is separate from \cw{redraw()} because it is often
1319 very different:
1320
1321 \b The printing function may not depend on pixel accuracy, since
1322 printer resolution is variable. Draw as if your canvas had infinite
1323 resolution.
1324
1325 \b The printing function sometimes needs to display things in a
1326 completely different style. Net, for example, is very different as
1327 an on-screen puzzle and as a printed one.
1328
1329 \b The printing function is often much simpler since it has no need
1330 to deal with repeated partial redraws.
1331
1332 However, there's no reason the printing and redraw functions can't
1333 share some code if they want to.
1334
1335 When this function (or any subfunction) calls the drawing API, the
1336 colour indices it passes should be colours which have been allocated
1337 by the \cw{print_*_colour()} functions within this execution of
1338 \cw{print()}. This is very different from the fixed small number of
1339 colours used in \cw{redraw()}, because printers do not have a
1340 limitation on the total number of colours that may be used. Some
1341 puzzles' printing functions might wish to allocate only one \q{ink}
1342 colour and use it for all drawing; others might wish to allocate
1343 \e{more} colours than are used on screen.
1344
1345 One possible colour policy worth mentioning specifically is that a
1346 puzzle's printing function might want to allocate the \e{same}
1347 colour indices as are used by the redraw function, so that code
1348 shared between drawing and printing does not have to keep switching
1349 its colour indices. In order to do this, the simplest thing is to
1350 make use of the fact that colour indices returned from
1351 \cw{print_*_colour()} are guaranteed to be in increasing order from
1352 zero. So if you have declared an \c{enum} defining three colours
1353 \cw{COL_BACKGROUND}, \cw{COL_THIS} and \cw{COL_THAT}, you might then
1354 write
1355
1356 \c int c;
1357 \c c = print_mono_colour(dr, 1); assert(c == COL_BACKGROUND);
1358 \c c = print_mono_colour(dr, 0); assert(c == COL_THIS);
1359 \c c = print_mono_colour(dr, 0); assert(c == COL_THAT);
1360
1361 If the \c{can_print} flag is \cw{FALSE}, this function will never be
1362 called.
1363
1364 \H{backend-misc} Miscellaneous
1365
1366 \S{backend-can-format-as-text} \c{can_format_as_text}
1367
1368 \c int can_format_as_text;
1369
1370 This boolean field is \cw{TRUE} if the game supports formatting a
1371 game state as ASCII text (typically ASCII art) for copying to the
1372 clipboard and pasting into other applications. If it is \cw{FALSE},
1373 front ends will not offer the \q{Copy} command at all.
1374
1375 If this field is \cw{FALSE}, the function \cw{text_format()}
1376 (\k{backend-text-format}) is not expected to do anything at all.
1377
1378 \S{backend-text-format} \cw{text_format()}
1379
1380 \c char *(*text_format)(game_state *state);
1381
1382 This function is passed a \c{game_state}, and returns a newly
1383 allocated C string containing an ASCII representation of that game
1384 state. It is used to implement the \q{Copy} operation in many front
1385 ends.
1386
1387 This function should only be called if the back end field
1388 \c{can_format_as_text} (\k{backend-can-format-as-text}) is
1389 \cw{TRUE}.
1390
1391 The returned string may contain line endings (and will probably want
1392 to), using the normal C internal \cq{\\n} convention. For
1393 consistency between puzzles, all multi-line textual puzzle
1394 representations should \e{end} with a newline as well as containing
1395 them internally. (There are currently no puzzles which have a
1396 one-line ASCII representation, so there's no precedent yet for
1397 whether that should come with a newline or not.)
1398
1399 \S{backend-wants-statusbar} \cw{wants_statusbar()}
1400
1401 \c int wants_statusbar;
1402
1403 This boolean field is set to \cw{TRUE} if the puzzle has a use for a
1404 textual status line (to display score, completion status, currently
1405 active tiles, etc).
1406
1407 \S{backend-is-timed} \c{is_timed}
1408
1409 \c int is_timed;
1410
1411 This boolean field is \cw{TRUE} if the puzzle is time-critical. If
1412 so, the mid-end will maintain a game timer while the user plays.
1413
1414 If this field is \cw{FALSE}, then \cw{timing_state()} will never be
1415 called and need not do anything.
1416
1417 \S{backend-timing-state} \cw{timing_state()}
1418
1419 \c int (*timing_state)(game_state *state, game_ui *ui);
1420
1421 This function is passed the current \c{game_state} and the local
1422 \c{game_ui}; it returns \cw{TRUE} if the game timer should currently
1423 be running.
1424
1425 A typical use for the \c{game_ui} in this function is to note when
1426 the game was first completed (by setting a flag in
1427 \cw{changed_state()} \dash see \k{backend-changed-state}), and
1428 freeze the timer thereafter so that the user can undo back through
1429 their solution process without altering their time.
1430
1431 \S{backend-flags} \c{flags}
1432
1433 \c int flags;
1434
1435 This field contains miscellaneous per-backend flags. It consists of
1436 the bitwise OR of some combination of the following:
1437
1438 \dt \cw{BUTTON_BEATS(x,y)}
1439
1440 \dd Given any \cw{x} and \cw{y} from the set (\cw{LEFT_BUTTON},
1441 \cw{MIDDLE_BUTTON}, \cw{RIGHT_BUTTON}), this macro evaluates to a
1442 bit flag which indicates that when buttons \cw{x} and \cw{y} are
1443 both pressed simultaneously, the mid-end should consider \cw{x} to
1444 have priority. (In the absence of any such flags, the mid-end will
1445 always consider the most recently pressed button to have priority.)
1446
1447 \dt \cw{SOLVE_ANIMATES}
1448
1449 \dd This flag indicates that moves generated by \cw{solve()}
1450 (\k{backend-solve}) are candidates for animation just like any other
1451 move. For most games, solve moves should not be animated, so the
1452 mid-end doesn't even bother calling \cw{anim_length()}
1453 (\k{backend-anim-length}), thus saving some special-case code in
1454 each game. On the rare occasion that animated solve moves are
1455 actually required, you can set this flag.
1456
1457 \H{backend-initiative} Things a back end may do on its own initiative
1458
1459 This section describes a couple of things that a back end may choose
1460 to do by calling functions elsewhere in the program, which would not
1461 otherwise be obvious.
1462
1463 \S{backend-newrs} Create a random state
1464
1465 If a back end needs random numbers at some point during normal play,
1466 it can create a fresh \c{random_state} by first calling
1467 \c{get_random_seed} (\k{frontend-get-random-seed}) and then passing
1468 the returned seed data to \cw{random_new()}.
1469
1470 This is likely not to be what you want. If a puzzle needs randomness
1471 in the middle of play, it's likely to be more sensible to store some
1472 sort of random state within the \e{game_state}, so that the random
1473 numbers are tied to the particular game state and hence the player
1474 can't simply keep undoing their move until they get numbers they
1475 like better.
1476
1477 This facility is currently used only in Net, to implement the
1478 \q{jumble} command, which sets every unlocked tile to a new random
1479 orientation. This randomness \e{is} a reasonable use of the feature,
1480 because it's non-adversarial \dash there's no advantage to the user
1481 in getting different random numbers.
1482
1483 \S{backend-supersede} Supersede its own game description
1484
1485 In response to a move, a back end is (reluctantly) permitted to call
1486 \cw{midend_supersede_game_desc()}:
1487
1488 \c void midend_supersede_game_desc(midend *me,
1489 \c                                 char *desc, char *privdesc);
1490
1491 When the user selects \q{New Game}, the mid-end calls
1492 \cw{new_desc()} (\k{backend-new-desc}) to get a new game
1493 description, and (as well as using that to generate an initial game
1494 state) stores it for the save file and for telling to the user. The
1495 function above overwrites that game description, and also splits it
1496 in two. \c{desc} becomes the new game description which is provided
1497 to the user on request, and is also the one used to construct a new
1498 initial game state if the user selects \q{Restart}. \c{privdesc} is
1499 a \q{private} game description, used to reconstruct the game's
1500 initial state when reloading.
1501
1502 The distinction between the two, as well as the need for this
1503 function at all, comes from Mines. Mines begins with a blank grid
1504 and no idea of where the mines actually are; \cw{new_desc()} does
1505 almost no work in interactive mode, and simply returns a string
1506 encoding the \c{random_state}. When the user first clicks to open a
1507 tile, \e{then} Mines generates the mine positions, in such a way
1508 that the game is soluble from that starting point. Then it uses this
1509 function to supersede the random-state game description with a
1510 proper one. But it needs two: one containing the initial click
1511 location (because that's what you want to happen if you restart the
1512 game, and also what you want to send to a friend so that they play
1513 \e{the same game} as you), and one without the initial click
1514 location (because when you save and reload the game, you expect to
1515 see the same blank initial state as you had before saving).
1516
1517 I should stress again that this function is a horrid hack. Nobody
1518 should use it if they're not Mines; if you think you need to use it,
1519 think again repeatedly in the hope of finding a better way to do
1520 whatever it was you needed to do.
1521
1522 \C{drawing} The drawing API
1523
1524 The back end function \cw{redraw()} (\k{backend-redraw}) is required
1525 to draw the puzzle's graphics on the window's drawing area, or on
1526 paper if the puzzle is printable. To do this portably, it is
1527 provided with a drawing API allowing it to talk directly to the
1528 front end. In this chapter I document that API, both for the benefit
1529 of back end authors trying to use it and for front end authors
1530 trying to implement it.
1531
1532 The drawing API as seen by the back end is a collection of global
1533 functions, each of which takes a pointer to a \c{drawing} structure
1534 (a \q{drawing object}). These objects are supplied as parameters to
1535 the back end's \cw{redraw()} and \cw{print()} functions.
1536
1537 In fact these global functions are not implemented directly by the
1538 front end; instead, they are implemented centrally in \c{drawing.c}
1539 and form a small piece of middleware. The drawing API as supplied by
1540 the front end is a structure containing a set of function pointers,
1541 plus a \cq{void *} handle which is passed to each of those
1542 functions. This enables a single front end to switch between
1543 multiple implementations of the drawing API if necessary. For
1544 example, the Windows API supplies a printing mechanism integrated
1545 into the same GDI which deals with drawing in windows, and therefore
1546 the same API implementation can handle both drawing and printing;
1547 but on Unix, the most common way for applications to print is by
1548 producing PostScript output directly, and although it would be
1549 \e{possible} to write a single (say) \cw{draw_rect()} function which
1550 checked a global flag to decide whether to do GTK drawing operations
1551 or output PostScript to a file, it's much nicer to have two separate
1552 functions and switch between them as appropriate.
1553
1554 When drawing, the puzzle window is indexed by pixel coordinates,
1555 with the top left pixel defined as \cw{(0,0)} and the bottom right
1556 pixel \cw{(w-1,h-1)}, where \c{w} and \c{h} are the width and height
1557 values returned by the back end function \cw{compute_size()}
1558 (\k{backend-compute-size}).
1559
1560 When printing, the puzzle's print area is indexed in exactly the
1561 same way (with an arbitrary tile size provided by the printing
1562 module \c{printing.c}), to facilitate sharing of code between the
1563 drawing and printing routines. However, when printing, puzzles may
1564 no longer assume that the coordinate unit has any relationship to a
1565 pixel; the printer's actual resolution might very well not even be
1566 known at print time, so the coordinate unit might be smaller or
1567 larger than a pixel. Puzzles' print functions should restrict
1568 themselves to drawing geometric shapes rather than fiddly pixel
1569 manipulation.
1570
1571 \e{Puzzles' redraw functions may assume that the surface they draw
1572 on is persistent}. It is the responsibility of every front end to
1573 preserve the puzzle's window contents in the face of GUI window
1574 expose issues and similar. It is not permissible to request the back
1575 end redraw any part of a window that it has already drawn, unless
1576 something has actually changed as a result of making moves in the
1577 puzzle.
1578
1579 Most front ends accomplish this by having the drawing routines draw
1580 on a stored bitmap rather than directly on the window, and copying
1581 the bitmap to the window every time a part of the window needs to be
1582 redrawn. Therefore, it is vitally important that whenever the back
1583 end does any drawing it informs the front end of which parts of the
1584 window it has accessed, and hence which parts need repainting. This
1585 is done by calling \cw{draw_update()} (\k{drawing-draw-update}).
1586
1587 In the following sections I first discuss the drawing API as seen by
1588 the back end, and then the \e{almost} identical function-pointer
1589 form seen by the front end.
1590
1591 \H{drawing-backend} Drawing API as seen by the back end
1592
1593 This section documents the back-end drawing API, in the form of
1594 functions which take a \c{drawing} object as an argument.
1595
1596 \S{drawing-draw-rect} \cw{draw_rect()}
1597
1598 \c void draw_rect(drawing *dr, int x, int y, int w, int h,
1599 \c                int colour);
1600
1601 Draws a filled rectangle in the puzzle window.
1602
1603 \c{x} and \c{y} give the coordinates of the top left pixel of the
1604 rectangle. \c{w} and \c{h} give its width and height. Thus, the
1605 horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
1606 inclusive, and the vertical extent from \c{y} to \c{y+h-1}
1607 inclusive.
1608
1609 \c{colour} is an integer index into the colours array returned by
1610 the back end function \cw{colours()} (\k{backend-colours}).
1611
1612 There is no separate pixel-plotting function. If you want to plot a
1613 single pixel, the approved method is to use \cw{draw_rect()} with
1614 width and height set to 1.
1615
1616 Unlike many of the other drawing functions, this function is
1617 guaranteed to be pixel-perfect: the rectangle will be sharply
1618 defined and not anti-aliased or anything like that.
1619
1620 This function may be used for both drawing and printing.
1621
1622 \S{drawing-draw-rect-outline} \cw{draw_rect_outline()}
1623
1624 \c void draw_rect_outline(drawing *dr, int x, int y, int w, int h,
1625 \c                        int colour);
1626
1627 Draws an outline rectangle in the puzzle window.
1628
1629 \c{x} and \c{y} give the coordinates of the top left pixel of the
1630 rectangle. \c{w} and \c{h} give its width and height. Thus, the
1631 horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
1632 inclusive, and the vertical extent from \c{y} to \c{y+h-1}
1633 inclusive.
1634
1635 \c{colour} is an integer index into the colours array returned by
1636 the back end function \cw{colours()} (\k{backend-colours}).
1637
1638 From a back end perspective, this function may be considered to be
1639 part of the drawing API. However, front ends are not required to
1640 implement it, since it is actually implemented centrally (in
1641 \cw{misc.c}) as a wrapper on \cw{draw_polygon()}.
1642
1643 This function may be used for both drawing and printing.
1644
1645 \S{drawing-draw-line} \cw{draw_line()}
1646
1647 \c void draw_line(drawing *dr, int x1, int y1, int x2, int y2,
1648 \c                int colour);
1649
1650 Draws a straight line in the puzzle window.
1651
1652 \c{x1} and \c{y1} give the coordinates of one end of the line.
1653 \c{x2} and \c{y2} give the coordinates of the other end. The line
1654 drawn includes both those points.
1655
1656 \c{colour} is an integer index into the colours array returned by
1657 the back end function \cw{colours()} (\k{backend-colours}).
1658
1659 Some platforms may perform anti-aliasing on this function.
1660 Therefore, do not assume that you can erase a line by drawing the
1661 same line over it in the background colour; anti-aliasing might
1662 lead to perceptible ghost artefacts around the vanished line.
1663
1664 This function may be used for both drawing and printing.
1665
1666 \S{drawing-draw-polygon} \cw{draw_polygon()}
1667
1668 \c void draw_polygon(drawing *dr, int *coords, int npoints,
1669 \c                   int fillcolour, int outlinecolour);
1670
1671 Draws an outlined or filled polygon in the puzzle window.
1672
1673 \c{coords} is an array of \cw{(2*npoints)} integers, containing the
1674 \c{x} and \c{y} coordinates of \c{npoints} vertices.
1675
1676 \c{fillcolour} and \c{outlinecolour} are integer indices into the
1677 colours array returned by the back end function \cw{colours()}
1678 (\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
1679 indicate that the polygon should be outlined only.
1680
1681 The polygon defined by the specified list of vertices is first
1682 filled in \c{fillcolour}, if specified, and then outlined in
1683 \c{outlinecolour}.
1684
1685 \c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
1686 (and front ends are permitted to enforce this by assertion). This is
1687 because different platforms disagree on whether a filled polygon
1688 should include its boundary line or not, so drawing \e{only} a
1689 filled polygon would have non-portable effects. If you want your
1690 filled polygon not to have a visible outline, you must set
1691 \c{outlinecolour} to the same as \c{fillcolour}.
1692
1693 Some platforms may perform anti-aliasing on this function.
1694 Therefore, do not assume that you can erase a polygon by drawing the
1695 same polygon over it in the background colour. Also, be prepared for
1696 the polygon to extend a pixel beyond its obvious bounding box as a
1697 result of this; if you really need it not to do this to avoid
1698 interfering with other delicate graphics, you should probably use
1699 \cw{clip()} (\k{drawing-clip}).
1700
1701 This function may be used for both drawing and printing.
1702
1703 \S{drawing-draw-circle} \cw{draw_circle()}
1704
1705 \c void draw_circle(drawing *dr, int cx, int cy, int radius,
1706 \c                  int fillcolour, int outlinecolour);
1707
1708 Draws an outlined or filled circle in the puzzle window.
1709
1710 \c{cx} and \c{cy} give the coordinates of the centre of the circle.
1711 \c{radius} gives its radius. The total horizontal pixel extent of
1712 the circle is from \c{cx-radius+1} to \c{cx+radius-1} inclusive, and
1713 the vertical extent similarly around \c{cy}.
1714
1715 \c{fillcolour} and \c{outlinecolour} are integer indices into the
1716 colours array returned by the back end function \cw{colours()}
1717 (\k{backend-colours}). \c{fillcolour} may also be \cw{-1} to
1718 indicate that the circle should be outlined only.
1719
1720 The circle is first filled in \c{fillcolour}, if specified, and then
1721 outlined in \c{outlinecolour}.
1722
1723 \c{outlinecolour} may \e{not} be \cw{-1}; it must be a valid colour
1724 (and front ends are permitted to enforce this by assertion). This is
1725 because different platforms disagree on whether a filled circle
1726 should include its boundary line or not, so drawing \e{only} a
1727 filled circle would have non-portable effects. If you want your
1728 filled circle not to have a visible outline, you must set
1729 \c{outlinecolour} to the same as \c{fillcolour}.
1730
1731 Some platforms may perform anti-aliasing on this function.
1732 Therefore, do not assume that you can erase a circle by drawing the
1733 same circle over it in the background colour. Also, be prepared for
1734 the circle to extend a pixel beyond its obvious bounding box as a
1735 result of this; if you really need it not to do this to avoid
1736 interfering with other delicate graphics, you should probably use
1737 \cw{clip()} (\k{drawing-clip}).
1738
1739 This function may be used for both drawing and printing.
1740
1741 \S{drawing-draw-text} \cw{draw_text()}
1742
1743 \c void draw_text(drawing *dr, int x, int y, int fonttype,
1744 \c                int fontsize, int align, int colour, char *text);
1745
1746 Draws text in the puzzle window.
1747
1748 \c{x} and \c{y} give the coordinates of a point. The relation of
1749 this point to the location of the text is specified by \c{align},
1750 which is a bitwise OR of horizontal and vertical alignment flags:
1751
1752 \dt \cw{ALIGN_VNORMAL}
1753
1754 \dd Indicates that \c{y} is aligned with the baseline of the text.
1755
1756 \dt \cw{ALIGN_VCENTRE}
1757
1758 \dd Indicates that \c{y} is aligned with the vertical centre of the
1759 text. (In fact, it's aligned with the vertical centre of normal
1760 \e{capitalised} text: displaying two pieces of text with
1761 \cw{ALIGN_VCENTRE} at the same \cw{y}-coordinate will cause their
1762 baselines to be aligned with one another, even if one is an ascender
1763 and the other a descender.)
1764
1765 \dt \cw{ALIGN_HLEFT}
1766
1767 \dd Indicates that \c{x} is aligned with the left-hand end of the
1768 text.
1769
1770 \dt \cw{ALIGN_HCENTRE}
1771
1772 \dd Indicates that \c{x} is aligned with the horizontal centre of
1773 the text.
1774
1775 \dt \cw{ALIGN_HRIGHT}
1776
1777 \dd Indicates that \c{x} is aligned with the right-hand end of the
1778 text.
1779
1780 \c{fonttype} is either \cw{FONT_FIXED} or \cw{FONT_VARIABLE}, for a
1781 monospaced or proportional font respectively. (No more detail than
1782 that may be specified; it would only lead to portability issues
1783 between different platforms.)
1784
1785 \c{fontsize} is the desired size, in pixels, of the text. This size
1786 corresponds to the overall point size of the text, not to any
1787 internal dimension such as the cap-height.
1788
1789 \c{colour} is an integer index into the colours array returned by
1790 the back end function \cw{colours()} (\k{backend-colours}).
1791
1792 This function may be used for both drawing and printing.
1793
1794 \S{drawing-clip} \cw{clip()}
1795
1796 \c void clip(drawing *dr, int x, int y, int w, int h);
1797
1798 Establishes a clipping rectangle in the puzzle window.
1799
1800 \c{x} and \c{y} give the coordinates of the top left pixel of the
1801 clipping rectangle. \c{w} and \c{h} give its width and height. Thus,
1802 the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
1803 inclusive, and the vertical extent from \c{y} to \c{y+h-1}
1804 inclusive. (These are exactly the same semantics as
1805 \cw{draw_rect()}.)
1806
1807 After this call, no drawing operation will affect anything outside
1808 the specified rectangle. The effect can be reversed by calling
1809 \cw{unclip()} (\k{drawing-unclip}).
1810
1811 Back ends should not assume that a clipping rectangle will be
1812 automatically cleared up by the front end if it's left lying around;
1813 that might work on current front ends, but shouldn't be relied upon.
1814 Always explicitly call \cw{unclip()}.
1815
1816 This function may be used for both drawing and printing.
1817
1818 \S{drawing-unclip} \cw{unclip()}
1819
1820 \c void unclip(drawing *dr);
1821
1822 Reverts the effect of a previous call to \cw{clip()}. After this
1823 call, all drawing operations will be able to affect the entire
1824 puzzle window again.
1825
1826 This function may be used for both drawing and printing.
1827
1828 \S{drawing-draw-update} \cw{draw_update()}
1829
1830 \c void draw_update(drawing *dr, int x, int y, int w, int h);
1831
1832 Informs the front end that a rectangular portion of the puzzle
1833 window has been drawn on and needs to be updated.
1834
1835 \c{x} and \c{y} give the coordinates of the top left pixel of the
1836 update rectangle. \c{w} and \c{h} give its width and height. Thus,
1837 the horizontal extent of the rectangle runs from \c{x} to \c{x+w-1}
1838 inclusive, and the vertical extent from \c{y} to \c{y+h-1}
1839 inclusive. (These are exactly the same semantics as
1840 \cw{draw_rect()}.)
1841
1842 The back end redraw function \e{must} call this function to report
1843 any changes it has made to the window. Otherwise, those changes may
1844 not become immediately visible, and may then appear at an
1845 unpredictable subsequent time such as the next time the window is
1846 covered and re-exposed.
1847
1848 This function is only important when drawing. It may be called when
1849 printing as well, but doing so is not compulsory, and has no effect.
1850 (So if you have a shared piece of code between the drawing and
1851 printing routines, that code may safely call \cw{draw_update()}.)
1852
1853 \S{drawing-status-bar} \cw{status_bar()}
1854
1855 \c void status_bar(drawing *dr, char *text);
1856
1857 Sets the text in the game's status bar to \c{text}. The text is copied
1858 from the supplied buffer, so the caller is free to deallocate or
1859 modify the buffer after use.
1860
1861 (This function is not exactly a \e{drawing} function, but it shares
1862 with the drawing API the property that it may only be called from
1863 within the back end redraw function, so this is as good a place as
1864 any to document it.)
1865
1866 This function is for drawing only; it must never be called during
1867 printing.
1868
1869 \S{drawing-blitter} Blitter functions
1870
1871 This section describes a group of related functions which save and
1872 restore a section of the puzzle window. This is most commonly used
1873 to implement user interfaces involving dragging a puzzle element
1874 around the window: at the end of each call to \cw{redraw()}, if an
1875 object is currently being dragged, the back end saves the window
1876 contents under that location and then draws the dragged object, and
1877 at the start of the next \cw{redraw()} the first thing it does is to
1878 restore the background.
1879
1880 The front end defines an opaque type called a \c{blitter}, which is
1881 capable of storing a rectangular area of a specified size.
1882
1883 Blitter functions are for drawing only; they must never be called
1884 during printing.
1885
1886 \S2{drawing-blitter-new} \cw{blitter_new()}
1887
1888 \c blitter *blitter_new(drawing *dr, int w, int h);
1889
1890 Creates a new blitter object which stores a rectangle of size \c{w}
1891 by \c{h} pixels. Returns a pointer to the blitter object.
1892
1893 Blitter objects are best stored in the \c{game_drawstate}. A good
1894 time to create them is in the \cw{set_size()} function
1895 (\k{backend-set-size}), since it is at this point that you first
1896 know how big a rectangle they will need to save.
1897
1898 \S2{drawing-blitter-free} \cw{blitter_free()}
1899
1900 \c void blitter_free(drawing *dr, blitter *bl);
1901
1902 Disposes of a blitter object. Best called in \cw{free_drawstate()}.
1903 (However, check that the blitter object is not \cw{NULL} before
1904 attempting to free it; it is possible that a draw state might be
1905 created and freed without ever having \cw{set_size()} called on it
1906 in between.)
1907
1908 \S2{drawing-blitter-save} \cw{blitter_save()}
1909
1910 \c void blitter_save(drawing *dr, blitter *bl, int x, int y);
1911
1912 This is a true drawing API function, in that it may only be called
1913 from within the game redraw routine. It saves a rectangular portion
1914 of the puzzle window into the specified blitter object.
1915
1916 \c{x} and \c{y} give the coordinates of the top left corner of the
1917 saved rectangle. The rectangle's width and height are the ones
1918 specified when the blitter object was created.
1919
1920 This function is required to cope and do the right thing if \c{x}
1921 and \c{y} are out of range. (The right thing probably means saving
1922 whatever part of the blitter rectangle overlaps with the visible
1923 area of the puzzle window.)
1924
1925 \S2{drawing-blitter-load} \cw{blitter_load()}
1926
1927 \c void blitter_load(drawing *dr, blitter *bl, int x, int y);
1928
1929 This is a true drawing API function, in that it may only be called
1930 from within the game redraw routine. It restores a rectangular
1931 portion of the puzzle window from the specified blitter object.
1932
1933 \c{x} and \c{y} give the coordinates of the top left corner of the
1934 rectangle to be restored. The rectangle's width and height are the
1935 ones specified when the blitter object was created.
1936
1937 Alternatively, you can specify both \c{x} and \c{y} as the special
1938 value \cw{BLITTER_FROMSAVED}, in which case the rectangle will be
1939 restored to exactly where it was saved from. (This is probably what
1940 you want to do almost all the time, if you're using blitters to
1941 implement draggable puzzle elements.)
1942
1943 This function is required to cope and do the right thing if \c{x}
1944 and \c{y} (or the equivalent ones saved in the blitter) are out of
1945 range. (The right thing probably means restoring whatever part of
1946 the blitter rectangle overlaps with the visible area of the puzzle
1947 window.)
1948
1949 If this function is called on a blitter which had previously been
1950 saved from a partially out-of-range rectangle, then the parts of the
1951 saved bitmap which were not visible at save time are undefined. If
1952 the blitter is restored to a different position so as to make those
1953 parts visible, the effect on the drawing area is undefined.
1954
1955 \S{print-mono-colour} \cw{print_mono_colour()}
1956
1957 \c int print_mono_colour(drawing *dr, int grey);
1958
1959 This function allocates a colour index for a simple monochrome
1960 colour during printing.
1961
1962 \c{grey} must be 0 or 1. If \c{grey} is 0, the colour returned is
1963 black; if \c{grey} is 1, the colour is white.
1964
1965 \S{print-grey-colour} \cw{print_grey_colour()}
1966
1967 \c int print_grey_colour(drawing *dr, int hatch, float grey);
1968
1969 This function allocates a colour index for a grey-scale colour
1970 during printing.
1971
1972 \c{grey} may be any number between 0 (black) and 1 (white); for
1973 example, 0.5 indicates a medium grey.
1974
1975 If printing in black and white only, the \c{grey} value will not be
1976 used; instead, regions shaded in this colour will be hatched with
1977 parallel lines. The \c{hatch} parameter defines what type of
1978 hatching should be used in place of this colour:
1979
1980 \dt \cw{HATCH_SOLID}
1981
1982 \dd In black and white, this colour will be replaced by solid black.
1983
1984 \dt \cw{HATCH_CLEAR}
1985
1986 \dd In black and white, this colour will be replaced by solid white.
1987
1988 \dt \cw{HATCH_SLASH}
1989
1990 \dd This colour will be hatched by lines slanting to the right at 45
1991 degrees. 
1992
1993 \dt \cw{HATCH_BACKSLASH}
1994
1995 \dd This colour will be hatched by lines slanting to the left at 45
1996 degrees.
1997
1998 \dt \cw{HATCH_HORIZ}
1999
2000 \dd This colour will be hatched by horizontal lines.
2001
2002 \dt \cw{HATCH_VERT}
2003
2004 \dd This colour will be hatched by vertical lines.
2005
2006 \dt \cw{HATCH_PLUS}
2007
2008 \dd This colour will be hatched by criss-crossing horizontal and
2009 vertical lines.
2010
2011 \dt \cw{HATCH_X}
2012
2013 \dd This colour will be hatched by criss-crossing diagonal lines.
2014
2015 Colours defined to use hatching may not be used for drawing lines;
2016 they may only be used for filling areas. That is, they may be used
2017 as the \c{fillcolour} parameter to \cw{draw_circle()} and
2018 \cw{draw_polygon()}, and as the colour parameter to
2019 \cw{draw_rect()}, but may not be used as the \c{outlinecolour}
2020 parameter to \cw{draw_circle()} or \cw{draw_polygon()}, or with
2021 \cw{draw_line()}.
2022
2023 \S{print-rgb-colour} \cw{print_rgb_colour()}
2024
2025 \c int print_rgb_colour(drawing *dr, int hatch,
2026 \c                      float r, float g, float b);
2027
2028 This function allocates a colour index for a fully specified RGB
2029 colour during printing.
2030
2031 \c{r}, \c{g} and \c{b} may each be anywhere in the range from 0 to 1.
2032
2033 If printing in black and white only, these values will not be used;
2034 instead, regions shaded in this colour will be hatched with parallel
2035 lines. The \c{hatch} parameter defines what type of hatching should
2036 be used in place of this colour; see \k{print-grey-colour} for its
2037 definition.
2038
2039 \S{print-line-width} \cw{print_line_width()}
2040
2041 \c void print_line_width(drawing *dr, int width);
2042
2043 This function is called to set the thickness of lines drawn during
2044 printing. It is meaningless in drawing: all lines drawn by
2045 \cw{draw_line()}, \cw{draw_circle} and \cw{draw_polygon()} are one
2046 pixel in thickness. However, in printing there is no clear
2047 definition of a pixel and so line widths must be explicitly
2048 specified.
2049
2050 The line width is specified in the usual coordinate system. Note,
2051 however, that it is a hint only: the central printing system may
2052 choose to vary line thicknesses at user request or due to printer
2053 capabilities.
2054
2055 \H{drawing-frontend} The drawing API as implemented by the front end
2056
2057 This section describes the drawing API in the function-pointer form
2058 in which it is implemented by a front end.
2059
2060 (It isn't only platform-specific front ends which implement this
2061 API; the platform-independent module \c{ps.c} also provides an
2062 implementation of it which outputs PostScript. Thus, any platform
2063 which wants to do PS printing can do so with minimum fuss.)
2064
2065 The following entries all describe function pointer fields in a
2066 structure called \c{drawing_api}. Each of the functions takes a
2067 \cq{void *} context pointer, which it should internally cast back to
2068 a more useful type. Thus, a drawing \e{object} (\c{drawing *)}
2069 suitable for passing to the back end redraw or printing functions
2070 is constructed by passing a \c{drawing_api} and a \cq{void *} to the
2071 function \cw{drawing_init()} (see \k{drawing-init}).
2072
2073 \S{drawingapi-draw-text} \cw{draw_text()}
2074
2075 \c void (*draw_text)(void *handle, int x, int y, int fonttype,
2076 \c                   int fontsize, int align, int colour, char *text);
2077
2078 This function behaves exactly like the back end \cw{draw_text()}
2079 function; see \k{drawing-draw-text}.
2080
2081 \S{drawingapi-draw-rect} \cw{draw_rect()}
2082
2083 \c void (*draw_rect)(void *handle, int x, int y, int w, int h,
2084 \c                   int colour);
2085
2086 This function behaves exactly like the back end \cw{draw_rect()}
2087 function; see \k{drawing-draw-rect}.
2088
2089 \S{drawingapi-draw-line} \cw{draw_line()}
2090
2091 \c void (*draw_line)(void *handle, int x1, int y1, int x2, int y2,
2092 \c                   int colour);
2093
2094 This function behaves exactly like the back end \cw{draw_line()}
2095 function; see \k{drawing-draw-line}.
2096
2097 \S{drawingapi-draw-polygon} \cw{draw_polygon()}
2098
2099 \c void (*draw_polygon)(void *handle, int *coords, int npoints,
2100 \c                      int fillcolour, int outlinecolour);
2101
2102 This function behaves exactly like the back end \cw{draw_polygon()}
2103 function; see \k{drawing-draw-polygon}.
2104
2105 \S{drawingapi-draw-circle} \cw{draw_circle()}
2106
2107 \c void (*draw_circle)(void *handle, int cx, int cy, int radius,
2108 \c                     int fillcolour, int outlinecolour);
2109
2110 This function behaves exactly like the back end \cw{draw_circle()}
2111 function; see \k{drawing-draw-circle}.
2112
2113 \S{drawingapi-draw-update} \cw{draw_update()}
2114
2115 \c void (*draw_update)(void *handle, int x, int y, int w, int h);
2116
2117 This function behaves exactly like the back end \cw{draw_text()}
2118 function; see \k{drawing-draw-text}.
2119
2120 An implementation of this API which only supports printing is
2121 permitted to define this function pointer to be \cw{NULL} rather
2122 than bothering to define an empty function. The middleware in
2123 \cw{drawing.c} will notice and avoid calling it.
2124
2125 \S{drawingapi-clip} \cw{clip()}
2126
2127 \c void (*clip)(void *handle, int x, int y, int w, int h);
2128
2129 This function behaves exactly like the back end \cw{clip()}
2130 function; see \k{drawing-clip}.
2131
2132 \S{drawingapi-unclip} \cw{unclip()}
2133
2134 \c void (*unclip)(void *handle);
2135
2136 This function behaves exactly like the back end \cw{unclip()}
2137 function; see \k{drawing-unclip}.
2138
2139 \S{drawingapi-start-draw} \cw{start_draw()}
2140
2141 \c void (*start_draw)(void *handle);
2142
2143 This function is called at the start of drawing. It allows the front
2144 end to initialise any temporary data required to draw with, such as
2145 device contexts.
2146
2147 Implementations of this API which do not provide drawing services
2148 may define this function pointer to be \cw{NULL}; it will never be
2149 called unless drawing is attempted.
2150
2151 \S{drawingapi-end-draw} \cw{end_draw()}
2152
2153 \c void (*end_draw)(void *handle);
2154
2155 This function is called at the end of drawing. It allows the front
2156 end to do cleanup tasks such as deallocating device contexts and
2157 scheduling appropriate GUI redraw events.
2158
2159 Implementations of this API which do not provide drawing services
2160 may define this function pointer to be \cw{NULL}; it will never be
2161 called unless drawing is attempted.
2162
2163 \S{drawingapi-status-bar} \cw{status_bar()}
2164
2165 \c void (*status_bar)(void *handle, char *text);
2166
2167 This function behaves exactly like the back end \cw{status_bar()}
2168 function; see \k{drawing-status-bar}.
2169
2170 Front ends implementing this function should not use the provided
2171 text directly; they should call \cw{midend_rewrite_statusbar()}
2172 (\k{midend-rewrite-statusbar}) to process it first.
2173
2174 In a game which has a timer, this function is likely to be called
2175 every time the timer goes off, i.e. many times a second. It is
2176 therefore likely to be common that this function is called with
2177 precisely the same text as the last time it was called. Front ends
2178 may well wish to detect this common case and avoid bothering to do
2179 anything. If they do, however, they \e{must} perform this check on
2180 the value \e{returned} from \cw{midend_rewrite_statusbar()}, rather
2181 than the value passed in to it (because the mid-end will frequently
2182 update the status-bar timer without the back end's intervention).
2183
2184 Implementations of this API which do not provide drawing services
2185 may define this function pointer to be \cw{NULL}; it will never be
2186 called unless drawing is attempted.
2187
2188 \S{drawingapi-blitter-new} \cw{blitter_new()}
2189
2190 \c blitter *(*blitter_new)(void *handle, int w, int h);
2191
2192 This function behaves exactly like the back end \cw{blitter_new()}
2193 function; see \k{drawing-blitter-new}.
2194
2195 Implementations of this API which do not provide drawing services
2196 may define this function pointer to be \cw{NULL}; it will never be
2197 called unless drawing is attempted.
2198
2199 \S{drawingapi-blitter-free} \cw{blitter_free()}
2200
2201 \c void (*blitter_free)(void *handle, blitter *bl);
2202
2203 This function behaves exactly like the back end \cw{blitter_free()}
2204 function; see \k{drawing-blitter-free}.
2205
2206 Implementations of this API which do not provide drawing services
2207 may define this function pointer to be \cw{NULL}; it will never be
2208 called unless drawing is attempted.
2209
2210 \S{drawingapi-blitter-save} \cw{blitter_save()}
2211
2212 \c void (*blitter_save)(void *handle, blitter *bl, int x, int y);
2213
2214 This function behaves exactly like the back end \cw{blitter_save()}
2215 function; see \k{drawing-blitter-save}.
2216
2217 Implementations of this API which do not provide drawing services
2218 may define this function pointer to be \cw{NULL}; it will never be
2219 called unless drawing is attempted.
2220
2221 \S{drawingapi-blitter-load} \cw{blitter_load()}
2222
2223 \c void (*blitter_load)(void *handle, blitter *bl, int x, int y);
2224
2225 This function behaves exactly like the back end \cw{blitter_load()}
2226 function; see \k{drawing-blitter-load}.
2227
2228 Implementations of this API which do not provide drawing services
2229 may define this function pointer to be \cw{NULL}; it will never be
2230 called unless drawing is attempted.
2231
2232 \S{drawingapi-begin-doc} \cw{begin_doc()}
2233
2234 \c void (*begin_doc)(void *handle, int pages);
2235
2236 This function is called at the beginning of a printing run. It gives
2237 the front end an opportunity to initialise any required printing
2238 subsystem. It also provides the number of pages in advance.
2239
2240 Implementations of this API which do not provide printing services
2241 may define this function pointer to be \cw{NULL}; it will never be
2242 called unless printing is attempted.
2243
2244 \S{drawingapi-begin-page} \cw{begin_page()}
2245
2246 \c void (*begin_page)(void *handle, int number);
2247
2248 This function is called during printing, at the beginning of each
2249 page. It gives the page number (numbered from 1 rather than 0, so
2250 suitable for use in user-visible contexts).
2251
2252 Implementations of this API which do not provide printing services
2253 may define this function pointer to be \cw{NULL}; it will never be
2254 called unless printing is attempted.
2255
2256 \S{drawingapi-begin-puzzle} \cw{begin_puzzle()}
2257
2258 \c void (*begin_puzzle)(void *handle, float xm, float xc,
2259 \c                      float ym, float yc, int pw, int ph, float wmm);
2260
2261 This function is called during printing, just before printing a
2262 single puzzle on a page. It specifies the size and location of the
2263 puzzle on the page.
2264
2265 \c{xm} and \c{xc} specify the horizontal position of the puzzle on
2266 the page, as a linear function of the page width. The front end is
2267 expected to multiply the page width by \c{xm}, add \c{xc} (measured
2268 in millimetres), and use the resulting x-coordinate as the left edge
2269 of the puzzle.
2270
2271 Similarly, \c{ym} and \c{yc} specify the vertical position of the
2272 puzzle as a function of the page height: the page height times
2273 \c{xm}, plus \c{xc} millimetres, equals the desired distance from
2274 the top of the page to the top of the puzzle.
2275
2276 (This unwieldy mechanism is required because not all printing
2277 systems can communicate the page size back to the software. The
2278 PostScript back end, for example, writes out PS which determines the
2279 page size at print time by means of calling \cq{clippath}, and
2280 centres the puzzles within that. Thus, exactly the same PS file
2281 works on A4 or on US Letter paper without needing local
2282 configuration, which simplifies matters.)
2283
2284 \cw{pw} and \cw{ph} give the size of the puzzle in drawing API
2285 coordinates. The printing system will subsequently call the puzzle's
2286 own print function, which will in turn call drawing API functions in
2287 the expectation that an area \cw{pw} by \cw{ph} units is available
2288 to draw the puzzle on.
2289
2290 Finally, \cw{wmm} gives the desired width of the puzzle in
2291 millimetres. (The aspect ratio is expected to be preserved, so if
2292 the desired puzzle height is also needed then it can be computed as
2293 \cw{wmm*ph/pw}.)
2294
2295 Implementations of this API which do not provide printing services
2296 may define this function pointer to be \cw{NULL}; it will never be
2297 called unless printing is attempted.
2298
2299 \S{drawingapi-end-puzzle} \cw{end_puzzle()}
2300
2301 \c void (*end_puzzle)(void *handle);
2302
2303 This function is called after the printing of a specific puzzle is
2304 complete.
2305
2306 Implementations of this API which do not provide printing services
2307 may define this function pointer to be \cw{NULL}; it will never be
2308 called unless printing is attempted.
2309
2310 \S{drawingapi-end-page} \cw{end_page()}
2311
2312 \c void (*end_page)(void *handle, int number);
2313
2314 This function is called after the printing of a page is finished.
2315
2316 Implementations of this API which do not provide printing services
2317 may define this function pointer to be \cw{NULL}; it will never be
2318 called unless printing is attempted.
2319
2320 \S{drawingapi-end-doc} \cw{end_doc()}
2321
2322 \c void (*end_doc)(void *handle);
2323
2324 This function is called after the printing of the entire document is
2325 finished. This is the moment to close files, send things to the
2326 print spooler, or whatever the local convention is.
2327
2328 Implementations of this API which do not provide printing services
2329 may define this function pointer to be \cw{NULL}; it will never be
2330 called unless printing is attempted.
2331
2332 \S{drawingapi-line-width} \cw{line_width()}
2333
2334 \c void (*line_width)(void *handle, float width);
2335
2336 This function is called to set the line thickness, during printing
2337 only. Note that the width is a \cw{float} here, where it was an
2338 \cw{int} as seen by the back end. This is because \cw{drawing.c} may
2339 have scaled it on the way past.
2340
2341 However, the width is still specified in the same coordinate system
2342 as the rest of the drawing.
2343
2344 Implementations of this API which do not provide printing services
2345 may define this function pointer to be \cw{NULL}; it will never be
2346 called unless printing is attempted.
2347
2348 \H{drawingapi-frontend} The drawing API as called by the front end
2349
2350 There are a small number of functions provided in \cw{drawing.c}
2351 which the front end needs to \e{call}, rather than helping to
2352 implement. They are described in this section.
2353
2354 \S{drawing-init} \cw{drawing_init()}
2355
2356 \c drawing *drawing_init(const drawing_api *api, void *handle);
2357
2358 This function creates a drawing object. It is passed a
2359 \c{drawing_api}, which is a structure containing nothing but
2360 function pointers; and also a \cq{void *} handle. The handle is
2361 passed back to each function pointer when it is called.
2362
2363 \S{drawing-free} \cw{drawing_free()}
2364
2365 \c void drawing_free(drawing *dr);
2366
2367 This function frees a drawing object. Note that the \cq{void *}
2368 handle is not freed; if that needs cleaning up it must be done by
2369 the front end.
2370
2371 \S{drawing-print-get-colour} \cw{print_get_colour()}
2372
2373 \c void print_get_colour(drawing *dr, int colour, int *hatch,
2374 \c                       float *r, float *g, float *b)
2375
2376 This function is called by the implementations of the drawing API
2377 functions when they are called in a printing context. It takes a
2378 colour index as input, and returns the description of the colour as
2379 requested by the back end.
2380
2381 \c{*r}, \c{*g} and \c{*b} are filled with the RGB values of the
2382 desired colour if printing in colour.
2383
2384 \c{*hatch} is filled with the type of hatching (or not) desired if
2385 printing in black and white. See \k{print-grey-colour} for details
2386 of the values this integer can take.
2387
2388 \C{midend} The API provided by the mid-end
2389
2390 This chapter documents the API provided by the mid-end to be called
2391 by the front end. You probably only need to read this if you are a
2392 front end implementor, i.e. you are porting Puzzles to a new
2393 platform. If you're only interested in writing new puzzles, you can
2394 safely skip this chapter.
2395
2396 All the persistent state in the mid-end is encapsulated within a
2397 \c{midend} structure, to facilitate having multiple mid-ends in any
2398 port which supports multiple puzzle windows open simultaneously.
2399 Each \c{midend} is intended to handle the contents of a single
2400 puzzle window.
2401
2402 \H{midend-new} \cw{midend_new()}
2403
2404 \c midend *midend_new(frontend *fe, const game *ourgame,
2405 \c                    const drawing_api *drapi, void *drhandle)
2406
2407 Allocates and returns a new mid-end structure.
2408
2409 The \c{fe} argument is stored in the mid-end. It will be used when
2410 calling back to functions such as \cw{activate_timer()}
2411 (\k{frontend-activate-timer}), and will be passed on to the back end
2412 function \cw{colours()} (\k{backend-colours}).
2413
2414 The parameters \c{drapi} and \c{drhandle} are passed to
2415 \cw{drawing_init()} (\k{drawing-init}) to construct a drawing object
2416 which will be passed to the back end function \cw{redraw()}
2417 (\k{backend-redraw}). Hence, all drawing-related function pointers
2418 defined in \c{drapi} can expect to be called with \c{drhandle} as
2419 their first argument.
2420
2421 The \c{ourgame} argument points to a container structure describing
2422 a game back end. The mid-end thus created will only be capable of
2423 handling that one game. (So even in a monolithic front end
2424 containing all the games, this imposes the constraint that any
2425 individual puzzle window is tied to a single game. Unless, of
2426 course, you feel brave enough to change the mid-end for the window
2427 without closing the window...)
2428
2429 \H{midend-free} \cw{midend_free()}
2430
2431 \c void midend_free(midend *me);
2432
2433 Frees a mid-end structure and all its associated data.
2434
2435 \H{midend-set-params} \cw{midend_set_params()}
2436
2437 \c void midend_set_params(midend *me, game_params *params);
2438
2439 Sets the current game parameters for a mid-end. Subsequent games
2440 generated by \cw{midend_new_game()} (\k{midend-new-game}) will use
2441 these parameters until further notice.
2442
2443 The usual way in which the front end will have an actual
2444 \c{game_params} structure to pass to this function is if it had
2445 previously got it from \cw{midend_fetch_preset()}
2446 (\k{midend-fetch-preset}). Thus, this function is usually called in
2447 response to the user making a selection from the presets menu.
2448
2449 \H{midend-get-params} \cw{midend_get_params()}
2450
2451 \c game_params *midend_get_params(midend *me);
2452
2453 Returns the current game parameters stored in this mid-end.
2454
2455 The returned value is dynamically allocated, and should be freed
2456 when finished with by passing it to the game's own
2457 \cw{free_params()} function (see \k{backend-free-params}).
2458
2459 \H{midend-size} \cw{midend_size()}
2460
2461 \c void midend_size(midend *me, int *x, int *y, int expand);
2462
2463 Tells the mid-end to figure out its window size.
2464
2465 On input, \c{*x} and \c{*y} should contain the maximum or requested
2466 size for the window. (Typically this will be the size of the screen
2467 that the window has to fit on, or similar.) The mid-end will
2468 repeatedly call the back end function \cw{compute_size()}
2469 (\k{backend-compute-size}), searching for a tile size that best
2470 satisfies the requirements. On exit, \c{*x} and \c{*y} will contain
2471 the size needed for the puzzle window's drawing area. (It is of
2472 course up to the front end to adjust this for any additional window
2473 furniture such as menu bars and window borders, if necessary. The
2474 status bar is also not included in this size.)
2475
2476 If \c{expand} is set to \cw{FALSE}, then the game's tile size will
2477 never go over its preferred one. This is the recommended approach
2478 when opening a new window at default size: the game will use its
2479 preferred size unless it has to use a smaller one to fit on the
2480 screen.
2481
2482 If \c{expand} is set to \cw{TRUE}, the mid-end will pick a tile size
2483 which approximates the input size \e{as closely as possible}, and
2484 will go over the game's preferred tile size if necessary to achieve
2485 this. Use this option if you want your front end to support dynamic
2486 resizing of the puzzle window with automatic scaling of the puzzle
2487 to fit.
2488
2489 The mid-end will try as hard as it can to return a size which is
2490 less than or equal to the input size, in both dimensions. In extreme
2491 circumstances it may fail (if even the lowest possible tile size
2492 gives window dimensions greater than the input), in which case it
2493 will return a size greater than the input size. Front ends should be
2494 prepared for this to happen (i.e. don't crash or fail an assertion),
2495 but may handle it in any way they see fit: by rejecting the game
2496 parameters which caused the problem, by opening a window larger than
2497 the screen regardless of inconvenience, by introducing scroll bars
2498 on the window, by drawing on a large bitmap and scaling it into a
2499 smaller window, or by any other means you can think of. It is likely
2500 that when the tile size is that small the game will be unplayable
2501 anyway, so don't put \e{too} much effort into handling it
2502 creatively.
2503
2504 If your platform has no limit on window size (or if you're planning
2505 to use scroll bars for large puzzles), you can pass dimensions of
2506 \cw{INT_MAX} as input to this function. You should probably not do
2507 that \e{and} set the \c{expand} flag, though!
2508
2509 \H{midend-new-game} \cw{midend_new_game()}
2510
2511 \c void midend_new_game(midend *me);
2512
2513 Causes the mid-end to begin a new game. Normally the game will be a
2514 new randomly generated puzzle. However, if you have previously
2515 called \cw{midend_game_id()} or \cw{midend_set_config()}, the game
2516 generated might be dictated by the results of those functions. (In
2517 particular, you \e{must} call \cw{midend_new_game()} after calling
2518 either of those functions, or else no immediate effect will be
2519 visible.)
2520
2521 You will probably need to call \cw{midend_size()} after calling this
2522 function, because if the game parameters have been changed since the
2523 last new game then the window size might need to change. (If you
2524 know the parameters \e{haven't} changed, you don't need to do this.)
2525
2526 This function will create a new \c{game_drawstate}, but does not
2527 actually perform a redraw (since you often need to call
2528 \cw{midend_size()} before the redraw can be done). So after calling
2529 this function and after calling \cw{midend_size()}, you should then
2530 call \cw{midend_redraw()}. (It is not necessary to call
2531 \cw{midend_force_redraw()}; that will discard the draw state and
2532 create a fresh one, which is unnecessary in this case since there's
2533 a fresh one already. It would work, but it's usually excessive.)
2534
2535 \H{midend-restart-game} \cw{midend_restart_game()}
2536
2537 \c void midend_restart_game(midend *me);
2538
2539 This function causes the current game to be restarted. This is done
2540 by placing a new copy of the original game state on the end of the
2541 undo list (so that an accidental restart can be undone).
2542
2543 This function automatically causes a redraw, i.e. the front end can
2544 expect its drawing API to be called from \e{within} a call to this
2545 function.
2546
2547 \H{midend-force-redraw} \cw{midend_force_redraw()}
2548
2549 \c void midend_force_redraw(midend *me);
2550
2551 Forces a complete redraw of the puzzle window, by means of
2552 discarding the current \c{game_drawstate} and creating a new one
2553 from scratch before calling the game's \cw{redraw()} function.
2554
2555 The front end can expect its drawing API to be called from within a
2556 call to this function.
2557
2558 \H{midend-redraw} \cw{midend_redraw()}
2559
2560 \c void midend_redraw(midend *me);
2561
2562 Causes a partial redraw of the puzzle window, by means of simply
2563 calling the game's \cw{redraw()} function. (That is, the only things
2564 redrawn will be things that have changed since the last redraw.)
2565
2566 The front end can expect its drawing API to be called from within a
2567 call to this function.
2568
2569 \H{midend-process-key} \cw{midend_process_key()}
2570
2571 \c int midend_process_key(midend *me, int x, int y, int button);
2572
2573 The front end calls this function to report a mouse or keyboard
2574 event. The parameters \c{x}, \c{y} and \c{button} are almost
2575 identical to the ones passed to the back end function
2576 \cw{interpret_move()} (\k{backend-interpret-move}), except that the
2577 front end is \e{not} required to provide the guarantees about mouse
2578 event ordering. The mid-end will sort out multiple simultaneous
2579 button presses and changes of button; the front end's responsibility
2580 is simply to pass on the mouse events it receives as accurately as
2581 possible.
2582
2583 (Some platforms may need to emulate absent mouse buttons by means of
2584 using a modifier key such as Shift with another mouse button. This
2585 tends to mean that if Shift is pressed or released in the middle of
2586 a mouse drag, the mid-end will suddenly stop receiving, say,
2587 \cw{LEFT_DRAG} events and start receiving \cw{RIGHT_DRAG}s, with no
2588 intervening button release or press events. This too is something
2589 which the mid-end will sort out for you; the front end has no
2590 obligation to maintain sanity in this area.)
2591
2592 The front end \e{should}, however, always eventually send some kind
2593 of button release. On some platforms this requires special effort:
2594 Windows, for example, requires a call to the system API function
2595 \cw{SetCapture()} in order to ensure that your window receives a
2596 mouse-up event even if the pointer has left the window by the time
2597 the mouse button is released. On any platform that requires this
2598 sort of thing, the front end \e{is} responsible for doing it.
2599
2600 Calling this function is very likely to result in calls back to the
2601 front end's drawing API and/or \cw{activate_timer()}
2602 (\k{frontend-activate-timer}).
2603
2604 \H{midend-colours} \cw{midend_colours()}
2605
2606 \c float *midend_colours(midend *me, int *ncolours);
2607
2608 Returns an array of the colours required by the game, in exactly the
2609 same format as that returned by the back end function \cw{colours()}
2610 (\k{backend-colours}). Front ends should call this function rather
2611 than calling the back end's version directly, since the mid-end adds
2612 standard customisation facilities. (At the time of writing, those
2613 customisation facilities are implemented hackily by means of
2614 environment variables, but it's not impossible that they may become
2615 more full and formal in future.)
2616
2617 \H{midend-timer} \cw{midend_timer()}
2618
2619 \c void midend_timer(midend *me, float tplus);
2620
2621 If the mid-end has called \cw{activate_timer()}
2622 (\k{frontend-activate-timer}) to request regular callbacks for
2623 purposes of animation or timing, this is the function the front end
2624 should call on a regular basis. The argument \c{tplus} gives the
2625 time, in seconds, since the last time either this function was
2626 called or \cw{activate_timer()} was invoked.
2627
2628 One of the major purposes of timing in the mid-end is to perform
2629 move animation. Therefore, calling this function is very likely to
2630 result in calls back to the front end's drawing API.
2631
2632 \H{midend-num-presets} \cw{midend_num_presets()}
2633
2634 \c int midend_num_presets(midend *me);
2635
2636 Returns the number of game parameter presets supplied by this game.
2637 Front ends should use this function and \cw{midend_fetch_preset()}
2638 to configure their presets menu rather than calling the back end
2639 directly, since the mid-end adds standard customisation facilities.
2640 (At the time of writing, those customisation facilities are
2641 implemented hackily by means of environment variables, but it's not
2642 impossible that they may become more full and formal in future.)
2643
2644 \H{midend-fetch-preset} \cw{midend_fetch_preset()}
2645
2646 \c void midend_fetch_preset(midend *me, int n,
2647 \c                          char **name, game_params **params);
2648
2649 Returns one of the preset game parameter structures for the game. On
2650 input \c{n} must be a non-negative integer and less than the value
2651 returned from \cw{midend_num_presets()}. On output, \c{*name} is set
2652 to an ASCII string suitable for entering in the game's presets menu,
2653 and \c{*params} is set to the corresponding \c{game_params}
2654 structure.
2655
2656 Both of the two output values are dynamically allocated, but they
2657 are owned by the mid-end structure: the front end should not ever
2658 free them directly, because they will be freed automatically during
2659 \cw{midend_free()}.
2660
2661 \H{midend-wants-statusbar} \cw{midend_wants_statusbar()}
2662
2663 \c int midend_wants_statusbar(midend *me);
2664
2665 This function returns \cw{TRUE} if the puzzle has a use for a
2666 textual status line (to display score, completion status, currently
2667 active tiles, time, or anything else).
2668
2669 Front ends should call this function rather than talking directly to
2670 the back end.
2671
2672 \H{midend-get-config} \cw{midend_get_config()}
2673
2674 \c config_item *midend_get_config(midend *me, int which,
2675 \c                                char **wintitle);
2676
2677 Returns a dialog box description for user configuration.
2678
2679 On input, \cw{which} should be set to one of three values, which
2680 select which of the various dialog box descriptions is returned:
2681
2682 \dt \cw{CFG_SETTINGS}
2683
2684 \dd Requests the GUI parameter configuration box generated by the
2685 puzzle itself. This should be used when the user selects \q{Custom}
2686 from the game types menu (or equivalent). The mid-end passes this
2687 request on to the back end function \cw{configure()}
2688 (\k{backend-configure}).
2689
2690 \dt \cw{CFG_DESC}
2691
2692 \dd Requests a box suitable for entering a descriptive game ID (and
2693 viewing the existing one). The mid-end generates this dialog box
2694 description itself. This should be used when the user selects
2695 \q{Specific} from the game menu (or equivalent).
2696
2697 \dt \cw{CFG_SEED}
2698
2699 \dd Requests a box suitable for entering a random-seed game ID (and
2700 viewing the existing one). The mid-end generates this dialog box
2701 description itself. This should be used when the user selects
2702 \q{Random Seed} from the game menu (or equivalent).
2703
2704 The returned value is an array of \cw{config_item}s, exactly as
2705 described in \k{backend-configure}. Another returned value is an
2706 ASCII string giving a suitable title for the configuration window,
2707 in \c{*wintitle}.
2708
2709 Both returned values are dynamically allocated and will need to be
2710 freed. The window title can be freed in the obvious way; the
2711 \cw{config_item} array is a slightly complex structure, so a utility
2712 function \cw{free_cfg()} is provided to free it for you. See
2713 \k{utils-free-cfg}.
2714
2715 (Of course, you will probably not want to free the \cw{config_item}
2716 array until the dialog box is dismissed, because before then you
2717 will probably need to pass it to \cw{midend_set_config}.)
2718
2719 \H{midend-set-config} \cw{midend_set_config()}
2720
2721 \c char *midend_set_config(midend *me, int which,
2722 \c                         config_item *cfg);
2723
2724 Passes the mid-end the results of a configuration dialog box.
2725 \c{which} should have the same value which it had when
2726 \cw{midend_get_config()} was called; \c{cfg} should be the array of
2727 \c{config_item}s returned from \cw{midend_get_config()}, modified to
2728 contain the results of the user's editing operations.
2729
2730 This function returns \cw{NULL} on success, or otherwise (if the
2731 configuration data was in some way invalid) an ASCII string
2732 containing an error message suitable for showing to the user.
2733
2734 If the function succeeds, it is likely that the game parameters will
2735 have been changed and it is certain that a new game will be
2736 requested. The front end should therefore call
2737 \cw{midend_new_game()}, and probably also re-think the window size
2738 using \cw{midend_size()} and eventually perform a refresh using
2739 \cw{midend_redraw()}.
2740
2741 \H{midend-game-id} \cw{midend_game_id()}
2742
2743 \c char *midend_game_id(midend *me, char *id);
2744
2745 Passes the mid-end a string game ID (of any of the valid forms
2746 \cq{params}, \cq{params:description} or \cq{params#seed}) which the
2747 mid-end will process and use for the next generated game.
2748
2749 This function returns \cw{NULL} on success, or otherwise (if the
2750 configuration data was in some way invalid) an ASCII string
2751 containing an error message (not dynamically allocated) suitable for
2752 showing to the user. In the event of an error, the mid-end's
2753 internal state will be left exactly as it was before the call.
2754
2755 If the function succeeds, it is likely that the game parameters will
2756 have been changed and it is certain that a new game will be
2757 requested. The front end should therefore call
2758 \cw{midend_new_game()}, and probably also re-think the window size
2759 using \cw{midend_size()} and eventually case a refresh using
2760 \cw{midend_redraw()}.
2761
2762 \H{midend-get-game-id} \cw{midend_get_game_id()}
2763
2764 \c char *midend_get_game_id(midend *me)
2765
2766 Returns a descriptive game ID (i.e. one in the form
2767 \cq{params:description}) describing the game currently active in the
2768 mid-end. The returned string is dynamically allocated.
2769
2770 \H{midend-text-format} \cw{midend_text_format()}
2771
2772 \c char *midend_text_format(midend *me);
2773
2774 Formats the current game's current state as ASCII text suitable for
2775 copying to the clipboard. The returned string is dynamically
2776 allocated.
2777
2778 You should not call this function if the game's
2779 \c{can_format_as_text} flag is \cw{FALSE}.
2780
2781 If the returned string contains multiple lines (which is likely), it
2782 will use the normal C line ending convention (\cw{\\n} only). On
2783 platforms which use a different line ending convention for data in
2784 the clipboard, it is the front end's responsibility to perform the
2785 conversion.
2786
2787 \H{midend-solve} \cw{midend_solve()}
2788
2789 \c char *midend_solve(midend *me);
2790
2791 Requests the mid-end to perform a Solve operation.
2792
2793 On success, \cw{NULL} is returned. On failure, an error message (not
2794 dynamically allocated) is returned, suitable for showing to the
2795 user.
2796
2797 The front end can expect its drawing API and/or
2798 \cw{activate_timer()} to be called from within a call to this
2799 function.
2800
2801 \H{midend-rewrite-statusbar} \cw{midend_rewrite_statusbar()}
2802
2803 \c char *midend_rewrite_statusbar(midend *me, char *text);
2804
2805 The front end should call this function from within
2806 \cw{status_bar()} (\k{drawing-status-bar}). It should be passed the
2807 string that was passed by the back end to \cw{status_bar()}; it will
2808 return a dynamically allocated string adjusted by the mid-end.
2809 (Specifically, adjusted to include the timer if the game is a timed
2810 one.) The returned value should be placed in the actual status bar
2811 in place of the input value.
2812
2813 (This is a nasty piece of architecture; I apologise for it. It would
2814 seem a lot more pleasant to have the back end pass its status bar
2815 text to the mid-end, which in turn would rewrite it and pass it on
2816 to the front end, so that each front end needed to do nothing
2817 strange. The main reason why I haven't done this is because it means
2818 the back end redraw function would need to be passed a mid-end
2819 pointer \e{as well} as a front end pointer, which seemed like an
2820 excessive proliferation of opaque handles. The only way to avoid
2821 that proliferation would be to have all the drawing API functions
2822 also gatewayed through the mid-end, and that seemed like an
2823 excessive proliferation of wrapper functions. The current setup
2824 isn't nice, but it has minimal impact and I'm unconvinced that any
2825 of the other options are an improvement.)
2826
2827 \H{midend-serialise} \cw{midend_serialise()}
2828
2829 \c void midend_serialise(midend *me,
2830 \c                       void (*write)(void *ctx, void *buf, int len),
2831 \c                       void *wctx);
2832
2833 Calling this function causes the mid-end to convert its entire
2834 internal state into a long ASCII text string, and to pass that
2835 string (piece by piece) to the supplied \c{write} function.
2836
2837 Desktop implementations can use this function to save a game in any
2838 state (including half-finished) to a disk file, by supplying a
2839 \c{write} function which is a wrapper on \cw{fwrite()} (or local
2840 equivalent). Other implementations may find other uses for it, such
2841 as compressing the large and sprawling mid-end state into a
2842 manageable amount of memory when a palmtop application is suspended
2843 so that another one can run; in this case \cw{write} might want to
2844 write to a memory buffer rather than a file. There may be other uses
2845 for it as well.
2846
2847 This function will call back to the supplied \c{write} function a
2848 number of times, with the first parameter (\c{ctx}) equal to
2849 \c{wctx}, and the other two parameters pointing at a piece of the
2850 output string.
2851
2852 \H{midend-deserialise} \cw{midend_deserialise()}
2853
2854 \c char *midend_deserialise(midend *me,
2855 \c                          int (*read)(void *ctx, void *buf, int len),
2856 \c                          void *rctx);
2857
2858 This function is the counterpart to \cw{midend_serialise()}. It
2859 calls the supplied \cw{read} function repeatedly to read a quantity
2860 of data, and attempts to interpret that data as a serialised mid-end
2861 as output by \cw{midend_serialise()}.
2862
2863 The \cw{read} function is called with the first parameter (\c{ctx})
2864 equal to \c{rctx}, and should attempt to read \c{len} bytes of data
2865 into the buffer pointed to by \c{buf}. It should return \cw{FALSE}
2866 on failure or \cw{TRUE} on success. It should not report success
2867 unless it has filled the entire buffer; on platforms which might be
2868 reading from a pipe or other blocking data source, \c{read} is
2869 responsible for looping until the whole buffer has been filled.
2870
2871 If the de-serialisation operation is successful, the mid-end's
2872 internal data structures will be replaced by the results of the
2873 load, and \cw{NULL} will be returned. Otherwise, the mid-end's state
2874 will be completely unchanged and an error message (typically some
2875 variation on \q{save file is corrupt}) will be returned. As usual,
2876 the error message string is not dynamically allocated.
2877
2878 If this function succeeds, it is likely that the game parameters
2879 will have been changed. The front end should therefore probably
2880 re-think the window size using \cw{midend_size()}, and probably
2881 cause a refresh using \cw{midend_redraw()}.
2882
2883 Because each mid-end is tied to a specific game back end, this
2884 function will fail if you attempt to read in a save file generated
2885 by a different game from the one configured in this mid-end, even if
2886 your application is a monolithic one containing all the puzzles. (It
2887 would be pretty easy to write a function which would look at a save
2888 file and determine which game it was for; any front end implementor
2889 who needs such a function can probably be accommodated.)
2890
2891 \H{frontend-backend} Direct reference to the back end structure by
2892 the front end
2893
2894 Although \e{most} things the front end needs done should be done by
2895 calling the mid-end, there are a few situations in which the front
2896 end needs to refer directly to the game back end structure.
2897
2898 The most obvious of these is
2899
2900 \b passing the game back end as a parameter to \cw{midend_new()}.
2901
2902 There are a few other back end features which are not wrapped by the
2903 mid-end because there didn't seem much point in doing so:
2904
2905 \b fetching the \c{name} field to use in window titles and similar
2906
2907 \b reading the \c{can_configure}, \c{can_solve} and
2908 \c{can_format_as_text} fields to decide whether to add those items
2909 to the menu bar or equivalent
2910
2911 \b reading the \c{winhelp_topic} field (Windows only)
2912
2913 \b the GTK front end provides a \cq{--generate} command-line option
2914 which directly calls the back end to do most of its work. This is
2915 not really part of the main front end code, though, and I'm not sure
2916 it counts.
2917
2918 In order to find the game back end structure, the front end does one
2919 of two things:
2920
2921 \b If the particular front end is compiling a separate binary per
2922 game, then the back end structure is a global variable with the
2923 standard name \cq{thegame}:
2924
2925 \lcont{
2926
2927 \c extern const game thegame;
2928
2929 }
2930
2931 \b If the front end is compiled as a monolithic application
2932 containing all the puzzles together (in which case the preprocessor
2933 symbol \cw{COMBINED} must be defined when compiling most of the code
2934 base), then there will be two global variables defined:
2935
2936 \lcont{
2937
2938 \c extern const game *gamelist[];
2939 \c extern const int gamecount;
2940
2941 \c{gamelist} will be an array of \c{gamecount} game structures,
2942 declared in the source module \c{list.c}. The application should
2943 search that array for the game it wants, probably by reaching into
2944 each game structure and looking at its \c{name} field.
2945
2946 }
2947
2948 \H{frontend-api} Mid-end to front-end calls
2949
2950 This section describes the small number of functions which a front
2951 end must provide to be called by the mid-end or other standard
2952 utility modules.
2953
2954 \H{frontend-get-random-seed} \cw{get_random_seed()}
2955
2956 \c void get_random_seed(void **randseed, int *randseedsize);
2957
2958 This function is called by a new mid-end, and also occasionally by
2959 game back ends. Its job is to return a piece of data suitable for
2960 using as a seed for initialisation of a new \c{random_state}.
2961
2962 On exit, \c{*randseed} should be set to point at a newly allocated
2963 piece of memory containing some seed data, and \c{*randseedsize}
2964 should be set to the length of that data.
2965
2966 A simple and entirely adequate implementation is to return a piece
2967 of data containing the current system time at the highest
2968 conveniently available resolution.
2969
2970 \H{frontend-activate-timer} \cw{activate_timer()}
2971
2972 \c void activate_timer(frontend *fe);
2973
2974 This is called by the mid-end to request that the front end begin
2975 calling it back at regular intervals.
2976
2977 The timeout interval is left up to the front end; the finer it is,
2978 the smoother move animations will be, but the more CPU time will be
2979 used. Current front ends use values around 20ms (i.e. 50Hz).
2980
2981 After this function is called, the mid-end will expect to receive
2982 calls to \cw{midend_timer()} on a regular basis.
2983
2984 \H{frontend-deactivate-timer} \cw{deactivate_timer()}
2985
2986 \c void deactivate_timer(frontend *fe);
2987
2988 This is called by the mid-end to request that the front end stop
2989 calling \cw{midend_timer()}.
2990
2991 \H{frontend-fatal} \cw{fatal()}
2992
2993 \c void fatal(char *fmt, ...);
2994
2995 This is called by some utility functions if they encounter a
2996 genuinely fatal error such as running out of memory. It is a
2997 variadic function in the style of \cw{printf()}, and is expected to
2998 show the formatted error message to the user any way it can and then
2999 terminate the application. It must not return.
3000
3001 \H{frontend-default-colour} \cw{frontend_default_colour()}
3002
3003 \c void frontend_default_colour(frontend *fe, float *output);
3004
3005 This function expects to be passed a pointer to an array of three
3006 \cw{float}s. It returns the platform's local preferred background
3007 colour in those three floats, as red, green and blue values (in that
3008 order) ranging from \cw{0.0} to \cw{1.0}.
3009
3010 This function should only ever be called by the back end function
3011 \cw{colours()} (\k{backend-colours}). (Thus, it isn't a
3012 \e{midend}-to-frontend function as such, but there didn't seem to be
3013 anywhere else particularly good to put it. Sorry.)
3014
3015 \C{utils} Utility APIs
3016
3017 This chapter documents a variety of utility APIs provided for the
3018 general use of the rest of the Puzzles code.
3019
3020 \H{utils-random} Random number generation
3021
3022 Platforms' local random number generators vary widely in quality and
3023 seed size. Puzzles therefore supplies its own high-quality random
3024 number generator, with the additional advantage of giving the same
3025 results if fed the same seed data on different platforms. This
3026 allows game random seeds to be exchanged between different ports of
3027 Puzzles and still generate the same games.
3028
3029 Unlike the ANSI C \cw{rand()} function, the Puzzles random number
3030 generator has an \e{explicit} state object called a
3031 \c{random_state}. One of these is managed by each mid-end, for
3032 example, and passed to the back end to generate a game with.
3033
3034 \S{utils-random-init} \cw{random_new()}
3035
3036 \c random_state *random_new(char *seed, int len);
3037
3038 Allocates, initialises and returns a new \c{random_state}. The input
3039 data is used as the seed for the random number stream (i.e. using
3040 the same seed at a later time will generate the same stream).
3041
3042 The seed data can be any data at all; there is no requirement to use
3043 printable ASCII, or NUL-terminated strings, or anything like that.
3044
3045 \S{utils-random-copy} \cw{random_copy()}
3046
3047 \c random_state *random_copy(random_state *tocopy);
3048
3049 Allocates a new \c{random_state}, copies the contents of another
3050 \c{random_state} into it, and returns the new state.  If exactly the
3051 same sequence of functions is subseqently called on both the copy and
3052 the original, the results will be identical.  This may be useful for
3053 speculatively performing some operation using a given random state,
3054 and later replaying that operation precisely.
3055
3056 \S{utils-random-free} \cw{random_free()}
3057
3058 \c void random_free(random_state *state);
3059
3060 Frees a \c{random_state}.
3061
3062 \S{utils-random-bits} \cw{random_bits()}
3063
3064 \c unsigned long random_bits(random_state *state, int bits);
3065
3066 Returns a random number from 0 to \cw{2^bits-1} inclusive. \c{bits}
3067 should be between 1 and 32 inclusive.
3068
3069 \S{utils-random-upto} \cw{random_upto()}
3070
3071 \c unsigned long random_upto(random_state *state, unsigned long limit);
3072
3073 Returns a random number from 0 to \cw{limit-1} inclusive.
3074
3075 \S{utils-random-state-encode} \cw{random_state_encode()}
3076
3077 \c char *random_state_encode(random_state *state);
3078
3079 Encodes the entire contents of a \c{random_state} in printable
3080 ASCII. Returns a dynamically allocated string containing that
3081 encoding. This can subsequently be passed to
3082 \cw{random_state_decode()} to reconstruct the same \c{random_state}.
3083
3084 \S{utils-random-state-decode} \cw{random_state_decode()}
3085
3086 \c random_state *random_state_decode(char *input);
3087
3088 Decodes a string generated by \cw{random_state_encode()} and
3089 reconstructs an equivalent \c{random_state} to the one encoded, i.e.
3090 it should produce the same stream of random numbers.
3091
3092 This function has no error reporting; if you pass it an invalid
3093 string it will simply generate an arbitrary random state, which may
3094 turn out to be noticeably non-random.
3095
3096 \S{utils-shuffle} \cw{shuffle()}
3097
3098 \c void shuffle(void *array, int nelts, int eltsize, random_state *rs);
3099
3100 Shuffles an array into a random order. The interface is much like
3101 ANSI C \cw{qsort()}, except that there's no need for a compare
3102 function.
3103
3104 \c{array} is a pointer to the first element of the array. \c{nelts}
3105 is the number of elements in the array; \c{eltsize} is the size of a
3106 single element (typically measured using \c{sizeof}). \c{rs} is a
3107 \c{random_state} used to generate all the random numbers for the
3108 shuffling process.
3109
3110 \H{utils-alloc} Memory allocation
3111
3112 Puzzles has some central wrappers on the standard memory allocation
3113 functions, which provide compile-time type checking, and run-time
3114 error checking by means of quitting the application if it runs out
3115 of memory. This doesn't provide the best possible recovery from
3116 memory shortage, but on the other hand it greatly simplifies the
3117 rest of the code, because nothing else anywhere needs to worry about
3118 \cw{NULL} returns from allocation.
3119
3120 \S{utils-snew} \cw{snew()}
3121
3122 \c var = snew(type);
3123 \e iii        iiii
3124
3125 This macro takes a single argument which is a \e{type name}. It
3126 allocates space for one object of that type. If allocation fails it
3127 will call \cw{fatal()} and not return; so if it does return, you can
3128 be confident that its return value is non-\cw{NULL}.
3129
3130 The return value is cast to the specified type, so that the compiler
3131 will type-check it against the variable you assign it into. Thus,
3132 this ensures you don't accidentally allocate memory the size of the
3133 wrong type and assign it into a variable of the right one (or vice
3134 versa!).
3135
3136 \S{utils-snewn} \cw{snewn()}
3137
3138 \c var = snewn(n, type);
3139 \e iii         i  iiii
3140
3141 This macro is the array form of \cw{snew()}. It takes two arguments;
3142 the first is a number, and the second is a type name. It allocates
3143 space for that many objects of that type, and returns a type-checked
3144 non-\cw{NULL} pointer just as \cw{snew()} does.
3145
3146 \S{utils-sresize} \cw{sresize()}
3147
3148 \c var = sresize(var, n, type);
3149 \e iii           iii  i  iiii
3150
3151 This macro is a type-checked form of \cw{realloc()}. It takes three
3152 arguments: an input memory block, a new size in elements, and a
3153 type. It re-sizes the input memory block to a size sufficient to
3154 contain that many elements of that type. It returns a type-checked
3155 non-\cw{NULL} pointer, like \cw{snew()} and \cw{snewn()}.
3156
3157 The input memory block can be \cw{NULL}, in which case this function
3158 will behave exactly like \cw{snewn()}. (In principle any
3159 ANSI-compliant \cw{realloc()} implementation ought to cope with
3160 this, but I've never quite trusted it to work everywhere.)
3161
3162 \S{utils-sfree} \cw{sfree()}
3163
3164 \c void sfree(void *p);
3165
3166 This function is pretty much equivalent to \cw{free()}. It is
3167 provided with a dynamically allocated block, and frees it.
3168
3169 The input memory block can be \cw{NULL}, in which case this function
3170 will do nothing. (In principle any ANSI-compliant \cw{free()}
3171 implementation ought to cope with this, but I've never quite trusted
3172 it to work everywhere.)
3173
3174 \S{utils-dupstr} \cw{dupstr()}
3175
3176 \c char *dupstr(const char *s);
3177
3178 This function dynamically allocates a duplicate of a C string. Like
3179 the \cw{snew()} functions, it guarantees to return non-\cw{NULL} or
3180 not return at all.
3181
3182 (Many platforms provide the function \cw{strdup()}. As well as
3183 guaranteeing never to return \cw{NULL}, my version has the advantage
3184 of being defined \e{everywhere}, rather than inconveniently not
3185 quite everywhere.)
3186
3187 \S{utils-free-cfg} \cw{free_cfg()}
3188
3189 \c void free_cfg(config_item *cfg);
3190
3191 This function correctly frees an array of \c{config_item}s,
3192 including walking the array until it gets to the end and freeing
3193 precisely those \c{sval} fields which are expected to be dynamically
3194 allocated.
3195
3196 (See \k{backend-configure} for details of the \c{config_item}
3197 structure.)
3198
3199 \H{utils-tree234} Sorted and counted tree functions
3200
3201 Many games require complex algorithms for generating random puzzles,
3202 and some require moderately complex algorithms even during play. A
3203 common requirement during these algorithms is for a means of
3204 maintaining sorted or unsorted lists of items, such that items can
3205 be removed and added conveniently.
3206
3207 For general use, Puzzles provides the following set of functions
3208 which maintain 2-3-4 trees in memory. (A 2-3-4 tree is a balanced
3209 tree structure, with the property that all lookups, insertions,
3210 deletions, splits and joins can be done in \cw{O(log N)} time.)
3211
3212 All these functions expect you to be storing a tree of \c{void *}
3213 pointers. You can put anything you like in those pointers.
3214
3215 By the use of per-node element counts, these tree structures have
3216 the slightly unusual ability to look elements up by their numeric
3217 index within the list represented by the tree. This means that they
3218 can be used to store an unsorted list (in which case, every time you
3219 insert a new element, you must explicitly specify the position where
3220 you wish to insert it). They can also do numeric lookups in a sorted
3221 tree, which might be useful for (for example) tracking the median of
3222 a changing data set.
3223
3224 As well as storing sorted lists, these functions can be used for
3225 storing \q{maps} (associative arrays), by defining each element of a
3226 tree to be a (key, value) pair.
3227
3228 \S{utils-newtree234} \cw{newtree234()}
3229
3230 \c tree234 *newtree234(cmpfn234 cmp);
3231
3232 Creates a new empty tree, and returns a pointer to it.
3233
3234 The parameter \c{cmp} determines the sorting criterion on the tree.
3235 Its prototype is
3236
3237 \c typedef int (*cmpfn234)(void *, void *);
3238
3239 If you want a sorted tree, you should provide a function matching
3240 this prototype, which returns like \cw{strcmp()} does (negative if
3241 the first argument is smaller than the second, positive if it is
3242 bigger, zero if they compare equal). In this case, the function
3243 \cw{addpos234()} will not be usable on your tree (because all
3244 insertions must respect the sorting order).
3245
3246 If you want an unsorted tree, pass \cw{NULL}. In this case you will
3247 not be able to use either \cw{add234()} or \cw{del234()}, or any
3248 other function such as \cw{find234()} which depends on a sorting
3249 order. Your tree will become something more like an array, except
3250 that it will efficiently support insertion and deletion as well as
3251 lookups by numeric index.
3252
3253 \S{utils-freetree234} \cw{freetree234()}
3254
3255 \c void freetree234(tree234 *t);
3256
3257 Frees a tree. This function will not free the \e{elements} of the
3258 tree (because they might not be dynamically allocated, or you might
3259 be storing the same set of elements in more than one tree); it will
3260 just free the tree structure itself. If you want to free all the
3261 elements of a tree, you should empty it before passing it to
3262 \cw{freetree234()}, by means of code along the lines of
3263
3264 \c while ((element = delpos234(tree, 0)) != NULL)
3265 \c     sfree(element); /* or some more complicated free function */
3266 \e                     iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
3267
3268 \S{utils-add234} \cw{add234()}
3269
3270 \c void *add234(tree234 *t, void *e);
3271
3272 Inserts a new element \c{e} into the tree \c{t}. This function
3273 expects the tree to be sorted; the new element is inserted according
3274 to the sort order.
3275
3276 If an element comparing equal to \c{e} is already in the tree, then
3277 the insertion will fail, and the return value will be the existing
3278 element. Otherwise, the insertion succeeds, and \c{e} is returned.
3279
3280 \S{utils-addpos234} \cw{addpos234()}
3281
3282 \c void *addpos234(tree234 *t, void *e, int index);
3283
3284 Inserts a new element into an unsorted tree. Since there is no
3285 sorting order to dictate where the new element goes, you must
3286 specify where you want it to go. Setting \c{index} to zero puts the
3287 new element right at the start of the list; setting \c{index} to the
3288 current number of elements in the tree puts the new element at the
3289 end.
3290
3291 Return value is \c{e}, in line with \cw{add234()} (although this
3292 function cannot fail except by running out of memory, in which case
3293 it will bomb out and die rather than returning an error indication).
3294
3295 \S{utils-index234} \cw{index234()}
3296
3297 \c void *index234(tree234 *t, int index);
3298
3299 Returns a pointer to the \c{index}th element of the tree, or
3300 \cw{NULL} if \c{index} is out of range. Elements of the tree are
3301 numbered from zero.
3302
3303 \S{utils-find234} \cw{find234()}
3304
3305 \c void *find234(tree234 *t, void *e, cmpfn234 cmp);
3306
3307 Searches for an element comparing equal to \c{e} in a sorted tree.
3308
3309 If \c{cmp} is \cw{NULL}, the tree's ordinary comparison function
3310 will be used to perform the search. However, sometimes you don't
3311 want that; suppose, for example, each of your elements is a big
3312 structure containing a \c{char *} name field, and you want to find
3313 the element with a given name. You \e{could} achieve this by
3314 constructing a fake element structure, setting its name field
3315 appropriately, and passing it to \cw{find234()}, but you might find
3316 it more convenient to pass \e{just} a name string to \cw{find234()},
3317 supplying an alternative comparison function which expects one of
3318 its arguments to be a bare name and the other to be a large
3319 structure containing a name field.
3320
3321 Therefore, if \c{cmp} is not \cw{NULL}, then it will be used to
3322 compare \c{e} to elements of the tree. The first argument passed to
3323 \c{cmp} will always be \c{e}; the second will be an element of the
3324 tree.
3325
3326 (See \k{utils-newtree234} for the definition of the \c{cmpfn234}
3327 function pointer type.)
3328
3329 The returned value is the element found, or \cw{NULL} if the search
3330 is unsuccessful.
3331
3332 \S{utils-findrel234} \cw{findrel234()}
3333
3334 \c void *findrel234(tree234 *t, void *e, cmpfn234 cmp, int relation);
3335
3336 This function is like \cw{find234()}, but has the additional ability
3337 to do a \e{relative} search. The additional parameter \c{relation}
3338 can be one of the following values:
3339
3340 \dt \cw{REL234_EQ}
3341
3342 \dd Find only an element that compares equal to \c{e}. This is
3343 exactly the behaviour of \cw{find234()}.
3344
3345 \dt \cw{REL234_LT}
3346
3347 \dd Find the greatest element that compares strictly less than
3348 \c{e}. \c{e} may be \cw{NULL}, in which case it finds the greatest
3349 element in the whole tree (which could also be done by
3350 \cw{index234(t, count234(t)-1)}).
3351
3352 \dt \cw{REL234_LE}
3353
3354 \dd Find the greatest element that compares less than or equal to
3355 \c{e}. (That is, find an element that compares equal to \c{e} if
3356 possible, but failing that settle for something just less than it.)
3357
3358 \dt \cw{REL234_GT}
3359
3360 \dd Find the smallest element that compares strictly greater than
3361 \c{e}. \c{e} may be \cw{NULL}, in which case it finds the smallest
3362 element in the whole tree (which could also be done by
3363 \cw{index234(t, 0)}).
3364
3365 \dt \cw{REL234_GE}
3366
3367 \dd Find the smallest element that compares greater than or equal to
3368 \c{e}. (That is, find an element that compares equal to \c{e} if
3369 possible, but failing that settle for something just bigger than
3370 it.)
3371
3372 Return value, as before, is the element found or \cw{NULL} if no
3373 element satisfied the search criterion.
3374
3375 \S{utils-findpos234} \cw{findpos234()}
3376
3377 \c void *findpos234(tree234 *t, void *e, cmpfn234 cmp, int *index);
3378
3379 This function is like \cw{find234()}, but has the additional feature
3380 of returning the index of the element found in the tree; that index
3381 is written to \c{*index} in the event of a successful search (a
3382 non-\cw{NULL} return value).
3383
3384 \c{index} may be \cw{NULL}, in which case this function behaves
3385 exactly like \cw{find234()}.
3386
3387 \S{utils-findrelpos234} \cw{findrelpos234()}
3388
3389 \c void *findrelpos234(tree234 *t, void *e, cmpfn234 cmp, int relation,
3390 \c                     int *index);
3391
3392 This function combines all the features of \cw{findrel234()} and
3393 \cw{findpos234()}.
3394
3395 \S{utils-del234} \cw{del234()}
3396
3397 \c void *del234(tree234 *t, void *e);
3398
3399 Finds an element comparing equal to \c{e} in the tree, deletes it,
3400 and returns it.
3401
3402 The input tree must be sorted.
3403
3404 The element found might be \c{e} itself, or might merely compare
3405 equal to it.
3406
3407 Return value is \cw{NULL} if no such element is found.
3408
3409 \S{utils-delpos234} \cw{delpos234()}
3410
3411 \c void *delpos234(tree234 *t, int index);
3412
3413 Deletes the element at position \c{index} in the tree, and returns
3414 it.
3415
3416 Return value is \cw{NULL} if the index is out of range.
3417
3418 \S{utils-count234} \cw{count234()}
3419
3420 \c int count234(tree234 *t);
3421
3422 Returns the number of elements currently in the tree.
3423
3424 \S{utils-splitpos234} \cw{splitpos234()}
3425
3426 \c tree234 *splitpos234(tree234 *t, int index, int before);
3427
3428 Splits the input tree into two pieces at a given position, and
3429 creates a new tree containing all the elements on one side of that
3430 position.
3431
3432 If \c{before} is \cw{TRUE}, then all the items at or after position
3433 \c{index} are left in the input tree, and the items before that
3434 point are returned in the new tree. Otherwise, the reverse happens:
3435 all the items at or after \c{index} are moved into the new tree, and
3436 those before that point are left in the old one.
3437
3438 If \c{index} is equal to 0 or to the number of elements in the input
3439 tree, then one of the two trees will end up empty (and this is not
3440 an error condition). If \c{index} is further out of range in either
3441 direction, the operation will fail completely and return \cw{NULL}.
3442
3443 This operation completes in \cw{O(log N)} time, no matter how large
3444 the tree or how balanced or unbalanced the split.
3445
3446 \S{utils-split234} \cw{split234()}
3447
3448 \c tree234 *split234(tree234 *t, void *e, cmpfn234 cmp, int rel);
3449
3450 Splits a sorted tree according to its sort order.
3451
3452 \c{rel} can be any of the relation constants described in
3453 \k{utils-findrel234}, \e{except} for \cw{REL234_EQ}. All the
3454 elements having that relation to \c{e} will be transferred into the
3455 new tree; the rest will be left in the old one.
3456
3457 The parameter \c{cmp} has the same semantics as it does in
3458 \cw{find234()}: if it is not \cw{NULL}, it will be used in place of
3459 the tree's own comparison function when comparing elements to \c{e},
3460 in such a way that \c{e} itself is always the first of its two
3461 operands.
3462
3463 Again, this operation completes in \cw{O(log N)} time, no matter how
3464 large the tree or how balanced or unbalanced the split.
3465
3466 \S{utils-join234} \cw{join234()}
3467
3468 \c tree234 *join234(tree234 *t1, tree234 *t2);
3469
3470 Joins two trees together by concatenating the lists they represent.
3471 All the elements of \c{t2} are moved into \c{t1}, in such a way that
3472 they appear \e{after} the elements of \c{t1}. The tree \c{t2} is
3473 freed; the return value is \c{t1}.
3474
3475 If you apply this function to a sorted tree and it violates the sort
3476 order (i.e. the smallest element in \c{t2} is smaller than or equal
3477 to the largest element in \c{t1}), the operation will fail and
3478 return \cw{NULL}.
3479
3480 This operation completes in \cw{O(log N)} time, no matter how large
3481 the trees being joined together.
3482
3483 \S{utils-join234r} \cw{join234r()}
3484
3485 \c tree234 *join234r(tree234 *t1, tree234 *t2);
3486
3487 Joins two trees together in exactly the same way as \cw{join234()},
3488 but this time the combined tree is returned in \c{t2}, and \c{t1} is
3489 destroyed. The elements in \c{t1} still appear before those in
3490 \c{t2}.
3491
3492 Again, this operation completes in \cw{O(log N)} time, no matter how
3493 large the trees being joined together.
3494
3495 \S{utils-copytree234} \cw{copytree234()}
3496
3497 \c tree234 *copytree234(tree234 *t, copyfn234 copyfn,
3498 \c                      void *copyfnstate);
3499
3500 Makes a copy of an entire tree.
3501
3502 If \c{copyfn} is \cw{NULL}, the tree will be copied but the elements
3503 will not be; i.e. the new tree will contain pointers to exactly the
3504 same physical elements as the old one.
3505
3506 If you want to copy each actual element during the operation, you
3507 can instead pass a function in \c{copyfn} which makes a copy of each
3508 element. That function has the prototype
3509
3510 \c typedef void *(*copyfn234)(void *state, void *element);
3511
3512 and every time it is called, the \c{state} parameter will be set to
3513 the value you passed in as \c{copyfnstate}.
3514
3515 \H{utils-misc} Miscellaneous utility functions and macros
3516
3517 This section contains all the utility functions which didn't
3518 sensibly fit anywhere else.
3519
3520 \S{utils-truefalse} \cw{TRUE} and \cw{FALSE}
3521
3522 The main Puzzles header file defines the macros \cw{TRUE} and
3523 \cw{FALSE}, which are used throughout the code in place of 0 and 1
3524 to indicate that the values are in a boolean context. For code base
3525 consistency, I'd prefer it if submissions of new code followed this
3526 convention as well.
3527
3528 \S{utils-maxmin} \cw{max()} and \cw{min()}
3529
3530 The main Puzzles header file defines the pretty standard macros
3531 \cw{max()} and \cw{min()}, each of which is given two arguments and
3532 returns the one which compares greater or less respectively.
3533
3534 These macros may evaluate their arguments multiple times. Avoid side
3535 effects.
3536
3537 \S{utils-pi} \cw{PI}
3538
3539 The main Puzzles header file defines a macro \cw{PI} which expands
3540 to a floating-point constant representing pi.
3541
3542 (I've never understood why ANSI's \cw{<math.h>} doesn't define this.
3543 It'd be so useful!)
3544
3545 \S{utils-obfuscate-bitmap} \cw{obfuscate_bitmap()}
3546
3547 \c void obfuscate_bitmap(unsigned char *bmp, int bits, int decode);
3548
3549 This function obscures the contents of a piece of data, by
3550 cryptographic methods. It is useful for games of hidden information
3551 (such as Mines, Guess or Black Box), in which the game ID
3552 theoretically reveals all the information the player is supposed to
3553 be trying to guess. So in order that players should be able to send
3554 game IDs to one another without accidentally spoiling the resulting
3555 game by looking at them, these games obfuscate their game IDs using
3556 this function.
3557
3558 Although the obfuscation function is cryptographic, it cannot
3559 properly be called encryption because it has no key. Therefore,
3560 anybody motivated enough can re-implement it, or hack it out of the
3561 Puzzles source, and strip the obfuscation off one of these game IDs
3562 to see what lies beneath. (Indeed, they could usually do it much
3563 more easily than that, by entering the game ID into their own copy
3564 of the puzzle and hitting Solve.) The aim is not to protect against
3565 a determined attacker; the aim is simply to protect people who
3566 wanted to play the game honestly from \e{accidentally} spoiling
3567 their own fun.
3568
3569 The input argument \c{bmp} points at a piece of memory to be
3570 obfuscated. \c{bits} gives the length of the data. Note that that
3571 length is in \e{bits} rather than bytes: if you ask for obfuscation
3572 of a partial number of bytes, then you will get it. Bytes are
3573 considered to be used from the top down: thus, for example, setting
3574 \c{bits} to 10 will cover the whole of \cw{bmp[0]} and the \e{top
3575 two} bits of \cw{bmp[1]}. The remainder of a partially used byte is
3576 undefined (i.e. it may be corrupted by the function).
3577
3578 The parameter \c{decode} is \cw{FALSE} for an encoding operation,
3579 and \cw{TRUE} for a decoding operation. Each is the inverse of the
3580 other. (There's no particular reason you shouldn't obfuscate by
3581 decoding and restore cleartext by encoding, if you really wanted to;
3582 it should still work.)
3583
3584 The input bitmap is processed in place.
3585
3586 \S{utils-bin2hex} \cw{bin2hex()}
3587
3588 \c char *bin2hex(const unsigned char *in, int inlen);
3589
3590 This function takes an input byte array and converts it into an
3591 ASCII string encoding those bytes in (lower-case) hex. It returns a
3592 dynamically allocated string containing that encoding.
3593
3594 This function is useful for encoding the result of
3595 \cw{obfuscate_bitmap()} in printable ASCII for use in game IDs.
3596
3597 \S{utils-hex2bin} \cw{hex2bin()}
3598
3599 \c unsigned char *hex2bin(const char *in, int outlen);
3600
3601 This function takes an ASCII string containing hex digits, and
3602 converts it back into a byte array of length \c{outlen}. If there
3603 aren't enough hex digits in the string, the contents of the
3604 resulting array will be undefined.
3605
3606 This function is the inverse of \cw{bin2hex()}.
3607
3608 \S{utils-game-mkhighlight} \cw{game_mkhighlight()}
3609
3610 \c void game_mkhighlight(frontend *fe, float *ret,
3611 \c                       int background, int highlight, int lowlight);
3612
3613 It's reasonably common for a puzzle game's graphics to use
3614 highlights and lowlights to indicate \q{raised} or \q{lowered}
3615 sections. Fifteen, Sixteen and Twiddle are good examples of this.
3616
3617 Puzzles using this graphical style are running a risk if they just
3618 use whatever background colour is supplied to them by the front end,
3619 because that background colour might be too light to see any
3620 highlights on at all. (In particular, it's not unheard of for the
3621 front end to specify a default background colour of white.)
3622
3623 Therefore, such puzzles can call this utility function from their
3624 \cw{colours()} routine (\k{backend-colours}). You pass it your front
3625 end handle, a pointer to the start of your return array, and three
3626 colour indices. It will:
3627
3628 \b call \cw{frontend_default_colour()} (\k{frontend-default-colour})
3629 to fetch the front end's default background colour
3630
3631 \b alter the brightness of that colour if it's unsuitable
3632
3633 \b define brighter and darker variants of the colour to be used as
3634 highlights and lowlights
3635
3636 \b write those results into the relevant positions in the \c{ret}
3637 array.
3638
3639 Thus, \cw{ret[background*3]} to \cw{ret[background*3+2]} will be set
3640 to RGB values defining a sensible background colour, and similary
3641 \c{highlight} and \c{lowlight} will be set to sensible colours.
3642
3643 \C{writing} How to write a new puzzle
3644
3645 This chapter gives a guide to how to actually write a new puzzle:
3646 where to start, what to do first, how to solve common problems.
3647
3648 The previous chapters have been largely composed of facts. This one
3649 is mostly advice.
3650
3651 \H{writing-editorial} Choosing a puzzle
3652
3653 Before you start writing a puzzle, you have to choose one. Your
3654 taste in puzzle games is up to you, of course; and, in fact, you're
3655 probably reading this guide because you've \e{already} thought of a
3656 game you want to write. But if you want to get it accepted into the
3657 official Puzzles distribution, then there's a criterion it has to
3658 meet.
3659
3660 The current Puzzles editorial policy is that all games should be
3661 \e{fair}. A fair game is one which a player can only fail to
3662 complete through demonstrable lack of skill \dash that is, such that
3663 a better player in the same situation would have \e{known} to do
3664 something different.
3665
3666 For a start, that means every game presented to the user must have
3667 \e{at least one solution}. Giving the unsuspecting user a puzzle
3668 which is actually impossible is not acceptable. (There is an
3669 exception: if the user has selected some non-default option which is
3670 clearly labelled as potentially unfair, \e{then} you're allowed to
3671 generate possibly insoluble puzzles, because the user isn't
3672 unsuspecting any more. Same Game and Mines both have options of this
3673 type.)
3674
3675 Also, this actually \e{rules out} games such as Klondike, or the
3676 normal form of Mahjong Solitaire. Those games have the property that
3677 even if there is a solution (i.e. some sequence of moves which will
3678 get from the start state to the solved state), the player doesn't
3679 necessarily have enough information to \e{find} that solution. In
3680 both games, it is possible to reach a dead end because you had an
3681 arbitrary choice to make and made it the wrong way. This violates
3682 the fairness criterion, because a better player couldn't have known
3683 they needed to make the other choice.
3684
3685 (GNOME has a variant on Mahjong Solitaire which makes it fair: there
3686 is a Shuffle operation which randomly permutes all the remaining
3687 tiles without changing their positions, which allows you to get out
3688 of a sticky situation. Using this operation adds a 60-second penalty
3689 to your solution time, so it's to the player's advantage to try to
3690 minimise the chance of having to use it. It's still possible to
3691 render the game uncompletable if you end up with only two tiles
3692 vertically stacked, but that's easy to foresee and avoid using a
3693 shuffle operation. This form of the game \e{is} fair. Implementing
3694 it in Puzzles would require an infrastructure change so that the
3695 back end could communicate time penalties to the mid-end, but that
3696 would be easy enough.)
3697
3698 Providing a \e{unique} solution is a little more negotiable; it
3699 depends on the puzzle. Solo would have been of unacceptably low
3700 quality if it didn't always have a unique solution, whereas Twiddle
3701 inherently has multiple solutions by its very nature and it would
3702 have been meaningless to even \e{suggest} making it uniquely
3703 soluble. Somewhere in between, Flip could reasonably be made to have
3704 unique solutions (by enforcing a zero-dimension kernel in every
3705 generated matrix) but it doesn't seem like a serious quality problem
3706 that it doesn't.
3707
3708 Of course, you don't \e{have} to care about all this. There's
3709 nothing stopping you implementing any puzzle you want to if you're
3710 happy to maintain your puzzle yourself, distribute it from your own
3711 web site, fork the Puzzles code completely, or anything like that.
3712 It's free software; you can do what you like with it. But any game
3713 that you want to be accepted into \e{my} Puzzles code base has to
3714 satisfy the fairness criterion, which means all randomly generated
3715 puzzles must have a solution (unless the user has deliberately
3716 chosen otherwise) and it must be possible \e{in theory} to find that
3717 solution without having to guess.
3718
3719 \H{writing-gs} Getting started
3720
3721 The simplest way to start writing a new puzzle is to copy
3722 \c{nullgame.c}. This is a template puzzle source file which does
3723 almost nothing, but which contains all the back end function
3724 prototypes and declares the back end data structure correctly. It is
3725 built every time the rest of Puzzles is built, to ensure that it
3726 doesn't get out of sync with the code and remains buildable.
3727
3728 So start by copying \c{nullgame.c} into your new source file. Then
3729 you'll gradually add functionality until the very boring Null Game
3730 turns into your real game.
3731
3732 Next you'll need to add your puzzle to the Makefiles, in order to
3733 compile it conveniently. \e{Do not edit the Makefiles}: they are
3734 created automatically by the script \c{mkfiles.pl}, from the file
3735 called \c{Recipe}. Edit \c{Recipe}, and then re-run \c{mkfiles.pl}.
3736
3737 Once your source file is building, you can move on to the fun bit.
3738
3739 \S{writing-generation} Puzzle generation
3740
3741 Randomly generating instances of your puzzle is almost certain to be
3742 the most difficult part of the code, and also the task with the
3743 highest chance of turning out to be completely infeasible. Therefore
3744 I strongly recommend doing it \e{first}, so that if it all goes
3745 horribly wrong you haven't wasted any more time than you absolutely
3746 had to. What I usually do is to take an unmodified \c{nullgame.c},
3747 and start adding code to \cw{new_game_desc()} which tries to
3748 generate a puzzle instance and print it out using \cw{printf()}.
3749 Once that's working, \e{then} I start connecting it up to the return
3750 value of \cw{new_game_desc()}, populating other structures like
3751 \c{game_params}, and generally writing the rest of the source file.
3752
3753 There are many ways to generate a puzzle which is known to be
3754 soluble. In this section I list all the methods I currently know of,
3755 in case any of them can be applied to your puzzle. (Not all of these
3756 methods will work, or in some cases even make sense, for all
3757 puzzles.)
3758
3759 Some puzzles are mathematically tractable, meaning you can work out
3760 in advance which instances are soluble. Sixteen, for example, has a
3761 parity constraint in some settings which renders exactly half the
3762 game space unreachable, but it can be mathematically proved that any
3763 position not in that half \e{is} reachable. Therefore, Sixteen's
3764 grid generation simply consists of selecting at random from a well
3765 defined subset of the game space. Cube in its default state is even
3766 easier: \e{every} possible arrangement of the blue squares and the
3767 cube's starting position is soluble!
3768
3769 Another option is to redefine what you mean by \q{soluble}. Black
3770 Box takes this approach. There are layouts of balls in the box which
3771 are completely indistinguishable from one another no matter how many
3772 beams you fire into the box from which angles, which would normally
3773 be grounds for declaring those layouts unfair; but fortunately,
3774 detecting that indistinguishability is computationally easy. So
3775 Black Box doesn't demand that your ball placements match its own; it
3776 merely demands that your ball placements be \e{indistinguishable}
3777 from the ones it was thinking of. If you have an ambiguous puzzle,
3778 then any of the possible answers is considered to be a solution.
3779 Having redefined the rules in that way, any puzzle is soluble again.
3780
3781 Those are the simple techniques. If they don't work, you have to get
3782 cleverer.
3783
3784 One way to generate a soluble puzzle is to start from the solved
3785 state and make inverse moves until you reach a starting state. Then
3786 you know there's a solution, because you can just list the inverse
3787 moves you made and make them in the opposite order to return to the
3788 solved state.
3789
3790 This method can be simple and effective for puzzles where you get to
3791 decide what's a starting state and what's not. In Pegs, for example,
3792 the generator begins with one peg in the centre of the board and
3793 makes inverse moves until it gets bored; in this puzzle, valid
3794 inverse moves are easy to detect, and \e{any} state that's reachable
3795 from the solved state by inverse moves is a reasonable starting
3796 position. So Pegs just continues making inverse moves until the
3797 board satisfies some criteria about extent and density, and then
3798 stops and declares itself done.
3799
3800 For other puzzles, it can be a lot more difficult. Same Game uses
3801 this strategy too, and it's lucky to get away with it at all: valid
3802 inverse moves aren't easy to find (because although it's easy to
3803 insert additional squares in a Same Game position, it's difficult to
3804 arrange that \e{after} the insertion they aren't adjacent to any
3805 other squares of the same colour), so you're constantly at risk of
3806 running out of options and having to backtrack or start again. Also,
3807 Same Game grids never start off half-empty, which means you can't
3808 just stop when you run out of moves \dash you have to find a way to
3809 fill the grid up \e{completely}.
3810
3811 The other way to generate a puzzle that's soluble is to start from
3812 the other end, and actually write a \e{solver}. This tends to ensure
3813 that a puzzle has a \e{unique} solution over and above having a
3814 solution at all, so it's a good technique to apply to puzzles for
3815 which that's important.
3816
3817 One theoretical drawback of generating soluble puzzles by using a
3818 solver is that your puzzles are restricted in difficulty to those
3819 which the solver can handle. (Most solvers are not fully general:
3820 many sets of puzzle rules are NP-complete or otherwise nasty, so
3821 most solvers can only handle a subset of the theoretically soluble
3822 puzzles.) It's been my experience in practice, however, that this
3823 usually isn't a problem; computers are good at very different things
3824 from humans, and what the computer thinks is nice and easy might
3825 still be pleasantly challenging for a human. For example, when
3826 solving Dominosa puzzles I frequently find myself using a variety of
3827 reasoning techniques that my solver doesn't know about; in
3828 principle, therefore, I should be able to solve the puzzle using
3829 only those techniques it \e{does} know about, but this would involve
3830 repeatedly searching the entire grid for the one simple deduction I
3831 can make. Computers are good at this sort of exhaustive search, but
3832 it's been my experience that human solvers prefer to do more complex
3833 deductions than to spend ages searching for simple ones. So in many
3834 cases I don't find my own playing experience to be limited by the
3835 restrictions on the solver.
3836
3837 (This isn't \e{always} the case. Solo is a counter-example;
3838 generating Solo puzzles using a simple solver does lead to
3839 qualitatively easier puzzles. Therefore I had to make the Solo
3840 solver rather more advanced than most of them.)
3841
3842 There are several different ways to apply a solver to the problem of
3843 generating a soluble puzzle. I list a few of them below.
3844
3845 The simplest approach is brute force: randomly generate a puzzle,
3846 use the solver to see if it's soluble, and if not, throw it away and
3847 try again until you get lucky. This is often a viable technique if
3848 all else fails, but it tends not to scale well: for many puzzle
3849 types, the probability of finding a uniquely soluble instance
3850 decreases sharply as puzzle size goes up, so this technique might
3851 work reasonably fast for small puzzles but take (almost) forever at
3852 larger sizes. Still, if there's no other alternative it can be
3853 usable: Pattern and Dominosa both use this technique. (However,
3854 Dominosa has a means of tweaking the randomly generated grids to
3855 increase the \e{probability} of them being soluble, by ruling out
3856 one of the most common ambiguous cases. This improved generation
3857 speed by over a factor of 10 on the highest preset!)
3858
3859 An approach which can be more scalable involves generating a grid
3860 and then tweaking it to make it soluble. This is the technique used
3861 by Mines and also by Net: first a random puzzle is generated, and
3862 then the solver is run to see how far it gets. Sometimes the solver
3863 will get stuck; when that happens, examine the area it's having
3864 trouble with, and make a small random change in that area to allow
3865 it to make more progress. Continue solving (possibly even without
3866 restarting the solver), tweaking as necessary, until the solver
3867 finishes. Then restart the solver from the beginning to ensure that
3868 the tweaks haven't caused new problems in the process of solving old
3869 ones (which can sometimes happen).
3870
3871 This strategy works well in situations where the usual solver
3872 failure mode is to get stuck in an easily localised spot. Thus it
3873 works well for Net and Mines, whose most common failure mode tends
3874 to be that most of the grid is fine but there are a few widely
3875 separated ambiguous sections; but it would work less well for
3876 Dominosa, in which the way you get stuck is to have scoured the
3877 whole grid and not found anything you can deduce \e{anywhere}. Also,
3878 it relies on there being a low probability that tweaking the grid
3879 introduces a new problem at the same time as solving the old one;
3880 Mines and Net also have the property that most of their deductions
3881 are local, so that it's very unlikely for a tweak to affect
3882 something half way across the grid from the location where it was
3883 applied. In Dominosa, by contrast, a lot of deductions use
3884 information about half the grid (\q{out of all the sixes, only one
3885 is next to a three}, which can depend on the values of up to 32 of
3886 the 56 squares in the default setting!), so this tweaking strategy
3887 would be rather less likely to work well.
3888
3889 A more specialised strategy is that used in Solo and Slant. These
3890 puzzles have the property that they derive their difficulty from not
3891 presenting all the available clues. (In Solo's case, if all the
3892 possible clues were provided then the puzzle would already be
3893 solved; in Slant it would still require user action to fill in the
3894 lines, but it would present no challenge at all). Therefore, a
3895 simple generation technique is to leave the decision of which clues
3896 to provide until the last minute. In other words, first generate a
3897 random \e{filled} grid with all possible clues present, and then
3898 gradually remove clues for as long as the solver reports that it's
3899 still soluble. Unlike the methods described above, this technique
3900 \e{cannot} fail \dash once you've got a filled grid, nothing can
3901 stop you from being able to convert it into a viable puzzle.
3902 However, it wouldn't even be meaningful to apply this technique to
3903 (say) Pattern, in which clues can never be left out, so the only way
3904 to affect the set of clues is by altering the solution.
3905
3906 (Unfortunately, Solo is complicated by the need to provide puzzles
3907 at varying difficulty levels. It's easy enough to generate a puzzle
3908 of \e{at most} a given level of difficulty; you just have a solver
3909 with configurable intelligence, and you set it to a given level and
3910 apply the above technique, thus guaranteeing that the resulting grid
3911 is solvable by someone with at most that much intelligence. However,
3912 generating a puzzle of \e{at least} a given level of difficulty is
3913 rather harder; if you go for \e{at most} Intermediate level, you're
3914 likely to find that you've accidentally generated a Trivial grid a
3915 lot of the time, because removing just one number is sufficient to
3916 take the puzzle from Trivial straight to Ambiguous. In that
3917 situation Solo has no remaining options but to throw the puzzle away
3918 and start again.)
3919
3920 A final strategy is to use the solver \e{during} puzzle
3921 construction: lay out a bit of the grid, run the solver to see what
3922 it allows you to deduce, and then lay out a bit more to allow the
3923 solver to make more progress. There are articles on the web that
3924 recommend constructing Sudoku puzzles by this method (which is
3925 completely the opposite way round to how Solo does it); for Sudoku
3926 it has the advantage that you get to specify your clue squares in
3927 advance (so you can have them make pretty patterns).
3928
3929 Rectangles uses a strategy along these lines. First it generates a
3930 grid by placing the actual rectangles; then it has to decide where
3931 in each rectangle to place a number. It uses a solver to help it
3932 place the numbers in such a way as to ensure a unique solution. It
3933 does this by means of running a test solver, but it runs the solver
3934 \e{before} it's placed any of the numbers \dash which means the
3935 solver must be capable of coping with uncertainty about exactly
3936 where the numbers are! It runs the solver as far as it can until it
3937 gets stuck; then it narrows down the possible positions of a number
3938 in order to allow the solver to make more progress, and so on. Most
3939 of the time this process terminates with the grid fully solved, at
3940 which point any remaining number-placement decisions can be made at
3941 random from the options not so far ruled out. Note that unlike the
3942 Net/Mines tweaking strategy described above, this algorithm does not
3943 require a checking run after it completes: if it finishes
3944 successfully at all, then it has definitely produced a uniquely
3945 soluble puzzle.
3946
3947 Most of the strategies described above are not 100% reliable. Each
3948 one has a failure rate: every so often it has to throw out the whole
3949 grid and generate a fresh one from scratch. (Solo's strategy would
3950 be the exception, if it weren't for the need to provide configurable
3951 difficulty levels.) Occasional failures are not a fundamental
3952 problem in this sort of work, however: it's just a question of
3953 dividing the grid generation time by the success rate (if it takes
3954 10ms to generate a candidate grid and 1/5 of them work, then it will
3955 take 50ms on average to generate a viable one), and seeing whether
3956 the expected time taken to \e{successfully} generate a puzzle is
3957 unacceptably slow. Dominosa's generator has a very low success rate
3958 (about 1 out of 20 candidate grids turn out to be usable, and if you
3959 think \e{that's} bad then go and look at the source code and find
3960 the comment showing what the figures were before the generation-time
3961 tweaks!), but the generator itself is very fast so this doesn't
3962 matter. Rectangles has a slower generator, but fails well under 50%
3963 of the time.
3964
3965 So don't be discouraged if you have an algorithm that doesn't always
3966 work: if it \e{nearly} always works, that's probably good enough.
3967 The one place where reliability is important is that your algorithm
3968 must never produce false positives: it must not claim a puzzle is
3969 soluble when it isn't. It can produce false negatives (failing to
3970 notice that a puzzle is soluble), and it can fail to generate a
3971 puzzle at all, provided it doesn't do either so often as to become
3972 slow.
3973
3974 One last piece of advice: for grid-based puzzles, when writing and
3975 testing your generation algorithm, it's almost always a good idea
3976 \e{not} to test it initially on a grid that's square (i.e.
3977 \cw{w==h}), because if the grid is square then you won't notice if
3978 you mistakenly write \c{h} instead of \c{w} (or vice versa)
3979 somewhere in the code. Use a rectangular grid for testing, and any
3980 size of grid will be likely to work after that.
3981
3982 \S{writing-textformats} Designing textual description formats
3983
3984 Another aspect of writing a puzzle which is worth putting some
3985 thought into is the design of the various text description formats:
3986 the format of the game parameter encoding, the game description
3987 encoding, and the move encoding.
3988
3989 The first two of these should be reasonably intuitive for a user to
3990 type in; so provide some flexibility where possible. Suppose, for
3991 example, your parameter format consists of two numbers separated by
3992 an \c{x} to specify the grid dimensions (\c{10x10} or \c{20x15}),
3993 and then has some suffixes to specify other aspects of the game
3994 type. It's almost always a good idea in this situation to arrange
3995 that \cw{decode_params()} can handle the suffixes appearing in any
3996 order, even if \cw{encode_params()} only ever generates them in one
3997 order.
3998
3999 These formats will also be expected to be reasonably stable: users
4000 will expect to be able to exchange game IDs with other users who
4001 aren't running exactly the same version of your game. So make them
4002 robust and stable: don't build too many assumptions into the game ID
4003 format which will have to be changed every time something subtle
4004 changes in the puzzle code.
4005
4006 \H{writing-howto} Common how-to questions
4007
4008 This section lists some common things people want to do when writing
4009 a puzzle, and describes how to achieve them within the Puzzles
4010 framework.
4011
4012 \S{writing-howto-cursor} Drawing objects at only one position
4013
4014 A common phenomenon is to have an object described in the
4015 \c{game_state} or the \c{game_ui} which can only be at one position.
4016 A cursor \dash probably specified in the \c{game_ui} \dash is a good
4017 example.
4018
4019 In the \c{game_ui}, it would \e{obviously} be silly to have an array
4020 covering the whole game grid with a boolean flag stating whether the
4021 cursor was at each position. Doing that would waste space, would
4022 make it difficult to find the cursor in order to do anything with
4023 it, and would introduce the potential for synchronisation bugs in
4024 which you ended up with two cursors or none. The obviously sensible
4025 way to store a cursor in the \c{game_ui} is to have fields directly
4026 encoding the cursor's coordinates.
4027
4028 However, it is a mistake to assume that the same logic applies to
4029 the \c{game_drawstate}. If you replicate the cursor position fields
4030 in the draw state, the redraw code will get very complicated. In the
4031 draw state, in fact, it \e{is} probably the right thing to have a
4032 cursor flag for every position in the grid. You probably have an
4033 array for the whole grid in the drawstate already (stating what is
4034 currently displayed in the window at each position); the sensible
4035 approach is to add a \q{cursor} flag to each element of that array.
4036 Then the main redraw loop will look something like this
4037 (pseudo-code):
4038
4039 \c for (y = 0; y < h; y++) {
4040 \c     for (x = 0; x < w; x++) {
4041 \c         int value = state->symbol_at_position[y][x];
4042 \c         if (x == ui->cursor_x && y == ui->cursor_y)
4043 \c             value |= CURSOR;
4044 \c         if (ds->symbol_at_position[y][x] != value) {
4045 \c             symbol_drawing_subroutine(dr, ds, x, y, value);
4046 \c             ds->symbol_at_position[y][x] = value;
4047 \c         }
4048 \c     }
4049 \c }
4050
4051 This loop is very simple, pretty hard to get wrong, and
4052 \e{automatically} deals both with erasing the previous cursor and
4053 drawing the new one, with no special case code required.
4054
4055 This type of loop is generally a sensible way to write a redraw
4056 function, in fact. The best thing is to ensure that the information
4057 stored in the draw state for each position tells you \e{everything}
4058 about what was drawn there. A good way to ensure that is to pass
4059 precisely the same information, and \e{only} that information, to a
4060 subroutine that does the actual drawing; then you know there's no
4061 additional information which affects the drawing but which you don't
4062 notice changes in.
4063
4064 \S{writing-keyboard-cursor} Implementing a keyboard-controlled cursor
4065
4066 It is often useful to provide a keyboard control method in a
4067 basically mouse-controlled game. A keyboard-controlled cursor is
4068 best implemented by storing its location in the \c{game_ui} (since
4069 if it were in the \c{game_state} then the user would have to
4070 separately undo every cursor move operation). So the procedure would
4071 be:
4072
4073 \b Put cursor position fields in the \c{game_ui}.
4074
4075 \b \cw{interpret_move()} responds to arrow keys by modifying the
4076 cursor position fields and returning \cw{""}.
4077
4078 \b \cw{interpret_move()} responds to some sort of fire button by
4079 actually performing a move based on the current cursor location.
4080
4081 \b You might want an additional \c{game_ui} field stating whether
4082 the cursor is currently visible, and having it disappear when a
4083 mouse action occurs (so that it doesn't clutter the display when not
4084 actually in use).
4085
4086 \b You might also want to automatically hide the cursor in
4087 \cw{changed_state()} when the current game state changes to one in
4088 which there is no move to make (which is the case in some types of
4089 completed game).
4090
4091 \b \cw{redraw()} draws the cursor using the technique described in
4092 \k{writing-howto-cursor}.
4093
4094 \S{writing-howto-dragging} Implementing draggable sprites
4095
4096 Some games have a user interface which involves dragging some sort
4097 of game element around using the mouse. If you need to show a
4098 graphic moving smoothly over the top of other graphics, use a
4099 blitter (see \k{drawing-blitter} for the blitter API) to save the
4100 background underneath it. The typical scenario goes:
4101
4102 \b Have a blitter field in the \c{game_drawstate}.
4103
4104 \b Set the blitter field to \cw{NULL} in the game's
4105 \cw{new_drawstate()} function, since you don't yet know how big the
4106 piece of saved background needs to be.
4107
4108 \b In the game's \cw{set_size()} function, once you know the size of
4109 the object you'll be dragging around the display and hence the
4110 required size of the blitter, actually allocate the blitter.
4111
4112 \b In \cw{free_drawstate()}, free the blitter if it's not \cw{NULL}.
4113
4114 \b In \cw{interpret_move()}, respond to mouse-down and mouse-drag
4115 events by updating some fields in the \cw{game_ui} which indicate
4116 that a drag is in progress.
4117
4118 \b At the \e{very end} of \cw{redraw()}, after all other drawing has
4119 been done, draw the moving object if there is one. First save the
4120 background under the object in the blitter; then set a clip
4121 rectangle covering precisely the area you just saved (just in case
4122 anti-aliasing or some other error causes your drawing to go beyond
4123 the area you saved). Then draw the object, and call \cw{unclip()}.
4124 Finally, set a flag in the \cw{game_drawstate} that indicates that
4125 the blitter needs restoring.
4126
4127 \b At the very start of \cw{redraw()}, before doing anything else at
4128 all, check the flag in the \cw{game_drawstate}, and if it says the
4129 blitter needs restoring then restore it. (Then clear the flag, so
4130 that this won't happen again in the next redraw if no moving object
4131 is drawn this time.)
4132
4133 This way, you will be able to write the rest of the redraw function
4134 completely ignoring the dragged object, as if it were floating above
4135 your bitmap and being completely separate.
4136
4137 \S{writing-ref-counting} Sharing large invariant data between all
4138 game states
4139
4140 In some puzzles, there is a large amount of data which never changes
4141 between game states. The array of numbers in Dominosa is a good
4142 example.
4143
4144 You \e{could} dynamically allocate a copy of that array in every
4145 \c{game_state}, and have \cw{dup_game()} make a fresh copy of it for
4146 every new \c{game_state}; but it would waste memory and time. A
4147 more efficient way is to use a reference-counted structure.
4148
4149 \b Define a structure type containing the data in question, and also
4150 containing an integer reference count.
4151
4152 \b Have a field in \c{game_state} which is a pointer to this
4153 structure.
4154
4155 \b In \cw{new_game()}, when creating a fresh game state at the start
4156 of a new game, create an instance of this structure, initialise it
4157 with the invariant data, and set its reference count to 1.
4158
4159 \b In \cw{dup_game()}, rather than making a copy of the structure
4160 for the new game state, simply set the new game state to point at
4161 the same copy of the structure, and increment its reference count.
4162
4163 \b In \cw{free_game()}, decrement the reference count in the
4164 structure pointed to by the game state; if the count reaches zero,
4165 free the structure.
4166
4167 This way, the invariant data will persist for only as long as it's
4168 genuinely needed; \e{as soon} as the last game state for a
4169 particular puzzle instance is freed, the invariant data for that
4170 puzzle will vanish as well. Reference counting is a very efficient
4171 form of garbage collection, when it works at all. (Which it does in
4172 this instance, of course, because there's no possibility of circular
4173 references.)
4174
4175 \S{writing-flash-types} Implementing multiple types of flash
4176
4177 In some games you need to flash in more than one different way.
4178 Mines, for example, flashes white when you win, and flashes red when
4179 you tread on a mine and die.
4180
4181 The simple way to do this is:
4182
4183 \b Have a field in the \c{game_ui} which describes the type of flash.
4184
4185 \b In \cw{flash_length()}, examine the old and new game states to
4186 decide whether a flash is required and what type. Write the type of
4187 flash to the \c{game_ui} field whenever you return non-zero.
4188
4189 \b In \cw{redraw()}, when you detect that \c{flash_time} is
4190 non-zero, examine the field in \c{game_ui} to decide which type of
4191 flash to draw.
4192
4193 \cw{redraw()} will never be called with \c{flash_time} non-zero
4194 unless \cw{flash_length()} was first called to tell the mid-end that
4195 a flash was required; so whenever \cw{redraw()} notices that
4196 \c{flash_time} is non-zero, you can be sure that the field in
4197 \c{game_ui} is correctly set.
4198
4199 \S{writing-move-anim} Animating game moves
4200
4201 A number of puzzle types benefit from a quick animation of each move
4202 you make.
4203
4204 For some games, such as Fifteen, this is particularly easy. Whenever
4205 \cw{redraw()} is called with \c{oldstate} non-\cw{NULL}, Fifteen
4206 simply compares the position of each tile in the two game states,
4207 and if the tile is not in the same place then it draws it some
4208 fraction of the way from its old position to its new position. This
4209 method copes automatically with undo.
4210
4211 Other games are less obvious. In Sixteen, for example, you can't
4212 just draw each tile a fraction of the way from its old to its new
4213 position: if you did that, the end tile would zip very rapidly past
4214 all the others to get to the other end and that would look silly.
4215 (Worse, it would look inconsistent if the end tile was drawn on top
4216 going one way and on the bottom going the other way.)
4217
4218 A useful trick here is to define a field or two in the game state
4219 that indicates what the last move was.
4220
4221 \b Add a \q{last move} field to the \c{game_state} (or two or more
4222 fields if the move is complex enough to need them).
4223
4224 \b \cw{new_game()} initialises this field to a null value for a new
4225 game state.
4226
4227 \b \cw{execute_move()} sets up the field to reflect the move it just
4228 performed.
4229
4230 \b \cw{redraw()} now needs to examine its \c{dir} parameter. If
4231 \c{dir} is positive, it determines the move being animated by
4232 looking at the last-move field in \c{newstate}; but if \c{dir} is
4233 negative, it has to look at the last-move field in \c{oldstate}, and
4234 invert whatever move it finds there.
4235
4236 Note also that Sixteen needs to store the \e{direction} of the move,
4237 because you can't quite determine it by examining the row or column
4238 in question. You can in almost all cases, but when the row is
4239 precisely two squares long it doesn't work since a move in either
4240 direction looks the same. (You could argue that since moving a
4241 2-element row left and right has the same effect, it doesn't matter
4242 which one you animate; but in fact it's very disorienting to click
4243 the arrow left and find the row moving right, and almost as bad to
4244 undo a move to the right and find the game animating \e{another}
4245 move to the right.)
4246
4247 \S{writing-conditional-anim} Animating drag operations
4248
4249 In Untangle, moves are made by dragging a node from an old position
4250 to a new position. Therefore, at the time when the move is initially
4251 made, it should not be animated, because the node has already been
4252 dragged to the right place and doesn't need moving there. However,
4253 it's nice to animate the same move if it's later undone or redone.
4254 This requires a bit of fiddling.
4255
4256 The obvious approach is to have a flag in the \c{game_ui} which
4257 inhibits move animation, and to set that flag in
4258 \cw{interpret_move()}. The question is, when would the flag be reset
4259 again? The obvious place to do so is \cw{changed_state()}, which
4260 will be called once per move. But it will be called \e{before}
4261 \cw{anim_length()}, so if it resets the flag then \cw{anim_length()}
4262 will never see the flag set at all.
4263
4264 The solution is to have \e{two} flags in a queue.
4265
4266 \b Define two flags in \c{game_ui}; let's call them \q{current} and
4267 \q{next}.
4268
4269 \b Set both to \cw{FALSE} in \c{new_ui()}.
4270
4271 \b When a drag operation completes in \cw{interpret_move()}, set the
4272 \q{next} flag to \cw{TRUE}.
4273
4274 \b Every time \cw{changed_state()} is called, set the value of
4275 \q{current} to the value in \q{next}, and then set the value of
4276 \q{next} to \cw{FALSE}.
4277
4278 \b That way, \q{current} will be \cw{TRUE} \e{after} a call to
4279 \cw{changed_state()} if and only if that call to
4280 \cw{changed_state()} was the result of a drag operation processed by
4281 \cw{interpret_move()}. Any other call to \cw{changed_state()}, due
4282 to an Undo or a Redo or a Restart or a Solve, will leave \q{current}
4283 \cw{FALSE}.
4284
4285 \b So now \cw{anim_length()} can request a move animation if and
4286 only if the \q{current} flag is \e{not} set.
4287
4288 \S{writing-cheating} Inhibiting the victory flash when Solve is used
4289
4290 Many games flash when you complete them, as a visual congratulation
4291 for having got to the end of the puzzle. It often seems like a good
4292 idea to disable that flash when the puzzle is brought to a solved
4293 state by means of the Solve operation.
4294
4295 This is easily done:
4296
4297 \b Add a \q{cheated} flag to the \c{game_state}.
4298
4299 \b Set this flag to \cw{FALSE} in \cw{new_game()}.
4300
4301 \b Have \cw{solve()} return a move description string which clearly
4302 identifies the move as a solve operation.
4303
4304 \b Have \cw{execute_move()} respond to that clear identification by
4305 setting the \q{cheated} flag in the returned \c{game_state}. The
4306 flag will then be propagated to all subsequent game states, even if
4307 the user continues fiddling with the game after it is solved.
4308
4309 \b \cw{flash_length()} now returns non-zero if \c{oldstate} is not
4310 completed and \c{newstate} is, \e{and} neither state has the
4311 \q{cheated} flag set.
4312
4313 \H{writing-testing} Things to test once your puzzle is written
4314
4315 Puzzle implementations written in this framework are self-testing as
4316 far as I could make them.
4317
4318 Textual game and move descriptions, for example, are generated and
4319 parsed as part of the normal process of play. Therefore, if you can
4320 make moves in the game \e{at all} you can be reasonably confident
4321 that the mid-end serialisation interface will function correctly and
4322 you will be able to save your game. (By contrast, if I'd stuck with
4323 a single \cw{make_move()} function performing the jobs of both
4324 \cw{interpret_move()} and \cw{execute_move()}, and had separate
4325 functions to encode and decode a game state in string form, then
4326 those functions would not be used during normal play; so they could
4327 have been completely broken, and you'd never know it until you tried
4328 to save the game \dash which would have meant you'd have to test
4329 game saving \e{extensively} and make sure to test every possible
4330 type of game state. As an added bonus, doing it the way I did leads
4331 to smaller save files.)
4332
4333 There is one exception to this, which is the string encoding of the
4334 \c{game_ui}. Most games do not store anything permanent in the
4335 \c{game_ui}, and hence do not need to put anything in its encode and
4336 decode functions; but if there is anything in there, you do need to
4337 test game loading and saving to ensure those functions work
4338 properly.
4339
4340 It's also worth testing undo and redo of all operations, to ensure
4341 that the redraw and the animations (if any) work properly. Failing
4342 to animate undo properly seems to be a common error.
4343
4344 Other than that, just use your common sense.