801331bdd06b14b3264ff1fbe5818daba780a44c
[open-adventure.git] / misc.c
1 #include <unistd.h>
2 #include <stdlib.h>
3 #include <stdio.h>
4 #include <string.h>
5 #include <sys/time.h>
6 #include <ctype.h>
7
8 #include "advent.h"
9 #include "database.h"
10 #include "linenoise/linenoise.h"
11 #include "newdb.h"
12
13 void* xmalloc(size_t size)
14 {
15   void* ptr = malloc(size);
16   if (ptr == NULL)
17     {
18       fprintf(stderr, "Out of memory!\n");
19       exit(EXIT_FAILURE);
20     }
21   return(ptr);
22 }
23
24 void packed_to_token(long packed, char token[6])
25 {
26   for (int i = 0; i < 5; ++i)
27     {
28       char advent = (packed >> i * 6) & 63;
29       token[i] = advent_to_ascii[advent];
30     }
31   token[5] = '\0';
32 }
33
34 /*  I/O routines (SPEAK, PSPEAK, RSPEAK, SETPRM, GETIN, YES) */
35
36 void newspeak(char* msg)
37 {
38   // Do nothing if we got a null pointer.
39   if (msg == NULL)
40     return;
41
42   // Do nothing if we got an empty string.
43   if (strlen(msg) == 0)
44     return;
45
46   // Print a newline if the global game.blklin says to.
47   if (game.blklin == true)
48     printf("\n");
49
50   // Create a copy of our string, so we can edit it.
51   char* copy = (char*) xmalloc(strlen(msg) + 1);
52   strncpy(copy, msg, strlen(msg) + 1);
53
54   // Staging area for stringified parameters.
55   char parameters[5][100]; // FIXME: to be replaced with dynamic allocation
56  
57   // Handle format specifiers (including the custom %C, %L, %S) by adjusting the parameter accordingly, and replacing the specifier with %s.
58   int pi = 0; // parameter index
59   for (int i = 0; i < strlen(msg); ++i)
60     {
61       if (msg[i] == '%')
62         {
63           ++pi;
64
65           // Integer specifier. In order to accommodate the fact that PARMS can have both legitimate integers *and* packed tokens, stringify everything. Future work may eliminate the need for this.
66           if (msg[i + 1] == 'd')
67             {
68               copy[i + 1] = 's';
69               sprintf(parameters[pi], "%d", PARMS[pi]);
70             }
71
72           // Unmodified string specifier.
73           if (msg[i + 1] == 's')
74             {
75               packed_to_token(PARMS[pi], parameters[pi]);
76             }
77
78           // Singular/plural specifier.
79           if (msg[i + 1] == 'S')
80             {
81               copy[i + 1] = 's';
82               if (PARMS[pi - 1] > 1) // look at the *previous* parameter (which by necessity must be numeric)
83                 {
84                   sprintf(parameters[pi], "%s", "s");
85                 }
86               else
87                 {
88                   sprintf(parameters[pi], "%s", "");
89                 }
90             }
91
92           // All-lowercase specifier.
93           if (msg[i + 1] == 'L')
94             {
95               copy[i + 1] = 's';
96               packed_to_token(PARMS[pi], parameters[pi]);
97               for (int i = 0; i < strlen(parameters[pi]); ++i)
98                 {
99                   parameters[pi][i] = tolower(parameters[pi][i]);
100                 }
101             }
102
103           // First char uppercase, rest lowercase.
104           if (msg[i + 1] == 'C')
105             {
106               copy[i + 1] = 's';
107               packed_to_token(PARMS[pi], parameters[pi]);
108               for (int i = 0; i < strlen(parameters[pi]); ++i)
109                 {
110                   parameters[pi][i] = tolower(parameters[pi][i]);
111                 }
112               parameters[pi][0] = toupper(parameters[pi][0]);
113             }
114         }
115     }
116
117   // Render the final string.
118   char rendered[2000]; // FIXME: to be replaced with dynamic allocation
119   sprintf(&rendered, copy, parameters[1], parameters[2], parameters[3], parameters[4]); // FIXME: to be replaced with vsprintf()
120
121   // Print the message.
122   printf("%s\n", rendered);
123
124   free(copy);
125 }
126
127 void PSPEAK(vocab_t msg,int skip)
128 /*  Find the skip+1st message from msg and print it.  msg should be
129  *  the index of the inventory message for object.  (INVEN+N+1 message
130  *  is game.prop=N message). */
131 {
132   if (skip >= 0)
133     newspeak(object_descriptions[msg].longs[skip]);
134   else
135     newspeak(object_descriptions[msg].inventory);
136 }
137
138 void RSPEAK(vocab_t i)
139 /* Print the i-th "random" message (section 6 of database). */
140 {
141   newspeak(arbitrary_messages[i]);
142 }
143
144 void SETPRM(long first, long p1, long p2)
145 /*  Stores parameters into the PRMCOM parms array for use by speak.  P1 and P2
146  *  are stored into PARMS(first) and PARMS(first+1). */
147 {
148     if (first >= MAXPARMS)
149         BUG(29);
150     else {
151         PARMS[first] = p1;
152         PARMS[first+1] = p2;
153     }
154 }
155
156 bool GETIN(FILE *input,
157             long *pword1, long *pword1x, 
158             long *pword2, long *pword2x) 
159 /*  Get a command from the adventurer.  Snarf out the first word, pad it with
160  *  blanks, and return it in WORD1.  Chars 6 thru 10 are returned in WORD1X, in
161  *  case we need to print out the whole word in an error message.  Any number of
162  *  blanks may follow the word.  If a second word appears, it is returned in
163  *  WORD2 (chars 6 thru 10 in WORD2X), else WORD2 is -1. */
164 {
165     long junk;
166
167     for (;;) {
168         if (game.blklin)
169             TYPE0();
170         if (!MAPLIN(input))
171             return false;
172         *pword1=GETTXT(true,true,true);
173         if (game.blklin && *pword1 < 0)
174             continue;
175         *pword1x=GETTXT(false,true,true);
176         do {    
177             junk=GETTXT(false,true,true);
178         } while 
179             (junk > 0);
180         *pword2=GETTXT(true,true,true);
181         *pword2x=GETTXT(false,true,true);
182         do {
183             junk=GETTXT(false,true,true);
184         } while 
185             (junk > 0);
186         if (GETTXT(true,true,true) <= 0)
187             return true;
188         RSPEAK(53);
189     }
190 }
191
192 long YES(FILE *input, vocab_t x, vocab_t y, vocab_t z)
193 /*  Print message X, wait for yes/no answer.  If yes, print Y and return true;
194  *  if no, print Z and return false. */
195 {
196     token_t reply, junk1, junk2, junk3;
197
198     for (;;) {
199         RSPEAK(x);
200         GETIN(input, &reply, &junk1, &junk2, &junk3);
201         if (reply == MAKEWD(250519) || reply == MAKEWD(25)) {
202             RSPEAK(y);
203             return true;
204         }
205         if (reply == MAKEWD(1415) || reply == MAKEWD(14)) {
206             RSPEAK(z);
207             return false;
208         }
209         RSPEAK(185);
210     }
211 }
212
213 /*  Line-parsing routines (GETTXT, MAKEWD, PUTTXT, SHFTXT, TYPE0) */
214
215 long GETTXT(bool skip, bool onewrd, bool upper)
216 /*  Take characters from an input line and pack them into 30-bit words.
217  *  Skip says to skip leading blanks.  ONEWRD says stop if we come to a
218  *  blank.  UPPER says to map all letters to uppercase.  If we reach the
219  *  end of the line, the word is filled up with blanks (which encode as 0's).
220  *  If we're already at end of line when TEXT is called, we return -1. */
221 {
222     long text;
223     static long splitting = -1;
224
225     if (LNPOSN != splitting)
226         splitting = -1;
227     text= -1;
228     while (true) {
229         if (LNPOSN > LNLENG)
230             return(text);
231         if ((!skip) || INLINE[LNPOSN] != 0)
232             break;
233         ++LNPOSN;
234     }
235
236     text=0;
237     for (int I=1; I<=TOKLEN; I++) {
238         text=text*64;
239         if (LNPOSN > LNLENG || (onewrd && INLINE[LNPOSN] == 0))
240             continue;
241         char current=INLINE[LNPOSN];
242         if (current < ascii_to_advent['%']) {
243             splitting = -1;
244             if (upper && current >= ascii_to_advent['a'])
245                 current=current-26;
246             text=text+current;
247             ++LNPOSN;
248             continue;
249         }
250         if (splitting != LNPOSN) {
251             text=text+ascii_to_advent['%'];
252             splitting = LNPOSN;
253             continue;
254         }
255
256         text=text+current-ascii_to_advent['%'];
257         splitting = -1;
258         ++LNPOSN;
259     }
260
261     return text;
262 }
263
264 token_t MAKEWD(long letters)
265 /*  Combine TOKLEN (currently 5) uppercase letters (represented by
266  *  pairs of decimal digits in lettrs) to form a 30-bit value matching
267  *  the one that GETTXT would return given those characters plus
268  *  trailing blanks.  Caution: lettrs will overflow 31 bits if
269  *  5-letter word starts with V-Z.  As a kludgey workaround, you can
270  *  increment a letter by 5 by adding 50 to the next pair of
271  *  digits. */
272 {
273     long i = 1, word = 0;
274
275     for (long k=letters; k != 0; k=k/100) {
276         word=word+i*(MOD(k,50)+10);
277         i=i*64;
278         if (MOD(k,100) > 50)word=word+i*5;
279     }
280     i=64L*64L*64L*64L*64L/i;
281     word=word*i;
282     return word;
283 }
284
285 void PUTTXT(token_t word, long *state, long casemake)
286 /*  Unpack the 30-bit value in word to obtain up to TOKLEN (currently
287  *  5) integer-encoded chars, and store them in inline starting at
288  *  LNPOSN.  If LNLENG>=LNPOSN, shift existing characters to the right
289  *  to make room.  STATE will be zero when puttxt is called with the
290  *  first of a sequence of words, but is thereafter unchanged by the
291  *  caller, so PUTTXT can use it to maintain state across calls.
292  *  LNPOSN and LNLENG are incremented by the number of chars stored.
293  *  If CASEMAKE=1, all letters are made uppercase; if -1, lowercase; if 0,
294  *  as is.  any other value for case is the same as 0 but also causes
295  *  trailing blanks to be included (in anticipation of subsequent
296  *  additional text). */
297 {
298     long alph1, alph2, byte, div, i, w;
299
300     alph1=13*casemake+24;
301     alph2=26*labs(casemake)+alph1;
302     if (labs(casemake) > 1)
303         alph1=alph2;
304     /*  alph1&2 define range of wrong-case chars, 11-36 or 37-62 or empty. */
305     div=64L*64L*64L*64L;
306     w=word;
307     for (i=1; i<=TOKLEN; i++) 
308     {
309         if (w <= 0 && *state == 0 && labs(casemake) <= 1)
310             return;
311         byte=w/div;
312         w=(w-byte*div)*64;
313         if (!(*state != 0 || byte != ascii_to_advent['%'])) {
314             *state=ascii_to_advent['%'];
315             continue;
316         }
317         SHFTXT(LNPOSN,1);
318         *state=*state+byte;
319         if (*state < alph2 && *state >= alph1)*state=*state-26*casemake;
320         INLINE[LNPOSN]=*state;
321         ++LNPOSN;
322         *state=0;
323     }
324 }
325 #define PUTTXT(WORD,STATE,CASE) fPUTTXT(WORD,&STATE,CASE)
326
327 void SHFTXT(long from, long delta) 
328 /*  Move INLINE(N) to INLINE(N+DELTA) for N=FROM,LNLENG.  Delta can be
329  *  negative.  LNLENG is updated; LNPOSN is not changed. */
330 {
331     long I, k, j;
332
333     if (!(LNLENG < from || delta == 0)) {
334         for (I=from; I<=LNLENG; I++) {
335             k=I;
336             if (delta > 0)
337                 k=from+LNLENG-I;
338             j=k+delta;
339             INLINE[j]=INLINE[k];
340         }
341     }
342     LNLENG=LNLENG+delta;
343 }
344
345 void TYPE0(void)
346 /*  Type a blank line.  This procedure is provided as a convenience for callers
347  *  who otherwise have no use for MAPCOM. */
348 {
349     long temp;
350
351     temp=LNLENG;
352     LNLENG=0;
353     TYPE();
354     LNLENG=temp;
355     return;
356 }
357
358 /*  Data structure  routines */
359
360 long VOCAB(long id, long init) 
361 /*  Look up ID in the vocabulary (ATAB) and return its "definition" (KTAB), or
362  *  -1 if not found.  If INIT is positive, this is an initialisation call setting
363  *  up a keyword variable, and not finding it constitutes a bug.  It also means
364  *  that only KTAB values which taken over 1000 equal INIT may be considered.
365  *  (Thus "STEPS", which is a motion verb as well as an object, may be located
366  *  as an object.)  And it also means the KTAB value is taken modulo 1000. */
367 {
368     long i, lexeme;
369
370     for (i=1; i<=TABSIZ; i++) {
371         if (KTAB[i] == -1) {
372             lexeme= -1;
373             if (init < 0)
374                 return(lexeme);
375             BUG(5);
376         }
377         if (init >= 0 && KTAB[i]/1000 != init) 
378             continue;
379         if (ATAB[i] == id) {
380             lexeme=KTAB[i];
381             if (init >= 0)
382                 lexeme=MOD(lexeme,1000);
383             return(lexeme);
384         }
385     }
386     BUG(21);
387 }
388
389 void DSTROY(long object)
390 /*  Permanently eliminate "object" by moving to a non-existent location. */
391 {
392     MOVE(object,0);
393 }
394
395 void JUGGLE(long object)
396 /*  Juggle an object by picking it up and putting it down again, the purpose
397  *  being to get the object to the front of the chain of things at its loc. */
398 {
399     long i, j;
400
401     i=game.place[object];
402     j=game.fixed[object];
403     MOVE(object,i);
404     MOVE(object+NOBJECTS,j);
405 }
406
407 void MOVE(long object, long where)
408 /*  Place any object anywhere by picking it up and dropping it.  May
409  *  already be toting, in which case the carry is a no-op.  Mustn't
410  *  pick up objects which are not at any loc, since carry wants to
411  *  remove objects from game.atloc chains. */
412 {
413     long from;
414
415     if (object > NOBJECTS) 
416         from=game.fixed[object-NOBJECTS];
417     else
418         from=game.place[object];
419     if (from > 0 && from <= 300)
420         CARRY(object,from);
421     DROP(object,where);
422 }
423
424 long PUT(long object, long where, long pval)
425 /*  PUT is the same as MOVE, except it returns a value used to set up the
426  *  negated game.prop values for the repository objects. */
427 {
428     MOVE(object,where);
429     return (-1)-pval;;
430 }
431
432 void CARRY(long object, long where) 
433 /*  Start toting an object, removing it from the list of things at its former
434  *  location.  Incr holdng unless it was already being toted.  If object>NOBJECTS
435  *  (moving "fixed" second loc), don't change game.place or game.holdng. */
436 {
437     long temp;
438
439     if (object <= NOBJECTS) {
440         if (game.place[object] == -1)
441             return;
442         game.place[object]= -1;
443         ++game.holdng;
444     }
445     if (game.atloc[where] == object) {
446         game.atloc[where]=game.link[object];
447         return;
448     }
449     temp=game.atloc[where];
450     while (game.link[temp] != object) {
451         temp=game.link[temp];
452     }
453     game.link[temp]=game.link[object];
454 }
455
456 void DROP(long object, long where)
457 /*  Place an object at a given loc, prefixing it onto the game.atloc list.  Decr
458  *  game.holdng if the object was being toted. */
459 {
460     if (object > NOBJECTS)
461         game.fixed[object-NOBJECTS] = where;
462     else
463     {
464         if (game.place[object] == -1)
465             --game.holdng;
466         game.place[object] = where;
467     }
468     if (where <= 0)
469         return;
470     game.link[object] = game.atloc[where];
471     game.atloc[where] = object;
472 }
473
474 long ATDWRF(long where)
475 /*  Return the index of first dwarf at the given location, zero if no dwarf is
476  *  there (or if dwarves not active yet), -1 if all dwarves are dead.  Ignore
477  *  the pirate (6th dwarf). */
478 {
479     long at, i;
480
481     at =0;
482     if (game.dflag < 2)
483         return(at);
484     at = -1;
485     for (i=1; i<=NDWARVES-1; i++) {
486         if (game.dloc[i] == where)
487             return i;
488         if (game.dloc[i] != 0)
489             at=0;
490     }
491     return(at);
492 }
493
494 /*  Utility routines (SETBIT, TSTBIT, set_seed, get_next_lcg_value,
495  *  randrange, RNDVOC, BUG) */
496
497 long SETBIT(long bit)
498 /*  Returns 2**bit for use in constructing bit-masks. */
499 {
500     return(1 << bit);
501 }
502
503 bool TSTBIT(long mask, int bit)
504 /*  Returns true if the specified bit is set in the mask. */
505 {
506     return (mask & (1 << bit)) != 0;
507 }
508
509 void set_seed(long seedval)
510 /* Set the LCG seed */
511 {
512     lcgstate.x = (unsigned long) seedval % lcgstate.m;
513 }
514
515 unsigned long get_next_lcg_value(void)
516 /* Return the LCG's current value, and then iterate it. */
517 {
518     unsigned long old_x = lcgstate.x;
519     lcgstate.x = (lcgstate.a * lcgstate.x + lcgstate.c) % lcgstate.m;
520     return old_x;
521 }
522
523 long randrange(long range)
524 /* Return a random integer from [0, range). */
525 {
526     return range * get_next_lcg_value() / lcgstate.m;
527 }
528
529 long RNDVOC(long second, long force)
530 /*  Searches the vocabulary ATAB for a word whose second character is
531  *  char, and changes that word such that each of the other four
532  *  characters is a random letter.  If force is non-zero, it is used
533  *  as the new word.  Returns the new word. */
534 {
535     long rnd = force;
536
537     if (rnd == 0) {
538         for (int i = 1; i <= 5; i++) {
539             long j = 11 + randrange(26);
540             if (i == 2)
541                 j = second;
542             rnd = rnd * 64 + j;
543         }
544     }
545
546     long div = 64L * 64L * 64L;
547     for (int i = 1; i <= TABSIZ; i++) {
548         if (MOD(ATAB[i]/div, 64L) == second)
549         {
550             ATAB[i] = rnd;
551             break;
552         }
553     }
554
555     return rnd;
556 }
557
558 void BUG(long num)
559 /*  The following conditions are currently considered fatal bugs.  Numbers < 20
560  *  are detected while reading the database; the others occur at "run time".
561  *      0       Message line > 70 characters
562  *      1       Null line in message
563  *      2       Too many words of messages
564  *      3       Too many travel options
565  *      4       Too many vocabulary words
566  *      5       Required vocabulary word not found
567  *      6       Too many RTEXT messages
568  *      7       Too many hints
569  *      8       Location has cond bit being set twice
570  *      9       Invalid section number in database
571  *      10      Too many locations
572  *      11      Too many class or turn messages
573  *      20      Special travel (500>L>300) exceeds goto list
574  *      21      Ran off end of vocabulary table
575  *      22      Vocabulary type (N/1000) not between 0 and 3
576  *      23      Intransitive action verb exceeds goto list
577  *      24      Transitive action verb exceeds goto list
578  *      25      Conditional travel entry with no alternative
579  *      26      Location has no travel entries
580  *      27      Hint number exceeds goto list
581  *      28      Invalid month returned by date function
582  *      29      Too many parameters given to SETPRM */
583 {
584
585     printf("Fatal error %ld.  See source code for interpretation.\n", num);
586     exit(0);
587 }
588
589 /*  Machine dependent routines (MAPLIN, TYPE, SAVEIO) */
590
591 bool MAPLIN(FILE *fp)
592 {
593     long i, val;
594     bool eof;
595
596     /*  Read a line of input, from the specified input source,
597      *  translate the chars to integers in the range 0-126 and store
598      *  them in the common array "INLINE".  Integer values are as follows:
599      *     0   = space [ASCII CODE 40 octal, 32 decimal]
600      *    1-2  = !" [ASCII 41-42 octal, 33-34 decimal]
601      *    3-10 = '()*+,-. [ASCII 47-56 octal, 39-46 decimal]
602      *   11-36 = upper-case letters
603      *   37-62 = lower-case letters
604      *    63   = percent (%) [ASCII 45 octal, 37 decimal]
605      *   64-73 = digits, 0 through 9
606      *  Remaining characters can be translated any way that is convenient;
607      *  The "TYPE" routine below is used to map them back to characters when
608      *  necessary.  The above mappings are required so that certain special
609      *  characters are known to fit in 6 bits and/or can be easily spotted.
610      *  Array elements beyond the end of the line should be filled with 0,
611      *  and LNLENG should be set to the index of the last character.
612      *
613      *  If the data file uses a character other than space (e.g., tab) to
614      *  separate numbers, that character should also translate to 0.
615      *
616      *  This procedure may use the map1,map2 arrays to maintain static data for
617      *  the mapping.  MAP2(1) is set to 0 when the program starts
618      *  and is not changed thereafter unless the routines on this page choose
619      *  to do so. */
620
621     if (!oldstyle && !isatty(1))
622         fputs("> ", stdout);
623     do {
624         if (oldstyle) {
625             IGNORE(fgets(rawbuf,sizeof(rawbuf)-1,fp));
626             eof = (feof(fp));
627         } else {
628             char *cp = linenoise("> ");
629             eof = (cp == NULL);
630             if (!eof) {
631                 strncpy(rawbuf, cp, sizeof(rawbuf)-1);
632                 linenoiseHistoryAdd(rawbuf);
633                 strncat(rawbuf, "\n", sizeof(rawbuf)-1);
634                 linenoiseFree(cp);
635             }
636         }
637     } while
638             (!eof && rawbuf[0] == '#');
639     if (eof) {
640         if (logfp && fp == stdin)
641             fclose(logfp);
642         return false;
643     } else {
644         if (logfp && fp == stdin)
645             IGNORE(fputs(rawbuf, logfp));
646         else if (!isatty(0))
647             IGNORE(fputs(rawbuf, stdout));
648         strcpy(INLINE+1, rawbuf);
649         LNLENG=0;
650         for (i=1; i<=(long)sizeof(INLINE) && INLINE[i]!=0; i++) {
651             val=INLINE[i];
652             INLINE[i]=ascii_to_advent[val];
653             if (INLINE[i] != 0)
654                 LNLENG=i;
655         }
656         LNPOSN=1;
657         return true;
658     }
659 }
660
661 void TYPE(void)
662 /*  Type the first "LNLENG" characters stored in inline, mapping them
663  *  from integers to text per the rules described above.  INLINE
664  *  may be changed by this routine. */
665 {
666     long i;
667
668     if (LNLENG == 0) {
669         printf("\n");
670         return;
671     }
672
673     for (i=1; i<=LNLENG; i++) {
674         INLINE[i]=advent_to_ascii[INLINE[i]];
675     }
676     INLINE[LNLENG+1]=0;
677     printf("%s\n", INLINE+1);
678     return;
679 }
680
681 void DATIME(long* d, long* t)
682 {
683     struct timeval tv;
684     gettimeofday(&tv, NULL);
685     *d = (long) tv.tv_sec;
686     *t = (long) tv.tv_usec;
687 }
688
689 long MOD(long n, long m) 
690 {
691     return(n%m);
692 }