document shapes array
[netris.git] / curses.c
1 /*
2  * Netris -- A free networked version of T*tris
3  * Copyright (C) 1994-1996,1999  Mark H. Weaver <mhw@netris.org>
4  * 
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include "netris.h"
21
22 #include <sys/types.h>
23 #include <unistd.h>
24 #include <curses.h>
25 #include <string.h>
26 #include <stdlib.h>
27
28 #include "client.h"
29 #include "curses.h"
30 #include "util.h"
31 #include "board.h"
32 #include "msg.en.h"
33
34 #ifdef NCURSES_VERSION
35 # define HAVE_NCURSES
36 #endif
37
38 static MyEventType KeyGenFunc(EventGenRec *gen, MyEvent *event);
39 static EventGenRec keyGen = {
40         NULL, 0, FT_read, STDIN_FILENO, KeyGenFunc, EM_key
41 };
42
43 static int boardYPos[MAX_SCREENS], boardXPos[MAX_SCREENS];
44 static int boardSize[MAX_SCREENS];
45 //^^^struct
46 static int statusYPos, statusXPos;
47 static int messageYPos, messageXPos, messageHeight, messageWidth;
48 WINDOW *msgwin;
49 static int haveColor;
50 int PlayerDisp[MAX_SCREENS];
51
52 #define MSG_HEIGHT 64  //max history
53 char *message[MSG_HEIGHT];
54 char messages[MSG_HEIGHT][MSG_WIDTH];
55
56 static char *term_vi;  /* String to make cursor invisible */
57 static char *term_ve;  /* String to make cursor visible */
58
59 void InitScreens(void)
60 {
61         MySigSet oldMask;
62
63         GetTermcapInfo();
64
65         /*
66          * Block signals while initializing curses.  Otherwise a badly timed
67          * Ctrl-C during initialization might leave the terminal in a bad state.
68          */
69         BlockSignals(&oldMask, SIGINT, 0);
70         initscr();  //start curses
71
72 #ifdef CURSES_HACK
73         {
74                 extern char *CS;
75
76                 CS = 0;
77         }
78 #endif
79
80 #ifdef HAVE_NCURSES
81         haveColor = Sets.color && has_colors();
82         if (haveColor) {
83                 static struct {
84                         char type;
85                         short color;
86                 } myColorTable[] = {
87                         { BT_T, COLOR_WHITE },
88                         { BT_I, COLOR_BLUE },
89                         { BT_O, COLOR_MAGENTA },
90                         { BT_L, COLOR_CYAN },
91                         { BT_J, COLOR_YELLOW },
92                         { BT_S, COLOR_GREEN },
93                         { BT_Z, COLOR_RED },
94                         { BT_none, 0 }
95                 }; //myColorTable
96                 int i = 0;
97
98                 start_color();
99                 if (can_change_color()) {
100                         init_color (COLOR_YELLOW, 1000, 1000, 0);
101                 } //I've never worked on a color-changable terminal, so no idea..
102                 for (i = 0; myColorTable[i].type != BT_none; ++i)
103                         init_pair(myColorTable[i].type, COLOR_BLACK,
104                                 myColorTable[i].color);
105         } //haveColor
106 #else
107         haveColor = 0;
108 #endif
109
110         AtExit(CleanupScreens);        //restore everything when done
111         RestoreSignals(NULL, &oldMask);
112
113         cbreak();                      //no line buffering
114         noecho();
115 //      keypad(stdscr, TRUE);          //get arrow/functionkeys 'n stuff
116         OutputTermStr(term_vi, 0);
117         AddEventGen(&keyGen);          //key handler
118         signal(SIGWINCH, CatchWinCh);  //handle window resize
119 //  ioctl(STDIN_FILENO, KDSKBMODE, K_MEDIUMRAW);
120         standend();                    //normal text
121
122         memset(messages, 0, sizeof(messages)); //empty messages
123         {
124                 int i;
125                 for (i = 0; i<MSG_HEIGHT; i++)
126                         message[i] = messages[i];  //set pointers
127         }
128 }
129
130 void CleanupScreens(void)
131 {
132         RemoveEventGen(&keyGen);
133         endwin();                      //end curses
134         OutputTermStr(term_ve, 1);
135 }
136
137 void GetTermcapInfo(void)
138 {
139         char *term, *buf, *data;
140         int bufSize = 8192;
141         char scratch[1024];
142
143         if (!(term = getenv("TERM")))
144                 return;
145         if (tgetent(scratch, term) == 1) {
146                 /*
147                  * Make the buffer HUGE, since tgetstr is unsafe.
148                  * Allocate it on the heap too.
149                  */
150                 data = buf = malloc(bufSize);
151
152                 /*
153                  * There is no standard include file for tgetstr, no prototype
154                  * definitions.  I like casting better than using my own prototypes
155                  * because if I guess the prototype, I might be wrong, especially
156                  * with regards to "const".
157                  */
158                 term_vi = (char *)tgetstr("vi", &data);
159                 term_ve = (char *)tgetstr("ve", &data);
160
161                 /* Okay, so I'm paranoid; I just don't like unsafe routines */
162                 if (data > buf + bufSize)
163                         fatal("tgetstr overflow, you must have a very sick termcap");
164
165                 /* Trim off the unused portion of buffer */
166                 buf = realloc(buf, data - buf);
167         }
168
169         /*
170          * If that fails, use hardcoded vt220 codes.
171          * They don't seem to do anything bad on vt100's, so
172          * we'll try them just in case they work.
173          */
174         if (!term_vi || !term_ve) {
175                 static char *vts[] = {
176                         "vt100", "vt101", "vt102",
177                         "vt200", "vt220", "vt300",
178                         "vt320", "vt400", "vt420",
179                         "screen", "xterm", NULL
180                 };
181                 int i;
182
183                 for (i = 0; vts[i]; i++)
184                         if (!strcmp(term, vts[i])) {
185                                 term_vi = "\033[?25l";
186                                 term_ve = "\033[?25h";
187                                 break;
188                         }
189         }
190         if (!term_vi || !term_ve)
191                 term_vi = term_ve = NULL;
192 }
193
194 void OutputTermStr(char *str, int flush)
195 {
196         if (str) {
197                 fputs(str, stdout);
198                 if (flush) fflush(stdout);
199         }
200 }
201
202 void DrawTitle(void)
203 {
204         int rows, cols;
205         char s[255];
206
207 #ifdef HAVE_NCURSES
208         attrset(A_REVERSE);
209 #else
210         standout();
211 #endif
212         getmaxyx(stdscr, rows, cols);
213         sprintf(s, " NETRIS %s", version_string);
214         memset(&s[strlen(s)], ' ', 254 - strlen(s));
215         if (cols > 56 + strlen(version_string))
216                 memcpy(&s[cols - 48],
217                         "(C)1994-1996,1999 Mark H. Weaver, (C)2002 Shiar \0", 49);
218         else memcpy(&s[cols], "\0", 1);
219         mvaddstr(0, 0, s);
220         standend();     //normal text
221 }
222
223 void DrawBox(int x1, int y1, int x2, int y2)
224 { //draw grid
225         int y, x;
226
227         for (y = y1 + 1; y < y2; y++) {
228                 mvaddch(y, x1, Sets.ascii ? '|' : ACS_VLINE); //left
229                 mvaddch(y, x2, Sets.ascii ? '|' : ACS_VLINE); //right
230         } //draw vertical lines
231         move(y1, x1); //top
232         addch(Sets.ascii ? '+' : ACS_ULCORNER);
233         for (x = x1 + 1; x < x2; x++)
234                 addch(Sets.ascii ? '-' : ACS_HLINE);
235         addch(Sets.ascii ? '+' : ACS_URCORNER);
236         move(y2, x1); //bottom
237         addch(Sets.ascii ? '+' : ACS_LLCORNER);
238         for (x = x1 + 1; x < x2; x++)
239                 addch(Sets.ascii ? '-' : ACS_HLINE);
240         addch(Sets.ascii ? '+' : ACS_LRCORNER);
241 }
242
243 void DrawField(int scr)
244 { //draw field for player scr
245         if (!PlayerDisp[scr]) return; 
246         DrawBox(boardXPos[scr] - 1, boardYPos[scr] - Players[scr].boardVisible,
247                 boardXPos[scr] + boardSize[scr] * Players[scr].boardWidth, boardYPos[scr] + 1);
248         {
249                 char s[boardSize[scr]*Players[scr].boardWidth+1];
250
251                 if (Players[scr].host && Players[scr].host[0])
252                         snprintf(s, sizeof(s), " %s <%s> ",
253                                 Players[scr].name, Players[scr].host);
254                 else snprintf(s, sizeof(s), " %s ", Players[scr].name);
255                 s[sizeof(s)] = 0;
256                 if (haveColor && Players[scr].team > 0 && Players[scr].team <= 7)
257                         attrset(A_REVERSE | COLOR_PAIR(Players[scr].team + 1));
258                 mvaddstr(1, boardXPos[scr], s);
259                 if (haveColor) standend();
260         } //display playername/host
261
262         {
263                 int x, y;
264                 for (y = 0; y <= Players[scr].boardVisible; y++)
265                         for (x = 0; x <= Players[scr].boardWidth; x++)
266                                 PlotBlock(scr, y, x, GetBlock(scr, y, x));
267         } //draw field
268
269         ShowPause(scr);
270 }
271
272 void InitFields(void)
273 { //calculate positions of all fields
274         int scr, prevscr;
275         int y, x;
276         int spaceavail;
277
278         clear();
279         DrawTitle();
280         getmaxyx(stdscr, y, x);
281         boardSize[me] = 2;
282         boardXPos[me] = 1;
283         boardYPos[me] = 21;
284         PlayerDisp[me] = 1;
285         statusXPos = boardSize[me] * Players[me].boardWidth + 3;
286         statusYPos = 21;
287         ShowScore(me, Players[me].score);
288
289         messageXPos = 2;
290         messageYPos = 24;
291         messageWidth  = MIN(x - messageXPos - 2, MSG_WIDTH);
292         messageHeight = MIN(y - messageYPos - 1, MSG_HEIGHT);
293         if (messageHeight <= 0) {
294                 messageWidth = 27;
295                 messageHeight = y - 3;
296                 messageXPos = statusXPos + 16;
297                 messageYPos = 2;
298         } //messagebox doesn't fit below
299         DrawBox(messageXPos - 2, messageYPos - 1,
300                 messageXPos + messageWidth + 1, messageYPos+messageHeight);
301         if (msgwin = subwin(stdscr, messageHeight, messageWidth,
302                             messageYPos, messageXPos))
303                 scrollok(msgwin, 1);  //allow scrolling
304         wmove(msgwin, messageHeight - 2, 0);
305         for (scr = messageHeight - 2; scr >= 0; scr--) //display message history
306                 DisplayMessage(message[scr]);
307
308         spaceavail = x;
309         for (scr = 1; scr <= maxPlayer; scr++)
310                 spaceavail -= Players[scr].boardWidth+2;
311         prevscr = me;
312         for (scr = 1; scr < MAX_SCREENS; scr++) if (scr != me) {
313                 boardYPos[scr] = 21;
314                 boardXPos[scr] =
315                         boardXPos[prevscr] + 2 + boardSize[prevscr] * Players[prevscr].boardWidth;
316                 if (prevscr == me) {
317                         boardXPos[scr] += 15; //scorebar
318                         if (messageYPos < 24)
319                                 boardXPos[scr] += messageWidth + 4; //messagebox
320                         spaceavail -= boardXPos[scr] - 3;
321                 } //stuff before second player
322                 if (spaceavail >= 0) {
323                         boardSize[scr] = 2;
324                         spaceavail -= Players[scr].boardWidth;
325                 } //not enough space, half width
326                 else
327                         boardSize[scr] = 1;
328                 if (x < boardXPos[scr] + 1 + boardSize[scr] * Players[scr].boardWidth)
329                         PlayerDisp[scr] = 0; //field doesn't fit on screen
330                 else
331                         PlayerDisp[scr] = 1;
332                 prevscr = scr;
333         }
334         for (scr = 1; scr <= maxPlayer; scr++)
335                 DrawField(scr);
336 }
337
338 void CleanupScreen(int scr)
339 {
340 }
341
342 void DisplayMessage(char *p)
343 {
344         char s[MSG_WIDTH];
345         char *psearch;
346         char c;
347
348         memcpy(s, p, sizeof(s)-1);
349         s[MSG_WIDTH-1] = 0;
350         p = s;
351         while (psearch = strchr(p, '\\')) {
352                 *psearch = '\0';
353                 waddstr(msgwin, p);
354                 c = atoi(++psearch) + 1;
355                 if (haveColor) wattrset(msgwin, A_REVERSE | COLOR_PAIR(c));
356                 p = ++psearch;
357         } //search for color escapes (\)
358         waddstr(msgwin, p);
359         if (haveColor) wstandend(msgwin);
360         waddch(msgwin, '\n');
361 }
362
363 void Message(char *fmt, ...)
364 { //print game/bot message
365         va_list args;
366         char s[MSG_WIDTH];
367         char *p;
368         int i;
369
370         if (!messageHeight) return;
371         va_start(args, fmt);
372         vsnprintf(s, sizeof(s), fmt, args);
373         va_end(args);
374         p = message[MSG_HEIGHT - 1]; //save last pointer
375         for (i = MSG_HEIGHT - 1; i > 0; i--)
376                 message[i] = message[i - 1]; //scroll history
377         message[0] = p;
378         strcpy(p, s);
379
380         wmove(msgwin, messageHeight - 1, 0);
381         DisplayMessage(s);
382         wclrtoeol(msgwin);
383         wrefresh(msgwin);
384 }
385
386 void Messagetype(char c, int x, char *s)
387 { //show single typed character
388         if (c == 27) {
389                 mvwaddch(msgwin, messageHeight-1, (x+1) % (messageWidth-1), ' ');
390         } //escape
391         else {
392                 if (c == 13 || c == 127) //enter/backspace
393                         mvwaddch(msgwin, messageHeight - 1, (x+2) % (messageWidth-1),
394                                 x >= messageWidth-3 ? s[x - messageWidth + 3] : ' ');
395                 else //any character
396                         mvwaddch(msgwin, messageHeight - 1, x % (messageWidth-1), c);
397                 mvwaddch(msgwin, messageHeight - 1, (x+1) % (messageWidth-1), '_');
398         } //typing mode
399         wrefresh(msgwin);
400 }
401
402 void PlotBlock1(int y, int x, unsigned char type)
403 { //display block on screen
404         move(y, x);
405         if (type == BT_none) addstr("  ");
406         else if (type == BT_shadow) addstr("::");
407         else {
408 #ifdef HAVE_NCURSES
409                 if (Sets.standout) {
410                         if (haveColor) attrset(COLOR_PAIR(type & 15));
411                         else attrset(A_REVERSE);
412                 }
413 #endif
414                 switch (Sets.drawstyle) {
415                 case 2:
416                         switch (type & 192) {
417                         case 64:  //right neighbour
418                                 addstr("[["); break;
419                         case 128: //left
420                                 addstr("]]"); break;
421                         default:  //both/none
422                                 addstr("[]"); break;
423                         } //horizontal stickiness
424                         break; //ascii horizontally grouped
425                 case 3:
426                         switch (type & 240) {
427                         case 48:
428                                 addstr("||"); break; //middle
429                         case 64: case 80: case 96:
430                                 addstr("[="); break; //left end
431                         case 112:
432                                 addstr("|="); break;
433                         case 128: case 144: case 160:
434                                 addstr("=]"); break; //right end
435                         case 176:
436                                 addstr("=|"); break;
437                         case 192: case 208: case 224:
438                                 addstr("=="); break;
439                         default:
440                                 addstr("[]"); break; //top/bottom/mid
441                         } //neighbours
442                         break; //ascii semi-grouped
443                 case 7:
444                         switch (type & 240) {
445                         case  16: addch(ACS_ULCORNER); addch(ACS_URCORNER); break;//top end
446                         case  32: addch(ACS_LLCORNER); addch(ACS_LRCORNER); break;//bottom end
447                         case  48: addch(ACS_VLINE); addch(ACS_VLINE); break;    //vertical middle
448                         case  64: addch('['); addch(ACS_HLINE); break;          //left end
449                         case  80: addch(ACS_ULCORNER); addch(ACS_TTEE); break;  //top left corner
450                         case  96: addch(ACS_LLCORNER); addch(ACS_BTEE); break;  //bottom left corner
451                         case 112: addch(ACS_LTEE); addch(ACS_PLUS); break;      //vertical+right
452                         case 128: addch(ACS_HLINE); addch(']'); break;          //right end
453                         case 144: addch(ACS_TTEE); addch(ACS_URCORNER); break;  //top right corner
454                         case 160: addch(ACS_BTEE); addch(ACS_LRCORNER); break;  //bottom right corner
455                         case 176: addch(ACS_PLUS); addch(ACS_RTEE); break;      //vertical+left
456                         case 192: addch(ACS_HLINE); addch(ACS_HLINE); break;    //horizontal middle
457                         case 208: addch(ACS_TTEE); addch(ACS_TTEE); break;      //horizontal+down
458                         case 224: addch(ACS_BTEE); addch(ACS_BTEE); break;      //horizontal+up
459                         default:  addstr("[]"); break;
460                         } //neighbours
461                         break; //curses grouped
462                 default:
463                         addstr("[]");
464                         break; //ascii non-grouped
465                 } //draw block
466 #ifdef HAVE_NCURSES
467                 if (Sets.standout) standend();
468 #endif
469         } //display one brick
470 }
471 void PlotBlock1S(int y, int x, unsigned char type)
472 { //display block small
473         move(y, x);
474         if (type == BT_none) addch(' ');
475         else if (type == BT_shadow) addch(':');
476         else {
477                 if (Sets.standout) {
478 #ifdef HAVE_NCURSES
479                         if (haveColor)
480                                 attrset(COLOR_PAIR(type & 15));
481                         else attrset(A_REVERSE);
482 #endif
483                 }
484                 if ((type & 192) == 64)
485                         addch('[');
486                 else if ((type & 192) == 128)
487                         addch(']');
488                 else
489                         addch('|');
490 #ifdef HAVE_NCURSES
491                 if (Sets.standout) standend();
492 #endif
493         } //display one brick
494 }
495 void PlotBlock(int scr, int y, int x, unsigned char type)
496 {
497         if (y >= 0 && y < Players[scr].boardVisible
498          && x >= 0 && x < Players[scr].boardWidth) {
499                 if (boardSize[scr] > 1)
500                         PlotBlock1(boardYPos[scr] - y, boardXPos[scr] + 2*x, type);
501                 else
502                         PlotBlock1S(boardYPos[scr] - y, boardXPos[scr] + x, type);
503         } //on screen
504 }
505 void PlotBlockXY(int y, int x, unsigned char type)
506 { //Draw block at specified position on screen (not on field)
507         PlotBlock1(20 - y, 2 * x, type);
508 }
509
510 void ShowScore(int scr, struct _Score score)
511 { //show score stuff
512         float timer;
513
514         mvaddstr(13, statusXPos, MSG_NEXT " ");
515         mvaddstr(14, statusXPos + 5,  "        ");
516         ShapeIterate(Players[scr].nextShape, scr, 8,
517                 statusXPos/2 + (Players[scr].nextShape/4 == 5 ? 3 : 4),
518                 GlanceFunc); //draw; stick one more to the left
519         mvprintw(3, statusXPos, MSG_LEVEL, score.level);
520         mvprintw(5, statusXPos, MSG_SCORE, score.score);
521         mvprintw(6, statusXPos, MSG_LINES, score.lines);
522         timer = CurTimeval() / 1e6;
523         if (timer > 4) {
524                 mvprintw(9, statusXPos, MSG_PPM, score.pieces * 60 / timer);
525                 if (score.lines > 0) {
526                         mvprintw(7, statusXPos, MSG_YIELD, 100 * score.adds / score.lines);
527                         mvprintw(10, statusXPos, MSG_APM, score.adds * 60 / timer);
528                 }
529         } //display [ap]pm
530         else {
531                 int i;
532                 for (i = 7; i <= 10; i++)
533                         mvaddstr(i, statusXPos, "             ");
534         } //too early to display stats, remove old..
535 }
536
537 void FieldMessage(int playa, char *message)
538 { //put a message over playa's field
539         if (!PlayerDisp[playa]) return;
540         if (message) {
541                 char s[MAX_BOARD_WIDTH+1];
542                 memset(s, ' ', MAX_BOARD_WIDTH);
543                 memcpy(&s[(boardSize[playa] * Players[playa].boardWidth / 2) - (strlen(message) / 2)],
544                         message, strlen(message));
545                 s[boardSize[playa] * Players[playa].boardWidth] = 0;
546 #ifdef HAVE_NCURSES
547                 attrset(A_REVERSE);
548 #else
549                 standout();
550 #endif
551                 mvprintw(boardYPos[playa] - Players[playa].boardVisible / 2,
552                         boardXPos[playa], "%s", s);
553                 standend();
554         } //display
555         else {
556                 int x, y;
557                 y = Players[playa].boardVisible / 2;
558                 for (x = 0; x <= Players[playa].boardWidth; x++)
559                         PlotBlock(playa, y, x, GetBlock(playa, y, x));
560         } //restore field
561 }
562
563 void ShowPause(int playa)
564 { //put paused over player's field
565         if (Players[playa].alive > 0)
566                 if (Players[playa].flags & SCF_paused)
567                         if (Game.started > 1)
568                                 FieldMessage(playa, boardSize[playa] > 1 ? "P A U S E D" : "PAUSED");
569                         else
570                                 FieldMessage(playa,
571                                         boardSize[playa] > 1 ? "N O T  R E A D Y" : "NOT  READY");
572                 else
573                         if (Game.started > 1)
574                                 FieldMessage(playa, NULL);
575                         else
576                                 FieldMessage(playa, boardSize[playa] > 1 ? "R E A D Y" : "READY");
577         else if (!Players[playa].alive)
578                 FieldMessage(playa,
579                         boardSize[playa] > 1 ? "G A M E  O V E R" : "GAME  OVER");
580         else
581                 FieldMessage(playa, boardSize[playa] > 1 ? "E M P T Y" : "EMPTY");
582 }
583
584
585 void ShowTime(void)
586 { //display timer
587         mvprintw(statusYPos, statusXPos, "timer %7.0f ", CurTimeval() / 1e6);
588 }
589
590 void ScheduleFullRedraw(void)
591 {
592         touchwin(stdscr);
593 }
594
595 void CatchWinCh(int sig)
596 { //handle window resize
597         endwin();      //exit curses
598         refresh();     //and reinit display (with different sizes)
599         InitFields();  //manually redraw everything
600         refresh();     //refresh
601 }
602
603 static MyEventType KeyGenFunc(EventGenRec *gen, MyEvent *event)
604 { //read keypresses
605         if (MyRead(gen->fd, &event->u.key, 1))
606                 return E_key;
607         else
608                 return E_none;
609 }
610