Animate both legs of Lion move
[xboard.git] / board.c
1 /*
2  * board.c -- platform-independent drawing code for XBoard
3  *
4  * Copyright 1991 by Digital Equipment Corporation, Maynard,
5  * Massachusetts.
6  *
7  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005, 2006,
8  * 2007, 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
9  *
10  * The following terms apply to Digital Equipment Corporation's copyright
11  * interest in XBoard:
12  * ------------------------------------------------------------------------
13  * All Rights Reserved
14  *
15  * Permission to use, copy, modify, and distribute this software and its
16  * documentation for any purpose and without fee is hereby granted,
17  * provided that the above copyright notice appear in all copies and that
18  * both that copyright notice and this permission notice appear in
19  * supporting documentation, and that the name of Digital not be
20  * used in advertising or publicity pertaining to distribution of the
21  * software without specific, written prior permission.
22  *
23  * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
24  * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
25  * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
26  * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
27  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
28  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
29  * SOFTWARE.
30  * ------------------------------------------------------------------------
31  *
32  * The following terms apply to the enhanced version of XBoard
33  * distributed by the Free Software Foundation:
34  * ------------------------------------------------------------------------
35  *
36  * GNU XBoard is free software: you can redistribute it and/or modify
37  * it under the terms of the GNU General Public License as published by
38  * the Free Software Foundation, either version 3 of the License, or (at
39  * your option) any later version.
40  *
41  * GNU XBoard is distributed in the hope that it will be useful, but
42  * WITHOUT ANY WARRANTY; without even the implied warranty of
43  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
44  * General Public License for more details.
45  *
46  * You should have received a copy of the GNU General Public License
47  * along with this program. If not, see http://www.gnu.org/licenses/.  *
48  *
49  *------------------------------------------------------------------------
50  ** See the file ChangeLog for a revision history.  */
51
52 #define HIGHDRAG 1
53
54 #include "config.h"
55
56 #include <stdio.h>
57 #include <ctype.h>
58 #include <signal.h>
59 #include <errno.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <pwd.h>
63 #include <math.h>
64
65 #if STDC_HEADERS
66 # include <stdlib.h>
67 # include <string.h>
68 #else /* not STDC_HEADERS */
69 extern char *getenv();
70 # if HAVE_STRING_H
71 #  include <string.h>
72 # else /* not HAVE_STRING_H */
73 #  include <strings.h>
74 # endif /* not HAVE_STRING_H */
75 #endif /* not STDC_HEADERS */
76
77 #if TIME_WITH_SYS_TIME
78 # include <sys/time.h>
79 # include <time.h>
80 #else
81 # if HAVE_SYS_TIME_H
82 #  include <sys/time.h>
83 # else
84 #  include <time.h>
85 # endif
86 #endif
87
88 #if HAVE_UNISTD_H
89 # include <unistd.h>
90 #endif
91
92 #if HAVE_SYS_WAIT_H
93 # include <sys/wait.h>
94 #endif
95
96 #include "common.h"
97 #include "frontend.h"
98 #include "backend.h"
99 #include "xboard2.h"
100 #include "moves.h"
101 #include "board.h"
102 #include "draw.h"
103
104
105 #ifdef __EMX__
106 #ifndef HAVE_USLEEP
107 #define HAVE_USLEEP
108 #endif
109 #define usleep(t)   _sleep2(((t)+500)/1000)
110 #endif
111
112
113 int squareSize, lineGap;
114
115 int damage[2][BOARD_RANKS][BOARD_FILES];
116
117 /* There can be two pieces being animated at once: a player
118    can begin dragging a piece before the remote opponent has moved. */
119
120 AnimState anims[NrOfAnims];
121
122 static void DrawSquare P((int row, int column, ChessSquare piece, int do_flash));
123 static Boolean IsDrawArrowEnabled P((void));
124 static void DrawArrowHighlight P((int fromX, int fromY, int toX,int toY));
125 static void ArrowDamage P((int s_col, int s_row, int d_col, int d_row));
126
127 static void
128 drawHighlight (int file, int rank, int type)
129 {
130     int x, y;
131
132     if (lineGap == 0) return;
133
134     if (flipView) {
135         x = lineGap/2 + ((BOARD_WIDTH-1)-file) *
136           (squareSize + lineGap);
137         y = lineGap/2 + rank * (squareSize + lineGap);
138     } else {
139         x = lineGap/2 + file * (squareSize + lineGap);
140         y = lineGap/2 + ((BOARD_HEIGHT-1)-rank) *
141           (squareSize + lineGap);
142     }
143
144     DrawBorder(x,y, type, lineGap & 1); // pass whether lineGap is odd
145 }
146
147 int hi1X = -1, hi1Y = -1, hi2X = -1, hi2Y = -1;
148 int pm1X = -1, pm1Y = -1, pm2X = -1, pm2Y = -1;
149
150 void
151 SetHighlights (int fromX, int fromY, int toX, int toY)
152 {
153     int arrow = hi2X >= 0 && hi1Y >= 0 && IsDrawArrowEnabled();
154
155     if (hi1X != fromX || hi1Y != fromY) {
156         if (hi1X >= 0 && hi1Y >= 0) {
157             drawHighlight(hi1X, hi1Y, 0);
158         }
159     } // [HGM] first erase both, then draw new!
160
161     if (hi2X != toX || hi2Y != toY) {
162         if (hi2X >= 0 && hi2Y >= 0) {
163             drawHighlight(hi2X, hi2Y, 0);
164         }
165     }
166
167     if(arrow) // there currently is an arrow displayed
168         ArrowDamage(hi1X, hi1Y, hi2X, hi2Y); // mark which squares it damaged
169
170     if (hi1X != fromX || hi1Y != fromY) {
171         if (fromX >= 0 && fromY >= 0) {
172             drawHighlight(fromX, fromY, 1);
173         }
174     }
175     if (hi2X != toX || hi2Y != toY) {
176         if (toX >= 0 && toY >= 0) {
177             drawHighlight(toX, toY, 1);
178         }
179     }
180
181     hi1X = fromX;
182     hi1Y = fromY;
183     hi2X = toX;
184     hi2Y = toY;
185
186     if(arrow || toX >= 0 && fromY >= 0 && IsDrawArrowEnabled())
187         DrawPosition(FALSE, NULL); // repair any arrow damage, or draw a new one
188 }
189
190 void
191 ClearHighlights ()
192 {
193     SetHighlights(-1, -1, -1, -1);
194 }
195
196
197 void
198 SetPremoveHighlights (int fromX, int fromY, int toX, int toY)
199 {
200     if (pm1X != fromX || pm1Y != fromY) {
201         if (pm1X >= 0 && pm1Y >= 0) {
202             drawHighlight(pm1X, pm1Y, 0);
203         }
204         if (fromX >= 0 && fromY >= 0) {
205             drawHighlight(fromX, fromY, 2);
206         }
207     }
208     if (pm2X != toX || pm2Y != toY) {
209         if (pm2X >= 0 && pm2Y >= 0) {
210             drawHighlight(pm2X, pm2Y, 0);
211         }
212         if (toX >= 0 && toY >= 0) {
213             drawHighlight(toX, toY, 2);
214         }
215     }
216     pm1X = fromX;
217     pm1Y = fromY;
218     pm2X = toX;
219     pm2Y = toY;
220 }
221
222 void
223 ClearPremoveHighlights ()
224 {
225   SetPremoveHighlights(-1, -1, -1, -1);
226 }
227
228 /*
229  * If the user selects on a border boundary, return -1; if off the board,
230  *   return -2.  Otherwise map the event coordinate to the square.
231  */
232 int
233 EventToSquare (int x, int limit)
234 {
235     if (x <= 0)
236       return -2;
237     if (x < lineGap)
238       return -1;
239     x -= lineGap;
240     if ((x % (squareSize + lineGap)) >= squareSize)
241       return -1;
242     x /= (squareSize + lineGap);
243     if (x >= limit)
244       return -2;
245     return x;
246 }
247
248 /* [HR] determine square color depending on chess variant. */
249 int
250 SquareColor (int row, int column)
251 {
252     int square_color;
253
254     if (gameInfo.variant == VariantXiangqi) {
255         if (column >= 3 && column <= 5 && row >= 0 && row <= 2) {
256             square_color = 1;
257         } else if (column >= 3 && column <= 5 && row >= 7 && row <= 9) {
258             square_color = 0;
259         } else if (row <= 4) {
260             square_color = 0;
261         } else {
262             square_color = 1;
263         }
264     } else {
265         square_color = ((column + row) % 2) == 1;
266     }
267
268     /* [hgm] holdings: next line makes all holdings squares light */
269     if(column < BOARD_LEFT || column >= BOARD_RGHT) square_color = 1;
270
271     if ( // [HGM] holdings: blank out area between board and holdings
272                  column == BOARD_LEFT-1
273              ||  column == BOARD_RGHT
274              || (column == BOARD_LEFT-2 && row < BOARD_HEIGHT-gameInfo.holdingsSize)
275              || (column == BOARD_RGHT+1 && row >= gameInfo.holdingsSize) )
276         square_color = 2; // black
277
278     return square_color;
279 }
280
281 /*      Convert board position to corner of screen rect and color       */
282
283 void
284 ScreenSquare (int column, int row, Pnt *pt, int *color)
285 {
286   if (flipView) {
287     pt->x = lineGap + ((BOARD_WIDTH-1)-column) * (squareSize + lineGap);
288     pt->y = lineGap + row * (squareSize + lineGap);
289   } else {
290     pt->x = lineGap + column * (squareSize + lineGap);
291     pt->y = lineGap + ((BOARD_HEIGHT-1)-row) * (squareSize + lineGap);
292   }
293   *color = SquareColor(row, column);
294 }
295
296 /*      Convert window coords to square                 */
297
298 void
299 BoardSquare (int x, int y, int *column, int *row)
300 {
301   *column = EventToSquare(x, BOARD_WIDTH);
302   if (flipView && *column >= 0)
303     *column = BOARD_WIDTH - 1 - *column;
304   *row = EventToSquare(y, BOARD_HEIGHT);
305   if (!flipView && *row >= 0)
306     *row = BOARD_HEIGHT - 1 - *row;
307 }
308
309 /*      Generate a series of frame coords from start->mid->finish.
310         The movement rate doubles until the half way point is
311         reached, then halves back down to the final destination,
312         which gives a nice slow in/out effect. The algorithmn
313         may seem to generate too many intermediates for short
314         moves, but remember that the purpose is to attract the
315         viewers attention to the piece about to be moved and
316         then to where it ends up. Too few frames would be less
317         noticeable.                                             */
318
319 static void
320 Tween (Pnt *start, Pnt *mid, Pnt *finish, int factor, Pnt frames[], int *nFrames)
321 {
322   int fraction, n, count;
323
324   count = 0;
325
326   /* Slow in, stepping 1/16th, then 1/8th, ... */
327   fraction = 1;
328   for (n = 0; n < factor; n++)
329     fraction *= 2;
330   for (n = 0; n < factor; n++) {
331     frames[count].x = start->x + (mid->x - start->x) / fraction;
332     frames[count].y = start->y + (mid->y - start->y) / fraction;
333     count ++;
334     fraction = fraction / 2;
335   }
336
337   /* Midpoint */
338   frames[count] = *mid;
339   count ++;
340
341   /* Slow out, stepping 1/2, then 1/4, ... */
342   fraction = 2;
343   for (n = 0; n < factor; n++) {
344     frames[count].x = finish->x - (finish->x - mid->x) / fraction;
345     frames[count].y = finish->y - (finish->y - mid->y) / fraction;
346     count ++;
347     fraction = fraction * 2;
348   }
349   *nFrames = count;
350 }
351
352 /****   Animation code by Hugh Fisher, DCS, ANU.
353
354         Known problem: if a window overlapping the board is
355         moved away while a piece is being animated underneath,
356         the newly exposed area won't be updated properly.
357         I can live with this.
358
359         Known problem: if you look carefully at the animation
360         of pieces in mono mode, they are being drawn as solid
361         shapes without interior detail while moving. Fixing
362         this would be a major complication for minimal return.
363 ****/
364
365 /*   Utilities  */
366
367 #undef Max  /* just in case */
368 #undef Min
369 #define Max(a, b) ((a) > (b) ? (a) : (b))
370 #define Min(a, b) ((a) < (b) ? (a) : (b))
371
372 typedef struct {
373   short int x, y, width, height;
374 } MyRectangle;
375
376 void
377 DoSleep (int n)
378 {
379     FrameDelay(n);
380 }
381
382 static void
383 SetRect (MyRectangle *rect, int x, int y, int width, int height)
384 {
385   rect->x = x;
386   rect->y = y;
387   rect->width  = width;
388   rect->height = height;
389 }
390
391 /*      Test if two frames overlap. If they do, return
392         intersection rect within old and location of
393         that rect within new. */
394
395 static Boolean
396 Intersect ( Pnt *old, Pnt *new, int size, MyRectangle *area, Pnt *pt)
397 {
398   if (old->x > new->x + size || new->x > old->x + size ||
399       old->y > new->y + size || new->y > old->y + size) {
400     return False;
401   } else {
402     SetRect(area, Max(new->x - old->x, 0), Max(new->y - old->y, 0),
403             size - abs(old->x - new->x), size - abs(old->y - new->y));
404     pt->x = Max(old->x - new->x, 0);
405     pt->y = Max(old->y - new->y, 0);
406     return True;
407   }
408 }
409
410 /*      For two overlapping frames, return the rect(s)
411         in the old that do not intersect with the new.   */
412
413 static void
414 CalcUpdateRects (Pnt *old, Pnt *new, int size, MyRectangle update[], int *nUpdates)
415 {
416   int        count;
417
418   /* If old = new (shouldn't happen) then nothing to draw */
419   if (old->x == new->x && old->y == new->y) {
420     *nUpdates = 0;
421     return;
422   }
423   /* Work out what bits overlap. Since we know the rects
424      are the same size we don't need a full intersect calc. */
425   count = 0;
426   /* Top or bottom edge? */
427   if (new->y > old->y) {
428     SetRect(&(update[count]), old->x, old->y, size, new->y - old->y);
429     count ++;
430   } else if (old->y > new->y) {
431     SetRect(&(update[count]), old->x, old->y + size - (old->y - new->y),
432                               size, old->y - new->y);
433     count ++;
434   }
435   /* Left or right edge - don't overlap any update calculated above. */
436   if (new->x > old->x) {
437     SetRect(&(update[count]), old->x, Max(new->y, old->y),
438                               new->x - old->x, size - abs(new->y - old->y));
439     count ++;
440   } else if (old->x > new->x) {
441     SetRect(&(update[count]), new->x + size, Max(new->y, old->y),
442                               old->x - new->x, size - abs(new->y - old->y));
443     count ++;
444   }
445   /* Done */
446   *nUpdates = count;
447 }
448
449 /* Animate the movement of a single piece */
450
451 static void
452 BeginAnimation (AnimNr anr, ChessSquare piece, ChessSquare bgPiece, int startColor, Pnt *start)
453 {
454   AnimState *anim = &anims[anr];
455
456   if(appData.upsideDown && flipView) piece += piece < BlackPawn ? BlackPawn : -BlackPawn;
457   /* The old buffer is initialised with the start square (empty) */
458   if(bgPiece == EmptySquare) {
459     DrawBlank(anr, start->x, start->y, startColor);
460   } else {
461        /* Kludge alert: When gating we want the introduced
462           piece to appear on the from square. To generate an
463           image of it, we draw it on the board, copy the image,
464           and draw the original piece again. */
465        if(piece != bgPiece) DrawSquare(anim->startBoardY, anim->startBoardX, bgPiece, 0);
466        CopyRectangle(anr, DISP, 2,
467                  start->x, start->y, squareSize, squareSize,
468                  0, 0); // [HGM] zh: unstack in stead of grab
469        if(piece != bgPiece) DrawSquare(anim->startBoardY, anim->startBoardX, piece, 0);
470   }
471   anim->prevFrame = *start;
472
473   SetDragPiece(anr, piece);
474 }
475
476 static void
477 AnimationFrame (AnimNr anr, Pnt *frame, ChessSquare piece)
478 {
479   MyRectangle updates[4];
480   MyRectangle overlap;
481   Pnt     pt;
482   AnimState *anim = &anims[anr];
483   int     count, i, x, y, w, h;
484
485   /* Save what we are about to draw into the new buffer */
486   CopyRectangle(anr, DISP, 0,
487             x = frame->x, y = frame->y, w = squareSize, h = squareSize,
488             0, 0);
489
490   /* Erase bits of the previous frame */
491   if (Intersect(&anim->prevFrame, frame, squareSize, &overlap, &pt)) {
492     /* Where the new frame overlapped the previous,
493        the contents in newBuf are wrong. */
494     CopyRectangle(anr, 2, 0,
495               overlap.x, overlap.y,
496               overlap.width, overlap.height,
497               pt.x, pt.y);
498     /* Repaint the areas in the old that don't overlap new */
499     CalcUpdateRects(&anim->prevFrame, frame, squareSize, updates, &count);
500     for (i = 0; i < count; i++)
501       CopyRectangle(anr, 2, DISP,
502                 updates[i].x - anim->prevFrame.x,
503                 updates[i].y - anim->prevFrame.y,
504                 updates[i].width, updates[i].height,
505                 updates[i].x, updates[i].y);
506     /* [HGM] correct expose rectangle to encompass both overlapping squares */
507     if(x > anim->prevFrame.x) w += x - anim->prevFrame.x, x = anim->prevFrame.x;
508     else  w += anim->prevFrame.x - x;
509     if(y > anim->prevFrame.y) h += y - anim->prevFrame.y, y = anim->prevFrame.y;
510     else  h += anim->prevFrame.y - y;
511   } else {
512     /* Easy when no overlap */
513     CopyRectangle(anr, 2, DISP,
514                   0, 0, squareSize, squareSize,
515                   anim->prevFrame.x, anim->prevFrame.y);
516     GraphExpose(currBoard, anim->prevFrame.x, anim->prevFrame.y, squareSize, squareSize);
517   }
518
519   /* Save this frame for next time round */
520   CopyRectangle(anr, 0, 2,
521                 0, 0, squareSize, squareSize,
522                 0, 0);
523   anim->prevFrame = *frame;
524
525   /* Draw piece over original screen contents, not current,
526      and copy entire rect. Wipes out overlapping piece images. */
527   InsertPiece(anr, piece);
528   CopyRectangle(anr, 0, DISP,
529                 0, 0, squareSize, squareSize,
530                 frame->x, frame->y);
531   GraphExpose(currBoard, x, y, w, h);
532 }
533
534 static void
535 EndAnimation (AnimNr anr, Pnt *finish)
536 {
537   MyRectangle updates[4];
538   MyRectangle overlap;
539   Pnt     pt;
540   int        count, i;
541   AnimState *anim = &anims[anr];
542
543   /* The main code will redraw the final square, so we
544      only need to erase the bits that don't overlap.    */
545   if (Intersect(&anim->prevFrame, finish, squareSize, &overlap, &pt)) {
546     CalcUpdateRects(&anim->prevFrame, finish, squareSize, updates, &count);
547     for (i = 0; i < count; i++)
548       CopyRectangle(anr, 2, DISP,
549                 updates[i].x - anim->prevFrame.x,
550                 updates[i].y - anim->prevFrame.y,
551                 updates[i].width, updates[i].height,
552                 updates[i].x, updates[i].y);
553   } else {
554     CopyRectangle(anr, 2, DISP,
555                 0, 0, squareSize, squareSize,
556                 anim->prevFrame.x, anim->prevFrame.y);
557   }
558 }
559
560 static void
561 FrameSequence (AnimNr anr, ChessSquare piece, int startColor, Pnt *start, Pnt *finish, Pnt frames[], int nFrames)
562 {
563   int n;
564
565   BeginAnimation(anr, piece, EmptySquare, startColor, start);
566   for (n = 0; n < nFrames; n++) {
567     AnimationFrame(anr, &(frames[n]), piece);
568     FrameDelay(appData.animSpeed);
569   }
570   EndAnimation(anr, finish);
571 }
572
573 void
574 AnimateAtomicCapture (Board board, int fromX, int fromY, int toX, int toY)
575 {
576     int i, x, y;
577     ChessSquare piece = board[fromY][toY];
578     board[fromY][toY] = EmptySquare;
579     DrawPosition(FALSE, board);
580     if (flipView) {
581         x = lineGap + ((BOARD_WIDTH-1)-toX) * (squareSize + lineGap);
582         y = lineGap + toY * (squareSize + lineGap);
583     } else {
584         x = lineGap + toX * (squareSize + lineGap);
585         y = lineGap + ((BOARD_HEIGHT-1)-toY) * (squareSize + lineGap);
586     }
587     for(i=1; i<4*kFactor; i++) {
588         int r = squareSize * 9 * i/(20*kFactor - 5);
589         DrawDot(1, x + squareSize/2 - r, y+squareSize/2 - r, 2*r);
590         FrameDelay(appData.animSpeed);
591     }
592     board[fromY][toY] = piece;
593     DrawGrid();
594 }
595
596 /* Main control logic for deciding what to animate and how */
597
598 void
599 AnimateMove (Board board, int fromX, int fromY, int toX, int toY)
600 {
601   ChessSquare piece;
602   int hop, x = toX, y = toY;
603   Pnt      start, finish, mid;
604   Pnt      frames[kFactor * 2 + 1];
605   int         nFrames, startColor, endColor;
606
607   /* Are we animating? */
608   if (!appData.animate || appData.blindfold)
609     return;
610
611   if(board[toY][toX] == WhiteRook && board[fromY][fromX] == WhiteKing ||
612      board[toY][toX] == BlackRook && board[fromY][fromX] == BlackKing)
613         return; // [HGM] FRC: no animtion of FRC castlings, as to-square is not true to-square
614
615   if (fromY < 0 || fromX < 0 || toX < 0 || toY < 0) return;
616   piece = board[fromY][fromX];
617   if (piece >= EmptySquare) return;
618
619   if(killX >= 0) toX = killX, toY = killY; // [HGM] lion: first to kill square
620
621 again:
622
623 #if DONT_HOP
624   hop = FALSE;
625 #else
626   hop = abs(fromX-toX) == 1 && abs(fromY-toY) == 2 || abs(fromX-toX) == 2 && abs(fromY-toY) == 1;
627 #endif
628
629   ScreenSquare(fromX, fromY, &start, &startColor);
630   ScreenSquare(toX, toY, &finish, &endColor);
631
632   if (hop) {
633     /* Knight: make straight movement then diagonal */
634     if (abs(toY - fromY) < abs(toX - fromX)) {
635        mid.x = start.x + (finish.x - start.x) / 2;
636        mid.y = start.y;
637      } else {
638        mid.x = start.x;
639        mid.y = start.y + (finish.y - start.y) / 2;
640      }
641   } else {
642     mid.x = start.x + (finish.x - start.x) / 2;
643     mid.y = start.y + (finish.y - start.y) / 2;
644   }
645
646   /* Don't use as many frames for very short moves */
647   if (abs(toY - fromY) + abs(toX - fromX) <= 2)
648     Tween(&start, &mid, &finish, kFactor - 1, frames, &nFrames);
649   else
650     Tween(&start, &mid, &finish, kFactor, frames, &nFrames);
651   FrameSequence(Game, piece, startColor, &start, &finish, frames, nFrames);
652   if(Explode(board, fromX, fromY, toX, toY)) { // mark as damaged
653     int i,j;
654     for(i=0; i<BOARD_WIDTH; i++) for(j=0; j<BOARD_HEIGHT; j++)
655       if((i-toX)*(i-toX) + (j-toY)*(j-toY) < 6) damage[0][j][i] |=  1 + ((i-toX ^ j-toY) & 1);
656   }
657
658   /* Be sure end square is redrawn */
659   damage[0][toY][toX] |= True;
660
661   if(toX != x || toY != y) { fromX = toX; fromY = toY; toX = x; toY = y; goto again; } // second leg
662 }
663
664 void
665 ChangeDragPiece (ChessSquare piece)
666 {
667   anims[Player].dragPiece = piece;
668   SetDragPiece(Player, piece);
669 }
670
671 void
672 DragPieceMove (int x, int y)
673 {
674     Pnt corner;
675
676     /* Are we animating? */
677     if (!appData.animateDragging || appData.blindfold)
678       return;
679
680     /* Sanity check */
681     if (! anims[Player].dragActive)
682       return;
683     /* Move piece, maintaining same relative position
684        of mouse within square    */
685     corner.x = x - anims[Player].mouseDelta.x;
686     corner.y = y - anims[Player].mouseDelta.y;
687     AnimationFrame(Player, &corner, anims[Player].dragPiece);
688 #if HIGHDRAG*0
689     if (appData.highlightDragging) {
690         int boardX, boardY;
691         BoardSquare(x, y, &boardX, &boardY);
692         SetHighlights(fromX, fromY, boardX, boardY);
693     }
694 #endif
695 }
696
697 void
698 DragPieceEnd (int x, int y)
699 {
700     int boardX, boardY, color;
701     Pnt corner;
702
703     /* Are we animating? */
704     if (!appData.animateDragging || appData.blindfold)
705       return;
706
707     /* Sanity check */
708     if (! anims[Player].dragActive)
709       return;
710     /* Last frame in sequence is square piece is
711        placed on, which may not match mouse exactly. */
712     BoardSquare(x, y, &boardX, &boardY);
713     ScreenSquare(boardX, boardY, &corner, &color);
714     EndAnimation(Player, &corner);
715
716     /* Be sure end square is redrawn */
717     damage[0][boardY][boardX] = True;
718
719     /* This prevents weird things happening with fast successive
720        clicks which on my Sun at least can cause motion events
721        without corresponding press/release. */
722     anims[Player].dragActive = False;
723 }
724
725 void
726 DragPieceBegin (int x, int y, Boolean instantly)
727 {
728     int  boardX, boardY, color;
729     Pnt corner;
730
731     /* Are we animating? */
732     if (!appData.animateDragging || appData.blindfold)
733       return;
734
735     /* Figure out which square we start in and the
736        mouse position relative to top left corner. */
737     BoardSquare(x, y, &boardX, &boardY);
738     anims[Player].startBoardX = boardX;
739     anims[Player].startBoardY = boardY;
740     ScreenSquare(boardX, boardY, &corner, &color);
741     anims[Player].startSquare  = corner;
742     anims[Player].startColor   = color;
743     /* As soon as we start dragging, the piece will jump slightly to
744        be centered over the mouse pointer. */
745     anims[Player].mouseDelta.x = squareSize/2;
746     anims[Player].mouseDelta.y = squareSize/2;
747     /* Initialise animation */
748     anims[Player].dragPiece = PieceForSquare(boardX, boardY);
749     /* Sanity check */
750     if (anims[Player].dragPiece >= 0 && anims[Player].dragPiece < EmptySquare) {
751         ChessSquare bgPiece = EmptySquare;
752         anims[Player].dragActive = True;
753         if(boardX == BOARD_RGHT+1 && PieceForSquare(boardX-1, boardY) > 1 ||
754            boardX == BOARD_LEFT-2 && PieceForSquare(boardX+1, boardY) > 1)
755             bgPiece = anims[Player].dragPiece;
756         if(gatingPiece != EmptySquare) bgPiece = gatingPiece;
757         BeginAnimation(Player, anims[Player].dragPiece, bgPiece, color, &corner);
758         /* Mark this square as needing to be redrawn. Note that
759            we don't remove the piece though, since logically (ie
760            as seen by opponent) the move hasn't been made yet. */
761         damage[0][boardY][boardX] = True;
762     } else {
763         anims[Player].dragActive = False;
764     }
765 }
766
767 /* Handle expose event while piece being dragged */
768
769 static void
770 DrawDragPiece ()
771 {
772   if (!anims[Player].dragActive || appData.blindfold)
773     return;
774
775   /* What we're doing: logically, the move hasn't been made yet,
776      so the piece is still in it's original square. But visually
777      it's being dragged around the board. So we erase the square
778      that the piece is on and draw it at the last known drag point. */
779   DrawOneSquare(anims[Player].startSquare.x, anims[Player].startSquare.y,
780                 EmptySquare, anims[Player].startColor, 0, NULL, NULL, 0);
781   AnimationFrame(Player, &anims[Player].prevFrame, anims[Player].dragPiece);
782   damage[0][anims[Player].startBoardY][anims[Player].startBoardX] = TRUE;
783 }
784
785 static void
786 DrawSquare (int row, int column, ChessSquare piece, int do_flash)
787 {
788     int square_color, x, y, align=0;
789     int i;
790     char tString[3], bString[2];
791     int flash_delay;
792
793     /* Calculate delay in milliseconds (2-delays per complete flash) */
794     flash_delay = 500 / appData.flashRate;
795
796     if (flipView) {
797         x = lineGap + ((BOARD_WIDTH-1)-column) *
798           (squareSize + lineGap);
799         y = lineGap + row * (squareSize + lineGap);
800     } else {
801         x = lineGap + column * (squareSize + lineGap);
802         y = lineGap + ((BOARD_HEIGHT-1)-row) *
803           (squareSize + lineGap);
804     }
805
806     square_color = SquareColor(row, column);
807
808     bString[1] = bString[0] = NULLCHAR;
809     if (appData.showCoords && row == (flipView ? BOARD_HEIGHT-1 : 0)
810                 && column >= BOARD_LEFT && column < BOARD_RGHT) {
811         bString[0] = 'a' + column - BOARD_LEFT;
812         align = 1; // coord in lower-right corner
813     }
814     if (appData.showCoords && column == (flipView ? BOARD_RGHT-1 : BOARD_LEFT)) {
815         snprintf(tString, 3, "%d", ONE - '0' + row);
816         align = 2; // coord in upper-left corner
817     }
818     if (column == (flipView ? BOARD_LEFT-1 : BOARD_RGHT) && piece > 1 ) {
819         snprintf(tString, 3, "%d", piece);
820         align = 3; // holdings count in upper-right corner
821     }
822     if (column == (flipView ? BOARD_RGHT : BOARD_LEFT-1) && piece > 1) {
823         snprintf(tString, 3, "%d", piece);
824         align = 4; // holdings count in upper-left corner
825     }
826     if(piece == DarkSquare) square_color = 2;
827     if(square_color == 2 || appData.blindfold) piece = EmptySquare;
828
829     if (do_flash && piece != EmptySquare && appData.flashCount > 0) {
830         for (i=0; i<appData.flashCount; ++i) {
831             DrawOneSquare(x, y, piece, square_color, 0, tString, bString, 0);
832             GraphExpose(currBoard, x, y, squareSize, squareSize);
833             FlashDelay(flash_delay);
834             DrawOneSquare(x, y, EmptySquare, square_color, 0, tString, bString, 0);
835             GraphExpose(currBoard, x, y, squareSize, squareSize);
836             FlashDelay(flash_delay);
837         }
838     }
839     DrawOneSquare(x, y, piece, square_color, partnerUp ? 0 : marker[row][column], tString, bString, align);
840 }
841
842 /* Returns 1 if there are "too many" differences between b1 and b2
843    (i.e. more than 1 move was made) */
844 static int
845 too_many_diffs (Board b1, Board b2)
846 {
847     int i, j;
848     int c = 0;
849
850     for (i=0; i<BOARD_HEIGHT; ++i) {
851         for (j=0; j<BOARD_WIDTH; ++j) {
852             if (b1[i][j] != b2[i][j]) {
853                 if (++c > 4)    /* Castling causes 4 diffs */
854                   return 1;
855             }
856         }
857     }
858     return 0;
859 }
860
861 /* Matrix describing castling maneuvers */
862 /* Row, ColRookFrom, ColKingFrom, ColRookTo, ColKingTo */
863 static int castling_matrix[4][5] = {
864     { 0, 0, 4, 3, 2 },          /* 0-0-0, white */
865     { 0, 7, 4, 5, 6 },          /* 0-0,   white */
866     { 7, 0, 4, 3, 2 },          /* 0-0-0, black */
867     { 7, 7, 4, 5, 6 }           /* 0-0,   black */
868 };
869
870 /* Checks whether castling occurred. If it did, *rrow and *rcol
871    are set to the destination (row,col) of the rook that moved.
872
873    Returns 1 if castling occurred, 0 if not.
874
875    Note: Only handles a max of 1 castling move, so be sure
876    to call too_many_diffs() first.
877    */
878 static int
879 check_castle_draw (Board newb, Board oldb, int *rrow, int *rcol)
880 {
881     int i, *r, j;
882     int match;
883
884     /* For each type of castling... */
885     for (i=0; i<4; ++i) {
886         r = castling_matrix[i];
887
888         /* Check the 4 squares involved in the castling move */
889         match = 0;
890         for (j=1; j<=4; ++j) {
891             if (newb[r[0]][r[j]] == oldb[r[0]][r[j]]) {
892                 match = 1;
893                 break;
894             }
895         }
896
897         if (!match) {
898             /* All 4 changed, so it must be a castling move */
899             *rrow = r[0];
900             *rcol = r[3];
901             return 1;
902         }
903     }
904     return 0;
905 }
906
907 void
908 DrawPosition (int repaint, Board board)
909 {
910     int i, j, do_flash, exposeAll = False;
911     static int lastFlipView = 0;
912     static int lastBoardValid[2] = {0, 0};
913     static Board lastBoard[2];
914     static char lastMarker[BOARD_RANKS][BOARD_FILES];
915     int rrow, rcol;
916     int nr = twoBoards*partnerUp;
917
918     if(DrawSeekGraph()) return; // [HGM] seekgraph: suppress any drawing if seek graph up
919
920     if (board == NULL) {
921         if (!lastBoardValid[nr]) return;
922         board = lastBoard[nr];
923     }
924     if (!lastBoardValid[nr] || (nr == 0 && lastFlipView != flipView)) {
925         MarkMenuItem("View.Flip View", flipView);
926     }
927
928     if(nr) { SlavePopUp(); SwitchWindow(0); } // [HGM] popup board if not yet popped up, and switch drawing to it.
929
930     /*
931      * It would be simpler to clear the window with XClearWindow()
932      * but this causes a very distracting flicker.
933      */
934
935     if (!repaint && lastBoardValid[nr] && (nr == 1 || lastFlipView == flipView)) {
936
937 //      if ( lineGap && IsDrawArrowEnabled())
938 //          DrawGrid();
939
940         /* If too much changes (begin observing new game, etc.), don't
941            do flashing */
942         do_flash = too_many_diffs(board, lastBoard[nr]) ? 0 : 1;
943
944         /* Special check for castling so we don't flash both the king
945            and the rook (just flash the king). */
946         if (do_flash) {
947             if (check_castle_draw(board, lastBoard[nr], &rrow, &rcol)) {
948                 /* Mark rook for drawing with NO flashing. */
949                 damage[nr][rrow][rcol] |= 1;
950             }
951         }
952
953         /* First pass -- Draw (newly) empty squares and repair damage.
954            This prevents you from having a piece show up twice while it
955            is flashing on its new square */
956         for (i = 0; i < BOARD_HEIGHT; i++)
957           for (j = 0; j < BOARD_WIDTH; j++)
958             if (((board[i][j] != lastBoard[nr][i][j] || !nr && marker[i][j] != lastMarker[i][j]) && board[i][j] == EmptySquare)
959                 || damage[nr][i][j]) {
960                 DrawSquare(i, j, board[i][j], 0);
961                 if(damage[nr][i][j] & 2) {
962                     drawHighlight(j, i, 0);   // repair arrow damage
963                     if(lineGap) damage[nr][i][j] = False; // this flushed the square as well
964                 } else damage[nr][i][j] = 1;  // mark for expose
965             }
966
967         /* Second pass -- Draw piece(s) in new position and flash them */
968         for (i = 0; i < BOARD_HEIGHT; i++)
969           for (j = 0; j < BOARD_WIDTH; j++)
970             if (board[i][j] != lastBoard[nr][i][j] || !nr && marker[i][j] != lastMarker[i][j]) {
971                 DrawSquare(i, j, board[i][j], do_flash);
972                 damage[nr][i][j] = 1; // mark for expose
973             }
974     } else {
975         if (lineGap > 0)
976           DrawGrid();
977
978         for (i = 0; i < BOARD_HEIGHT; i++)
979           for (j = 0; j < BOARD_WIDTH; j++) {
980               DrawSquare(i, j, board[i][j], 0);
981               damage[nr][i][j] = False;
982           }
983
984         exposeAll = True;
985     }
986
987     CopyBoard(lastBoard[nr], board);
988     lastBoardValid[nr] = 1;
989   if(nr == 0) { // [HGM] dual: no highlights on second board yet
990     lastFlipView = flipView;
991     for (i = 0; i < BOARD_HEIGHT; i++)
992         for (j = 0; j < BOARD_WIDTH; j++)
993             lastMarker[i][j] = marker[i][j];
994
995     /* Draw highlights */
996     if (pm1X >= 0 && pm1Y >= 0) {
997       drawHighlight(pm1X, pm1Y, 2);
998       if(lineGap) damage[nr][pm1Y][pm1X] = False;
999     }
1000     if (pm2X >= 0 && pm2Y >= 0) {
1001       drawHighlight(pm2X, pm2Y, 2);
1002       if(lineGap) damage[nr][pm2Y][pm2X] = False;
1003     }
1004     if (hi1X >= 0 && hi1Y >= 0) {
1005       drawHighlight(hi1X, hi1Y, 1);
1006       if(lineGap) damage[nr][hi1Y][hi1X] = False;
1007     }
1008     if (hi2X >= 0 && hi2Y >= 0) {
1009       drawHighlight(hi2X, hi2Y, 1);
1010       if(lineGap) damage[nr][hi2Y][hi2X] = False;
1011     }
1012     DrawArrowHighlight(hi1X, hi1Y, hi2X, hi2Y);
1013   }
1014   else DrawArrowHighlight (board[EP_STATUS-3], board[EP_STATUS-4], board[EP_STATUS-1], board[EP_STATUS-2]);
1015
1016     /* If piece being dragged around board, must redraw that too */
1017     DrawDragPiece();
1018
1019     if(exposeAll)
1020         GraphExpose(currBoard, 0, 0, BOARD_WIDTH*(squareSize + lineGap) + lineGap, BOARD_HEIGHT*(squareSize + lineGap) + lineGap);
1021     else {
1022         for (i = 0; i < BOARD_HEIGHT; i++)
1023             for (j = 0; j < BOARD_WIDTH; j++)
1024                 if(damage[nr][i][j]) {
1025                     int x, y;
1026                     if (flipView) {
1027                         x = lineGap + ((BOARD_WIDTH-1)-j) *
1028                           (squareSize + lineGap);
1029                         y = lineGap + i * (squareSize + lineGap);
1030                     } else {
1031                         x = lineGap + j * (squareSize + lineGap);
1032                         y = lineGap + ((BOARD_HEIGHT-1)-i) *
1033                           (squareSize + lineGap);
1034                     }
1035                     if(damage[nr][i][j] & 2) // damage by old or new arrow
1036                         GraphExpose(currBoard, x - lineGap, y - lineGap, squareSize + 2*lineGap, squareSize  + 2*lineGap);
1037                     else
1038                         GraphExpose(currBoard, x, y, squareSize, squareSize);
1039                     damage[nr][i][j] &= 2; // remember damage by newly drawn error in '2' bit, to schedule it for erasure next draw
1040                 }
1041     }
1042
1043     FlashDelay(0); // this flushes drawing queue;
1044     if(nr) SwitchWindow(1);
1045 }
1046
1047 /* [AS] Arrow highlighting support */
1048
1049 static double A_WIDTH = 5; /* Width of arrow body */
1050
1051 #define A_HEIGHT_FACTOR 6   /* Length of arrow "point", relative to body width */
1052 #define A_WIDTH_FACTOR  3   /* Width of arrow "point", relative to body width */
1053
1054 static double
1055 Sqr (double x)
1056 {
1057     return x*x;
1058 }
1059
1060 static int
1061 Round (double x)
1062 {
1063     return (int) (x + 0.5);
1064 }
1065
1066 void
1067 SquareToPos (int rank, int file, int *x, int *y)
1068 {
1069     if (flipView) {
1070         *x = lineGap + ((BOARD_WIDTH-1)-file) * (squareSize + lineGap);
1071         *y = lineGap + rank * (squareSize + lineGap);
1072     } else {
1073         *x = lineGap + file * (squareSize + lineGap);
1074         *y = lineGap + ((BOARD_HEIGHT-1)-rank) * (squareSize + lineGap);
1075     }
1076 }
1077
1078 /* Draw an arrow between two points using current settings */
1079 static void
1080 DrawArrowBetweenPoints (int s_x, int s_y, int d_x, int d_y)
1081 {
1082     Pnt arrow[8];
1083     double dx, dy, j, k, x, y;
1084
1085     if( d_x == s_x ) {
1086         int h = (d_y > s_y) ? +A_WIDTH*A_HEIGHT_FACTOR : -A_WIDTH*A_HEIGHT_FACTOR;
1087
1088         arrow[0].x = s_x + A_WIDTH + 0.5;
1089         arrow[0].y = s_y;
1090
1091         arrow[1].x = s_x + A_WIDTH + 0.5;
1092         arrow[1].y = d_y - h;
1093
1094         arrow[2].x = arrow[1].x + A_WIDTH*(A_WIDTH_FACTOR-1) + 0.5;
1095         arrow[2].y = d_y - h;
1096
1097         arrow[3].x = d_x;
1098         arrow[3].y = d_y;
1099
1100         arrow[5].x = arrow[1].x - 2*A_WIDTH + 0.5;
1101         arrow[5].y = d_y - h;
1102
1103         arrow[4].x = arrow[5].x - A_WIDTH*(A_WIDTH_FACTOR-1) + 0.5;
1104         arrow[4].y = d_y - h;
1105
1106         arrow[6].x = arrow[1].x - 2*A_WIDTH + 0.5;
1107         arrow[6].y = s_y;
1108     }
1109     else if( d_y == s_y ) {
1110         int w = (d_x > s_x) ? +A_WIDTH*A_HEIGHT_FACTOR : -A_WIDTH*A_HEIGHT_FACTOR;
1111
1112         arrow[0].x = s_x;
1113         arrow[0].y = s_y + A_WIDTH + 0.5;
1114
1115         arrow[1].x = d_x - w;
1116         arrow[1].y = s_y + A_WIDTH + 0.5;
1117
1118         arrow[2].x = d_x - w;
1119         arrow[2].y = arrow[1].y + A_WIDTH*(A_WIDTH_FACTOR-1) + 0.5;
1120
1121         arrow[3].x = d_x;
1122         arrow[3].y = d_y;
1123
1124         arrow[5].x = d_x - w;
1125         arrow[5].y = arrow[1].y - 2*A_WIDTH + 0.5;
1126
1127         arrow[4].x = d_x - w;
1128         arrow[4].y = arrow[5].y - A_WIDTH*(A_WIDTH_FACTOR-1) + 0.5;
1129
1130         arrow[6].x = s_x;
1131         arrow[6].y = arrow[1].y - 2*A_WIDTH + 0.5;
1132     }
1133     else {
1134         /* [AS] Needed a lot of paper for this! :-) */
1135         dy = (double) (d_y - s_y) / (double) (d_x - s_x);
1136         dx = (double) (s_x - d_x) / (double) (s_y - d_y);
1137
1138         j = sqrt( Sqr(A_WIDTH) / (1.0 + Sqr(dx)) );
1139
1140         k = sqrt( Sqr(A_WIDTH*A_HEIGHT_FACTOR) / (1.0 + Sqr(dy)) );
1141
1142         x = s_x;
1143         y = s_y;
1144
1145         arrow[0].x = Round(x - j);
1146         arrow[0].y = Round(y + j*dx);
1147
1148         arrow[1].x = Round(arrow[0].x + 2*j);   // [HGM] prevent width to be affected by rounding twice
1149         arrow[1].y = Round(arrow[0].y - 2*j*dx);
1150
1151         if( d_x > s_x ) {
1152             x = (double) d_x - k;
1153             y = (double) d_y - k*dy;
1154         }
1155         else {
1156             x = (double) d_x + k;
1157             y = (double) d_y + k*dy;
1158         }
1159
1160         x = Round(x); y = Round(y); // [HGM] make sure width of shaft is rounded the same way on both ends
1161
1162         arrow[6].x = Round(x - j);
1163         arrow[6].y = Round(y + j*dx);
1164
1165         arrow[2].x = Round(arrow[6].x + 2*j);
1166         arrow[2].y = Round(arrow[6].y - 2*j*dx);
1167
1168         arrow[3].x = Round(arrow[2].x + j*(A_WIDTH_FACTOR-1));
1169         arrow[3].y = Round(arrow[2].y - j*(A_WIDTH_FACTOR-1)*dx);
1170
1171         arrow[4].x = d_x;
1172         arrow[4].y = d_y;
1173
1174         arrow[5].x = Round(arrow[6].x - j*(A_WIDTH_FACTOR-1));
1175         arrow[5].y = Round(arrow[6].y + j*(A_WIDTH_FACTOR-1)*dx);
1176     }
1177
1178     DrawPolygon(arrow, 7);
1179 //    Polygon( hdc, arrow, 7 );
1180 }
1181
1182 static void
1183 ArrowDamage (int s_col, int s_row, int d_col, int d_row)
1184 {
1185     int hor, vert, i, n = partnerUp * twoBoards;
1186     hor = 64*s_col + 32; vert = 64*s_row + 32;
1187     for(i=0; i<= 64; i++) {
1188             damage[n][vert+6>>6][hor+6>>6] |= 2;
1189             damage[n][vert-6>>6][hor+6>>6] |= 2;
1190             damage[n][vert+6>>6][hor-6>>6] |= 2;
1191             damage[n][vert-6>>6][hor-6>>6] |= 2;
1192             hor += d_col - s_col; vert += d_row - s_row;
1193     }
1194 }
1195
1196 /* [AS] Draw an arrow between two squares */
1197 static void
1198 DrawArrowBetweenSquares (int s_col, int s_row, int d_col, int d_row)
1199 {
1200     int s_x, s_y, d_x, d_y;
1201
1202     if( s_col == d_col && s_row == d_row ) {
1203         return;
1204     }
1205
1206     /* Get source and destination points */
1207     SquareToPos( s_row, s_col, &s_x, &s_y);
1208     SquareToPos( d_row, d_col, &d_x, &d_y);
1209
1210     if( d_y > s_y ) {
1211         d_y += squareSize / 2 - squareSize / 4; // [HGM] round towards same centers on all sides!
1212     }
1213     else if( d_y < s_y ) {
1214         d_y += squareSize / 2 + squareSize / 4;
1215     }
1216     else {
1217         d_y += squareSize / 2;
1218     }
1219
1220     if( d_x > s_x ) {
1221         d_x += squareSize / 2 - squareSize / 4;
1222     }
1223     else if( d_x < s_x ) {
1224         d_x += squareSize / 2 + squareSize / 4;
1225     }
1226     else {
1227         d_x += squareSize / 2;
1228     }
1229
1230     s_x += squareSize / 2;
1231     s_y += squareSize / 2;
1232
1233     /* Adjust width */
1234     A_WIDTH = squareSize / 14.; //[HGM] make float
1235
1236     DrawArrowBetweenPoints( s_x, s_y, d_x, d_y );
1237     ArrowDamage(s_col, s_row, d_col, d_row);
1238 }
1239
1240 static Boolean
1241 IsDrawArrowEnabled ()
1242 {
1243     return (appData.highlightMoveWithArrow || twoBoards && partnerUp) && squareSize >= 32;
1244 }
1245
1246 static void
1247 DrawArrowHighlight (int fromX, int fromY, int toX,int toY)
1248 {
1249     if( IsDrawArrowEnabled() && fromX >= 0 && fromY >= 0 && toX >= 0 && toY >= 0)
1250         DrawArrowBetweenSquares(fromX, fromY, toX, toY);
1251 }