gfx.cpp

Go to the documentation of this file.
00001 /* $Id$ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
00006  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
00007  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "gfx_func.h"
00014 #include "fontcache.h"
00015 #include "progress.h"
00016 #include "zoom_func.h"
00017 #include "blitter/factory.hpp"
00018 #include "video/video_driver.hpp"
00019 #include "strings_func.h"
00020 #include "settings_type.h"
00021 #include "network/network.h"
00022 #include "network/network_func.h"
00023 #include "thread/thread.h"
00024 #include "window_func.h"
00025 #include "newgrf_debug.h"
00026 
00027 #include "table/palettes.h"
00028 #include "table/sprites.h"
00029 #include "table/control_codes.h"
00030 
00031 byte _dirkeys;        
00032 bool _fullscreen;
00033 CursorVars _cursor;
00034 bool _ctrl_pressed;   
00035 bool _shift_pressed;  
00036 byte _fast_forward;
00037 bool _left_button_down;     
00038 bool _left_button_clicked;  
00039 bool _right_button_down;    
00040 bool _right_button_clicked; 
00041 DrawPixelInfo _screen;
00042 bool _screen_disable_anim = false;   
00043 bool _exit_game;
00044 GameMode _game_mode;
00045 SwitchMode _switch_mode;  
00046 PauseModeByte _pause_mode;
00047 Palette _cur_palette;
00048 
00049 static int _max_char_height; 
00050 static int _max_char_width;  
00051 static byte _stringwidth_table[FS_END][224]; 
00052 DrawPixelInfo *_cur_dpi;
00053 byte _colour_gradient[COLOUR_END][8];
00054 
00055 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
00056 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZOOM_LVL_NORMAL);
00057 
00062 struct DrawStringParams {
00063   FontSize fontsize;
00064   TextColour cur_colour, prev_colour;
00065 
00066   DrawStringParams(TextColour colour, FontSize fontsize) : fontsize(fontsize), cur_colour(colour), prev_colour(colour) {}
00067 
00072   inline void SetColour(TextColour c)
00073   {
00074     assert(c >=  TC_BLUE && c <= TC_BLACK);
00075     this->prev_colour = this->cur_colour;
00076     this->cur_colour = c;
00077   }
00078 
00080   inline void SetPreviousColour()
00081   {
00082     Swap(this->cur_colour, this->prev_colour);
00083   }
00084 
00089   inline void SetFontSize(FontSize f)
00090   {
00091     this->fontsize = f;
00092   }
00093 };
00094 
00095 static ReusableBuffer<uint8> _cursor_backup;
00096 
00104 static Rect _invalid_rect;
00105 static const byte *_colour_remap_ptr;
00106 static byte _string_colourremap[3]; 
00107 
00108 static const uint DIRTY_BLOCK_HEIGHT   = 8;
00109 static const uint DIRTY_BLOCK_WIDTH    = 64;
00110 
00111 static uint _dirty_bytes_per_line = 0;
00112 static byte *_dirty_blocks = NULL;
00113 
00114 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
00115 {
00116   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00117 
00118   if (xo == 0 && yo == 0) return;
00119 
00120   if (_cursor.visible) UndrawMouseCursor();
00121 
00122 #ifdef ENABLE_NETWORK
00123   if (_networking) NetworkUndrawChatMessage();
00124 #endif /* ENABLE_NETWORK */
00125 
00126   blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
00127   /* This part of the screen is now dirty. */
00128   _video_driver->MakeDirty(left, top, width, height);
00129 }
00130 
00131 
00146 void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
00147 {
00148   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00149   const DrawPixelInfo *dpi = _cur_dpi;
00150   void *dst;
00151   const int otop = top;
00152   const int oleft = left;
00153 
00154   if (dpi->zoom != ZOOM_LVL_NORMAL) return;
00155   if (left > right || top > bottom) return;
00156   if (right < dpi->left || left >= dpi->left + dpi->width) return;
00157   if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
00158 
00159   if ( (left -= dpi->left) < 0) left = 0;
00160   right = right - dpi->left + 1;
00161   if (right > dpi->width) right = dpi->width;
00162   right -= left;
00163   assert(right > 0);
00164 
00165   if ( (top -= dpi->top) < 0) top = 0;
00166   bottom = bottom - dpi->top + 1;
00167   if (bottom > dpi->height) bottom = dpi->height;
00168   bottom -= top;
00169   assert(bottom > 0);
00170 
00171   dst = blitter->MoveTo(dpi->dst_ptr, left, top);
00172 
00173   switch (mode) {
00174     default: // FILLRECT_OPAQUE
00175       blitter->DrawRect(dst, right, bottom, (uint8)colour);
00176       break;
00177 
00178     case FILLRECT_RECOLOUR:
00179       blitter->DrawColourMappingRect(dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
00180       break;
00181 
00182     case FILLRECT_CHECKER: {
00183       byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
00184       do {
00185         for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
00186         dst = blitter->MoveTo(dst, 0, 1);
00187       } while (--bottom > 0);
00188       break;
00189     }
00190   }
00191 }
00192 
00193 void GfxDrawLine(int x, int y, int x2, int y2, int colour, int width)
00194 {
00195   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00196   DrawPixelInfo *dpi = _cur_dpi;
00197 
00198   assert(width > 0);
00199 
00200   x -= dpi->left;
00201   x2 -= dpi->left;
00202   y -= dpi->top;
00203   y2 -= dpi->top;
00204 
00205   /* Check clipping */
00206   if (x + width / 2 < 0           && x2 + width / 2 < 0          ) return;
00207   if (y + width / 2 < 0           && y2 + width / 2 < 0          ) return;
00208   if (x - width / 2 > dpi->width  && x2 - width / 2 > dpi->width ) return;
00209   if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return;
00210 
00211   blitter->DrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour, width);
00212 }
00213 
00214 void GfxDrawLineUnscaled(int x, int y, int x2, int y2, int colour)
00215 {
00216   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00217   DrawPixelInfo *dpi = _cur_dpi;
00218 
00219   x -= dpi->left;
00220   x2 -= dpi->left;
00221   y -= dpi->top;
00222   y2 -= dpi->top;
00223 
00224   /* Check clipping */
00225   if (x < 0 && x2 < 0) return;
00226   if (y < 0 && y2 < 0) return;
00227   if (x > dpi->width  && x2 > dpi->width)  return;
00228   if (y > dpi->height && y2 > dpi->height) return;
00229 
00230   blitter->DrawLine(dpi->dst_ptr, UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
00231       UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
00232       UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
00233 }
00234 
00248 void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
00249 {
00250   /*           ....
00251    *         ..    ....
00252    *       ..          ....
00253    *     ..                ^
00254    *   <--__(dx1,dy1)    /(dx2,dy2)
00255    *   :    --__       /   :
00256    *   :        --__ /     :
00257    *   :            *(x,y) :
00258    *   :            |      :
00259    *   :            |     ..
00260    *    ....        |(dx3,dy3)
00261    *        ....    | ..
00262    *            ....V.
00263    */
00264 
00265   static const byte colour = PC_WHITE;
00266 
00267   GfxDrawLineUnscaled(x, y, x + dx1, y + dy1, colour);
00268   GfxDrawLineUnscaled(x, y, x + dx2, y + dy2, colour);
00269   GfxDrawLineUnscaled(x, y, x + dx3, y + dy3, colour);
00270 
00271   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
00272   GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
00273   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
00274   GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
00275   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
00276   GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
00277 }
00278 
00283 static void SetColourRemap(TextColour colour)
00284 {
00285   if (colour == TC_INVALID) return;
00286 
00287   /* Black strings have no shading ever; the shading is black, so it
00288    * would be invisible at best, but it actually makes it illegible. */
00289   bool no_shade   = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
00290   bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
00291   colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
00292 
00293   _string_colourremap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
00294   _string_colourremap[2] = no_shade ? 0 : 1;
00295   _colour_remap_ptr = _string_colourremap;
00296 }
00297 
00298 #if !defined(WITH_ICU)
00299 typedef WChar UChar;
00300 static UChar *HandleBiDiAndArabicShapes(UChar *text) { return text; }
00301 #else
00302 #include <unicode/ubidi.h>
00303 #include <unicode/ushape.h>
00304 
00334 static UChar *HandleBiDiAndArabicShapes(UChar *buffer)
00335 {
00336   static UChar input_output[DRAW_STRING_BUFFER];
00337   UChar intermediate[DRAW_STRING_BUFFER];
00338 
00339   UChar *t = buffer;
00340   size_t length = 0;
00341   while (*t != '\0' && length < lengthof(input_output) - 1) {
00342     input_output[length++] = *t++;
00343   }
00344   input_output[length] = 0;
00345 
00346   UErrorCode err = U_ZERO_ERROR;
00347   UBiDi *para = ubidi_openSized((int32_t)length, 0, &err);
00348   if (para == NULL) return buffer;
00349 
00350   ubidi_setPara(para, input_output, (int32_t)length, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, &err);
00351   ubidi_writeReordered(para, intermediate, (int32_t)length, UBIDI_REMOVE_BIDI_CONTROLS, &err);
00352   length = u_shapeArabic(intermediate, (int32_t)length, input_output, lengthof(input_output), U_SHAPE_TEXT_DIRECTION_VISUAL_LTR | U_SHAPE_LETTERS_SHAPE, &err);
00353   ubidi_close(para);
00354 
00355   if (U_FAILURE(err)) return buffer;
00356 
00357   input_output[length] = '\0';
00358   return input_output;
00359 }
00360 #endif /* WITH_ICU */
00361 
00362 
00372 static int TruncateString(char *str, int maxw, bool ignore_setxy, FontSize start_fontsize)
00373 {
00374   int w = 0;
00375   FontSize size = start_fontsize;
00376   int ddd, ddd_w;
00377 
00378   WChar c;
00379   char *ddd_pos;
00380 
00381   ddd_w = ddd = GetCharacterWidth(size, '.') * 3;
00382 
00383   for (ddd_pos = str; (c = Utf8Consume(const_cast<const char **>(&str))) != '\0'; ) {
00384     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00385       w += GetCharacterWidth(size, c);
00386 
00387       if (w > maxw) {
00388         /* string got too big... insert dotdotdot, but make sure we do not
00389          * print anything beyond the string termination character. */
00390         for (int i = 0; *ddd_pos != '\0' && i < 3; i++, ddd_pos++) *ddd_pos = '.';
00391         *ddd_pos = '\0';
00392         return ddd_w;
00393       }
00394     } else {
00395       if (c == SCC_SETX) {
00396         if (!ignore_setxy) w = *str;
00397         str++;
00398       } else if (c == SCC_SETXY) {
00399         if (!ignore_setxy) w = *str;
00400         str += 2;
00401       } else if (c == SCC_TINYFONT) {
00402         size = FS_SMALL;
00403         ddd = GetCharacterWidth(size, '.') * 3;
00404       } else if (c == SCC_BIGFONT) {
00405         size = FS_LARGE;
00406         ddd = GetCharacterWidth(size, '.') * 3;
00407       } else if (c == '\n') {
00408         DEBUG(misc, 0, "Drawing string using newlines with DrawString instead of DrawStringMultiLine. Please notify the developers of this: [%s]", str);
00409       }
00410     }
00411 
00412     /* Remember the last position where three dots fit. */
00413     if (w + ddd < maxw) {
00414       ddd_w = w + ddd;
00415       ddd_pos = str;
00416     }
00417   }
00418 
00419   return w;
00420 }
00421 
00422 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped = false);
00423 
00430 static int GetStringWidth(const UChar *str, FontSize start_fontsize)
00431 {
00432   FontSize size = start_fontsize;
00433   int max_width;
00434   int width;
00435   WChar c;
00436 
00437   width = max_width = 0;
00438   for (;;) {
00439     c = *str++;
00440     if (c == 0) break;
00441     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00442       width += GetCharacterWidth(size, c);
00443     } else {
00444       switch (c) {
00445         case SCC_SETX:
00446         case SCC_SETXY:
00447           /* At this point there is no SCC_SETX(Y) anymore */
00448           NOT_REACHED();
00449           break;
00450         case SCC_TINYFONT: size = FS_SMALL; break;
00451         case SCC_BIGFONT:  size = FS_LARGE; break;
00452         case '\n':
00453           max_width = max(max_width, width);
00454           break;
00455       }
00456     }
00457   }
00458 
00459   return max(max_width, width);
00460 }
00461 
00480 static int DrawString(int left, int right, int top, char *str, const char *last, DrawStringParams &params, StringAlignment align, bool underline = false, bool truncate = true)
00481 {
00482   /* We need the outer limits of both left/right */
00483   int min_left = INT32_MAX;
00484   int max_right = INT32_MIN;
00485 
00486   int initial_left = left;
00487   int initial_right = right;
00488   int initial_top = top;
00489 
00490   if (truncate) TruncateString(str, right - left + 1, (align & SA_STRIP) == SA_STRIP, params.fontsize);
00491 
00492   /*
00493    * To support SETX and SETXY properly with RTL languages we have to
00494    * calculate the offsets from the right. To do this we need to split
00495    * the string and draw the parts separated by SETX(Y).
00496    * So here we split
00497    */
00498   static SmallVector<UChar *, 4> setx_offsets;
00499   setx_offsets.Clear();
00500 
00501   UChar draw_buffer[DRAW_STRING_BUFFER];
00502   UChar *p = draw_buffer;
00503 
00504   *setx_offsets.Append() = p;
00505 
00506   char *loc = str;
00507   for (;;) {
00508     WChar c;
00509     /* We cannot use Utf8Consume as we need the location of the SETX(Y) */
00510     size_t len = Utf8Decode(&c, loc);
00511     *p++ = c;
00512 
00513     if (c == '\0') break;
00514     if (p >= lastof(draw_buffer) - 3) {
00515       /* Make sure we never overflow (even if copying SCC_SETX(Y)). */
00516       *p = '\0';
00517       break;
00518     }
00519     if (c != SCC_SETX && c != SCC_SETXY) {
00520       loc += len;
00521       continue;
00522     }
00523 
00524     if (align & SA_STRIP) {
00525       /* We do not want to keep the SETX(Y)!. It was already copied, so
00526        * remove it and undo the incrementing of the pointer! */
00527       *p-- = '\0';
00528       loc += len + (c == SCC_SETXY ? 2 : 1);
00529       continue;
00530     }
00531 
00532     if ((align & SA_HOR_MASK) != SA_LEFT) {
00533       DEBUG(grf, 1, "Using SETX and/or SETXY when not aligned to the left. Fixing alignment...");
00534 
00535       /* For left alignment and change the left so it will roughly be in the
00536        * middle. This will never cause the string to be completely centered,
00537        * but once SETX is used you cannot be sure the actual content of the
00538        * string is centered, so it doesn't really matter. */
00539       align = SA_LEFT | SA_FORCE;
00540       initial_left = left = max(left, (left + right - (int)GetStringBoundingBox(str).width) / 2);
00541     }
00542 
00543     /* We add the begin of the string, but don't add it twice */
00544     if (p != draw_buffer) {
00545       *setx_offsets.Append() = p;
00546       p[-1] = '\0';
00547       *p++ = c;
00548     }
00549 
00550     /* Skip the SCC_SETX(Y) ... */
00551     loc += len;
00552     /* ... copy the x coordinate ... */
00553     *p++ = *loc++;
00554     /* ... and finally copy the y coordinate if it exists */
00555     if (c == SCC_SETXY) *p++ = *loc++;
00556   }
00557 
00558   /* In case we have a RTL language we swap the alignment. */
00559   if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && !(align & SA_STRIP) && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
00560 
00561   for (UChar **iter = setx_offsets.Begin(); iter != setx_offsets.End(); iter++) {
00562     UChar *to_draw = *iter;
00563     int offset = 0;
00564 
00565     /* Skip the SETX(Y) and set the appropriate offsets. */
00566     if (*to_draw == SCC_SETX || *to_draw == SCC_SETXY) {
00567       to_draw++;
00568       offset = *to_draw++;
00569       if (*to_draw == SCC_SETXY) top = initial_top + *to_draw++;
00570     }
00571 
00572     to_draw = HandleBiDiAndArabicShapes(to_draw);
00573     int w = GetStringWidth(to_draw, params.fontsize);
00574 
00575     /* right is the right most position to draw on. In this case we want to do
00576      * calculations with the width of the string. In comparison right can be
00577      * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
00578      * So most +1/-1 additions are to move from lengthof to 'indices'.
00579      */
00580     switch (align & SA_HOR_MASK) {
00581       case SA_LEFT:
00582         /* right + 1 = left + w */
00583         left = initial_left + offset;
00584         right = left + w - 1;
00585         break;
00586 
00587       case SA_HOR_CENTER:
00588         left  = RoundDivSU(initial_right + 1 + initial_left - w, 2);
00589         /* right + 1 = left + w */
00590         right = left + w - 1;
00591         break;
00592 
00593       case SA_RIGHT:
00594         left = initial_right + 1 - w - offset;
00595         break;
00596 
00597       default:
00598         NOT_REACHED();
00599     }
00600 
00601     min_left  = min(left, min_left);
00602     max_right = max(right, max_right);
00603 
00604     ReallyDoDrawString(to_draw, left, top, params, !truncate);
00605     if (underline) {
00606       GfxFillRect(left, top + FONT_HEIGHT_NORMAL, right, top + FONT_HEIGHT_NORMAL, _string_colourremap[1]);
00607     }
00608   }
00609 
00610   return (align & SA_HOR_MASK) == SA_RIGHT ? min_left : max_right;
00611 }
00612 
00627 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00628 {
00629   char buffer[DRAW_STRING_BUFFER];
00630   strecpy(buffer, str, lastof(buffer));
00631   DrawStringParams params(colour, fontsize);
00632   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00633 }
00634 
00649 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00650 {
00651   char buffer[DRAW_STRING_BUFFER];
00652   GetString(buffer, str, lastof(buffer));
00653   DrawStringParams params(colour, fontsize);
00654   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00655 }
00656 
00677 uint32 FormatStringLinebreaks(char *str, const char *last, int maxw, FontSize size)
00678 {
00679   int num = 0;
00680 
00681   assert(maxw > 0);
00682 
00683   for (;;) {
00684     /* The character *after* the last space. */
00685     char *last_space = NULL;
00686     int w = 0;
00687 
00688     for (;;) {
00689       WChar c = Utf8Consume(const_cast<const char **>(&str));
00690       /* whitespace is where we will insert the line-break */
00691       if (IsWhitespace(c)) last_space = str;
00692 
00693       if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00694         int char_w = GetCharacterWidth(size, c);
00695         w += char_w;
00696         if (w > maxw) {
00697           /* The string is longer than maximum width so we need to decide
00698            * what to do with it. */
00699           if (w == char_w) {
00700             /* The character is wider than allowed width; don't know
00701              * what to do with this case... bail out! */
00702             return num + (size << 16);
00703           }
00704           if (last_space == NULL) {
00705             /* No space has been found. Just terminate at our current
00706              * location. This usually happens for languages that do not
00707              * require spaces in strings, like Chinese, Japanese and
00708              * Korean. For other languages terminating mid-word might
00709              * not be the best, but terminating the whole string instead
00710              * of continuing the word at the next line is worse. */
00711             str = Utf8PrevChar(str);
00712             size_t len = strlen(str);
00713             char *terminator = str + len;
00714 
00715             /* The string location + length of the string + 1 for '\0'
00716              * always fits; otherwise there's no trailing '\0' and it
00717              * it not a valid string. */
00718             assert(terminator <= last);
00719             assert(*terminator == '\0');
00720 
00721             /* If the string is too long we have to terminate it earlier. */
00722             if (terminator == last) {
00723               /* Get the 'begin' of the previous character and make that
00724                * the terminator of the string; we truncate it 'early'. */
00725               *Utf8PrevChar(terminator) = '\0';
00726               len = strlen(str);
00727             }
00728             /* Also move the terminator! */
00729             memmove(str + 1, str, len + 1);
00730             *str = '\0';
00731             /* str needs to point to the character *after* the last space */
00732             str++;
00733           } else {
00734             /* A space is found; perfect place to terminate */
00735             str = last_space;
00736           }
00737           break;
00738         }
00739       } else {
00740         switch (c) {
00741           case '\0': return num + (size << 16);
00742           case SCC_SETX:  str++; break;
00743           case SCC_SETXY: str += 2; break;
00744           case SCC_TINYFONT: size = FS_SMALL; break;
00745           case SCC_BIGFONT:  size = FS_LARGE; break;
00746           case '\n': goto end_of_inner_loop;
00747         }
00748       }
00749     }
00750 end_of_inner_loop:
00751     /* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
00752      * and increase linecount. We use Utf8PrevChar() as also non 1 char long
00753      * whitespace seperators are supported */
00754     num++;
00755     char *s = Utf8PrevChar(str);
00756     *s++ = '\0';
00757 
00758     /* In which case (see above) we will shift remainder to left and close the gap */
00759     if (str - s >= 1) {
00760       for (; str[-1] != '\0';) *s++ = *str++;
00761     }
00762   }
00763 }
00764 
00765 
00774 static int GetMultilineStringHeight(const char *src, int num, FontSize start_fontsize)
00775 {
00776   int maxy = 0;
00777   int y = 0;
00778   int fh = GetCharacterHeight(start_fontsize);
00779 
00780   for (;;) {
00781     WChar c = Utf8Consume(&src);
00782 
00783     switch (c) {
00784       case 0:            y += fh; if (--num < 0) return maxy; break;
00785       case '\n':         y += fh;                             break;
00786       case SCC_SETX:     src++;                               break;
00787       case SCC_SETXY:    src++; y = (int)*src++;              break;
00788       case SCC_TINYFONT: fh = GetCharacterHeight(FS_SMALL);   break;
00789       case SCC_BIGFONT:  fh = GetCharacterHeight(FS_LARGE);   break;
00790       default:           maxy = max<int>(maxy, y + fh);       break;
00791     }
00792   }
00793 }
00794 
00795 
00802 int GetStringHeight(StringID str, int maxw)
00803 {
00804   char buffer[DRAW_STRING_BUFFER];
00805 
00806   GetString(buffer, str, lastof(buffer));
00807 
00808   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00809 
00810   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00811 }
00812 
00819 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00820 {
00821   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00822   return box;
00823 }
00824 
00841 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00842 {
00843   int maxw = right - left + 1;
00844   int maxh = bottom - top + 1;
00845 
00846   /* It makes no sense to even try if it can't be drawn anyway, or
00847    * do we really want to support fonts of 0 or less pixels high? */
00848   if (maxh <= 0) return top;
00849 
00850   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
00851   int num = GB(tmp, 0, 16) + 1;
00852 
00853   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
00854   int total_height = num * mt;
00855 
00856   int skip_lines = 0;
00857   if (total_height > maxh) {
00858     if (maxh < mt) return top; //  Not enough room for a single line.
00859     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
00860       skip_lines = num;
00861       num = maxh / mt;
00862       skip_lines -= num;
00863     } else {
00864       num = maxh / mt;
00865     }
00866     total_height = num * mt;
00867   }
00868 
00869   int y;
00870   switch (align & SA_VERT_MASK) {
00871     case SA_TOP:
00872       y = top;
00873       break;
00874 
00875     case SA_VERT_CENTER:
00876       y = RoundDivSU(bottom + top - total_height, 2);
00877       break;
00878 
00879     case SA_BOTTOM:
00880       y = bottom - total_height;
00881       break;
00882 
00883     default: NOT_REACHED();
00884   }
00885 
00886   const char *src = str;
00887   DrawStringParams params(colour, fontsize);
00888   int written_top = bottom; // Uppermost position of rendering a line of text
00889   for (;;) {
00890     if (skip_lines == 0) {
00891       char buf2[DRAW_STRING_BUFFER];
00892       strecpy(buf2, src, lastof(buf2));
00893       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
00894       if (written_top > y) written_top = y;
00895       y += mt;
00896       num--;
00897     }
00898 
00899     for (;;) {
00900       WChar c = Utf8Consume(&src);
00901       if (c == 0) {
00902         break;
00903       } else if (c == SCC_SETX) {
00904         src++;
00905       } else if (c == SCC_SETXY) {
00906         src += 2;
00907       } else if (skip_lines > 0) {
00908         /* Skipped drawing, so do additional processing to update params. */
00909         if (c >= SCC_BLUE && c <= SCC_BLACK) {
00910           params.SetColour((TextColour)(c - SCC_BLUE));
00911         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
00912           params.SetPreviousColour();
00913         } else if (c == SCC_TINYFONT) {
00914           params.SetFontSize(FS_SMALL);
00915         } else if (c == SCC_BIGFONT) {
00916           params.SetFontSize(FS_LARGE);
00917         }
00918 
00919       }
00920     }
00921     if (skip_lines > 0) skip_lines--;
00922     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
00923   }
00924 }
00925 
00941 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00942 {
00943   char buffer[DRAW_STRING_BUFFER];
00944   strecpy(buffer, str, lastof(buffer));
00945   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline, fontsize);
00946 }
00947 
00963 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
00964 {
00965   char buffer[DRAW_STRING_BUFFER];
00966   GetString(buffer, str, lastof(buffer));
00967   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline, fontsize);
00968 }
00969 
00980 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
00981 {
00982   FontSize size = start_fontsize;
00983   Dimension br;
00984   uint max_width;
00985   WChar c;
00986 
00987   br.width = br.height = max_width = 0;
00988   for (;;) {
00989     c = Utf8Consume(&str);
00990     if (c == 0) break;
00991     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00992       br.width += GetCharacterWidth(size, c);
00993     } else {
00994       switch (c) {
00995         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
00996         case SCC_SETXY:
00997           br.width  = max((uint)*str++, br.width);
00998           br.height = max((uint)*str++, br.height);
00999           break;
01000         case SCC_TINYFONT: size = FS_SMALL; break;
01001         case SCC_BIGFONT:  size = FS_LARGE; break;
01002         case '\n':
01003           br.height += GetCharacterHeight(size);
01004           if (br.width > max_width) max_width = br.width;
01005           br.width = 0;
01006           break;
01007       }
01008     }
01009   }
01010   br.height += GetCharacterHeight(size);
01011 
01012   br.width  = max(br.width, max_width);
01013   return br;
01014 }
01015 
01022 Dimension GetStringBoundingBox(StringID strid)
01023 {
01024   char buffer[DRAW_STRING_BUFFER];
01025 
01026   GetString(buffer, strid, lastof(buffer));
01027   return GetStringBoundingBox(buffer);
01028 }
01029 
01037 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
01038 {
01039   SetColourRemap(colour);
01040   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
01041 }
01042 
01060 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
01061 {
01062   DrawPixelInfo *dpi = _cur_dpi;
01063   bool draw_shadow = GetDrawGlyphShadow();
01064   UChar c;
01065   int xo = x;
01066 
01067   if (!parse_string_also_when_clipped) {
01068     /* in "mode multiline", the available space have been verified. Not in regular one.
01069      * So if the string cannot be drawn, return the original start to say so.*/
01070     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
01071   }
01072 
01073 switch_colour:;
01074   SetColourRemap(params.cur_colour);
01075 
01076 check_bounds:
01077   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
01078 skip_char:;
01079     for (;;) {
01080       c = *string++;
01081       if (!IsPrintable(c)) goto skip_cont;
01082     }
01083   }
01084 
01085   for (;;) {
01086     c = *string++;
01087 skip_cont:;
01088     if (c == 0) {
01089       return x;  // Nothing more to draw, get out. And here is the new x position
01090     }
01091     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01092       if (x >= dpi->left + dpi->width) goto skip_char;
01093       if (x + _max_char_width >= dpi->left) {
01094         const Sprite *glyph = GetGlyph(params.fontsize, c);
01095         if (draw_shadow && params.fontsize == FS_NORMAL && params.cur_colour != TC_BLACK && !(c >= SCC_SPRITE_START && c <= SCC_SPRITE_END)) {
01096           SetColourRemap(TC_BLACK);
01097           GfxMainBlitter(glyph, x + 1, y + 1, BM_COLOUR_REMAP);
01098           SetColourRemap(params.cur_colour);
01099         }
01100         GfxMainBlitter(glyph, x, y, BM_COLOUR_REMAP);
01101       }
01102       x += GetCharacterWidth(params.fontsize, c);
01103     } else if (c == '\n') { // newline = {}
01104       x = xo;  // We require a new line, so the x coordinate is reset
01105       y += GetCharacterHeight(params.fontsize);
01106       goto check_bounds;
01107     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
01108       params.SetColour((TextColour)(c - SCC_BLUE));
01109       goto switch_colour;
01110     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
01111       params.SetPreviousColour();
01112       goto switch_colour;
01113     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
01114       /* The characters are handled before calling this. */
01115       NOT_REACHED();
01116     } else if (c == SCC_TINYFONT) { // {TINYFONT}
01117       params.SetFontSize(FS_SMALL);
01118     } else if (c == SCC_BIGFONT) { // {BIGFONT}
01119       params.SetFontSize(FS_LARGE);
01120     } else if (!IsTextDirectionChar(c)) {
01121       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
01122     }
01123   }
01124 }
01125 
01133 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
01134 {
01135   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
01136 
01137   if (offset != NULL) {
01138     offset->x = UnScaleByZoom(sprite->x_offs, zoom);
01139     offset->y = UnScaleByZoom(sprite->y_offs, zoom);
01140   }
01141 
01142   Dimension d;
01143   d.width  = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
01144   d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
01145   return d;
01146 }
01147 
01156 void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
01157 {
01158   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01159   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01160     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01161     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
01162   } else if (pal != PAL_NONE) {
01163     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01164     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
01165   } else {
01166     GfxMainBlitterViewport(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
01167   }
01168 }
01169 
01179 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
01180 {
01181   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01182   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01183     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01184     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite, zoom);
01185   } else if (pal != PAL_NONE) {
01186     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01187     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite, zoom);
01188   } else {
01189     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite, zoom);
01190   }
01191 }
01192 
01193 static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
01194 {
01195   const DrawPixelInfo *dpi = _cur_dpi;
01196   Blitter::BlitterParams bp;
01197 
01198   /* Amount of pixels to clip from the source sprite */
01199   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left * ZOOM_LVL_BASE       ) : 0);
01200   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top  * ZOOM_LVL_BASE       ) : 0);
01201   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + (sub->right + 1)  * ZOOM_LVL_BASE)) : 0);
01202   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_LVL_BASE)) : 0);
01203 
01204   if (clip_left + clip_right >= sprite->width) return;
01205   if (clip_top + clip_bottom >= sprite->height) return;
01206 
01207   /* Move to the correct offset */
01208   x += sprite->x_offs;
01209   y += sprite->y_offs;
01210 
01211   /* Copy the main data directly from the sprite */
01212   bp.sprite = sprite->data;
01213   bp.sprite_width = sprite->width;
01214   bp.sprite_height = sprite->height;
01215   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
01216   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
01217   bp.top = 0;
01218   bp.left = 0;
01219   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
01220   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
01221 
01222   x += ScaleByZoom(bp.skip_left, dpi->zoom);
01223   y += ScaleByZoom(bp.skip_top, dpi->zoom);
01224 
01225   bp.dst = dpi->dst_ptr;
01226   bp.pitch = dpi->pitch;
01227   bp.remap = _colour_remap_ptr;
01228 
01229   assert(sprite->width > 0);
01230   assert(sprite->height > 0);
01231 
01232   if (bp.width <= 0) return;
01233   if (bp.height <= 0) return;
01234 
01235   y -= dpi->top;
01236   /* Check for top overflow */
01237   if (y < 0) {
01238     bp.height -= -UnScaleByZoom(y, dpi->zoom);
01239     if (bp.height <= 0) return;
01240     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
01241     y = 0;
01242   } else {
01243     bp.top = UnScaleByZoom(y, dpi->zoom);
01244   }
01245 
01246   /* Check for bottom overflow */
01247   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
01248   if (y > 0) {
01249     bp.height -= UnScaleByZoom(y, dpi->zoom);
01250     if (bp.height <= 0) return;
01251   }
01252 
01253   x -= dpi->left;
01254   /* Check for left overflow */
01255   if (x < 0) {
01256     bp.width -= -UnScaleByZoom(x, dpi->zoom);
01257     if (bp.width <= 0) return;
01258     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
01259     x = 0;
01260   } else {
01261     bp.left = UnScaleByZoom(x, dpi->zoom);
01262   }
01263 
01264   /* Check for right overflow */
01265   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
01266   if (x > 0) {
01267     bp.width -= UnScaleByZoom(x, dpi->zoom);
01268     if (bp.width <= 0) return;
01269   }
01270 
01271   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
01272   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
01273 
01274   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01275   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01276     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01277     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01278     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01279 
01280     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01281 
01282     if (topleft <= clicked && clicked <= bottomright) {
01283       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01284       if (offset < (uint)bp.width) {
01285         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01286       }
01287     }
01288   }
01289 
01290   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
01291 }
01292 
01293 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id, ZoomLevel zoom)
01294 {
01295   const DrawPixelInfo *dpi = _cur_dpi;
01296   Blitter::BlitterParams bp;
01297 
01298   /* Amount of pixels to clip from the source sprite */
01299   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
01300   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
01301   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
01302   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
01303 
01304   if (clip_left + clip_right >= sprite->width) return;
01305   if (clip_top + clip_bottom >= sprite->height) return;
01306 
01307   /* Scale it */
01308   x = ScaleByZoom(x, zoom);
01309   y = ScaleByZoom(y, zoom);
01310 
01311   /* Move to the correct offset */
01312   x += sprite->x_offs;
01313   y += sprite->y_offs;
01314 
01315   /* Copy the main data directly from the sprite */
01316   bp.sprite = sprite->data;
01317   bp.sprite_width = sprite->width;
01318   bp.sprite_height = sprite->height;
01319   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, zoom);
01320   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, zoom);
01321   bp.top = 0;
01322   bp.left = 0;
01323   bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
01324   bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
01325 
01326   x += ScaleByZoom(bp.skip_left, zoom);
01327   y += ScaleByZoom(bp.skip_top, zoom);
01328 
01329   bp.dst = dpi->dst_ptr;
01330   bp.pitch = dpi->pitch;
01331   bp.remap = _colour_remap_ptr;
01332 
01333   assert(sprite->width > 0);
01334   assert(sprite->height > 0);
01335 
01336   if (bp.width <= 0) return;
01337   if (bp.height <= 0) return;
01338 
01339   y -= ScaleByZoom(dpi->top, zoom);
01340   /* Check for top overflow */
01341   if (y < 0) {
01342     bp.height -= -UnScaleByZoom(y, zoom);
01343     if (bp.height <= 0) return;
01344     bp.skip_top += -UnScaleByZoom(y, zoom);
01345     y = 0;
01346   } else {
01347     bp.top = UnScaleByZoom(y, zoom);
01348   }
01349 
01350   /* Check for bottom overflow */
01351   y += ScaleByZoom(bp.height - dpi->height, zoom);
01352   if (y > 0) {
01353     bp.height -= UnScaleByZoom(y, zoom);
01354     if (bp.height <= 0) return;
01355   }
01356 
01357   x -= ScaleByZoom(dpi->left, zoom);
01358   /* Check for left overflow */
01359   if (x < 0) {
01360     bp.width -= -UnScaleByZoom(x, zoom);
01361     if (bp.width <= 0) return;
01362     bp.skip_left += -UnScaleByZoom(x, zoom);
01363     x = 0;
01364   } else {
01365     bp.left = UnScaleByZoom(x, zoom);
01366   }
01367 
01368   /* Check for right overflow */
01369   x += ScaleByZoom(bp.width - dpi->width, zoom);
01370   if (x > 0) {
01371     bp.width -= UnScaleByZoom(x, zoom);
01372     if (bp.width <= 0) return;
01373   }
01374 
01375   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, zoom));
01376   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, zoom));
01377 
01378   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01379   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01380     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01381     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01382     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01383 
01384     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01385 
01386     if (topleft <= clicked && clicked <= bottomright) {
01387       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01388       if (offset < (uint)bp.width) {
01389         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01390       }
01391     }
01392   }
01393 
01394   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, zoom);
01395 }
01396 
01397 void DoPaletteAnimations();
01398 
01399 void GfxInitPalettes()
01400 {
01401   memcpy(&_cur_palette, &_palette, sizeof(_cur_palette));
01402   DoPaletteAnimations();
01403 }
01404 
01405 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01406 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01407 
01408 void DoPaletteAnimations()
01409 {
01410   /* Animation counter for the palette animation. */
01411   static int palette_animation_counter = 0;
01412   palette_animation_counter += 8;
01413 
01414   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01415   const Colour *s;
01416   const ExtraPaletteValues *ev = &_extra_palette_values;
01417   Colour old_val[PALETTE_ANIM_SIZE];
01418   const uint old_tc = palette_animation_counter;
01419   uint i;
01420   uint j;
01421 
01422   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01423     palette_animation_counter = 0;
01424   }
01425 
01426   Colour *palette_pos = &_cur_palette.palette[PALETTE_ANIM_START];  // Points to where animations are taking place on the palette
01427   /* Makes a copy of the current anmation palette in old_val,
01428    * so the work on the current palette could be compared, see if there has been any changes */
01429   memcpy(old_val, palette_pos, sizeof(old_val));
01430 
01431   /* Fizzy Drink bubbles animation */
01432   s = ev->fizzy_drink;
01433   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01434   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01435     *palette_pos++ = s[j];
01436     j++;
01437     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01438   }
01439 
01440   /* Oil refinery fire animation */
01441   s = ev->oil_refinery;
01442   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01443   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01444     *palette_pos++ = s[j];
01445     j++;
01446     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01447   }
01448 
01449   /* Radio tower blinking */
01450   {
01451     byte i = (palette_animation_counter >> 1) & 0x7F;
01452     byte v;
01453 
01454     if (i < 0x3f) {
01455       v = 255;
01456     } else if (i < 0x4A || i >= 0x75) {
01457       v = 128;
01458     } else {
01459       v = 20;
01460     }
01461     palette_pos->r = v;
01462     palette_pos->g = 0;
01463     palette_pos->b = 0;
01464     palette_pos++;
01465 
01466     i ^= 0x40;
01467     if (i < 0x3f) {
01468       v = 255;
01469     } else if (i < 0x4A || i >= 0x75) {
01470       v = 128;
01471     } else {
01472       v = 20;
01473     }
01474     palette_pos->r = v;
01475     palette_pos->g = 0;
01476     palette_pos->b = 0;
01477     palette_pos++;
01478   }
01479 
01480   /* Handle lighthouse and stadium animation */
01481   s = ev->lighthouse;
01482   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01483   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01484     *palette_pos++ = s[j];
01485     j++;
01486     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01487   }
01488 
01489   /* Dark blue water */
01490   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01491   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01492   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01493     *palette_pos++ = s[j];
01494     j++;
01495     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01496   }
01497 
01498   /* Glittery water */
01499   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01500   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01501   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01502     *palette_pos++ = s[j];
01503     j += 3;
01504     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01505   }
01506 
01507   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01508     palette_animation_counter = old_tc;
01509   } else {
01510     if (memcmp(old_val, &_cur_palette.palette[PALETTE_ANIM_START], sizeof(old_val)) != 0 && _cur_palette.count_dirty == 0) {
01511       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01512       _cur_palette.first_dirty = PALETTE_ANIM_START;
01513       _cur_palette.count_dirty = PALETTE_ANIM_SIZE;
01514     }
01515   }
01516 }
01517 
01518 
01523 void LoadStringWidthTable(bool monospace)
01524 {
01525   _max_char_height = 0;
01526   _max_char_width  = 0;
01527 
01528   for (FontSize fs = monospace ? FS_MONO : FS_BEGIN; fs < (monospace ? FS_END : FS_MONO); fs++) {
01529     _max_char_height = max<int>(_max_char_height, GetCharacterHeight(fs));
01530     for (uint i = 0; i != 224; i++) {
01531       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01532       _max_char_width = max<int>(_max_char_width, _stringwidth_table[fs][i]);
01533     }
01534   }
01535 
01536   /* Needed because they need to be 1 more than the widest. */
01537   _max_char_height++;
01538   _max_char_width++;
01539 
01540   ReInitAllWindows();
01541 }
01542 
01549 byte GetCharacterWidth(FontSize size, WChar key)
01550 {
01551   /* Use _stringwidth_table cache if possible */
01552   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01553 
01554   return GetGlyphWidth(size, key);
01555 }
01556 
01562 byte GetDigitWidth(FontSize size)
01563 {
01564   byte width = 0;
01565   for (char c = '0'; c <= '9'; c++) {
01566     width = max(GetCharacterWidth(size, c), width);
01567   }
01568   return width;
01569 }
01570 
01571 
01572 void ScreenSizeChanged()
01573 {
01574   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01575   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01576 
01577   /* check the dirty rect */
01578   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01579   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01580 
01581   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01582   _cursor.visible = false;
01583 }
01584 
01585 void UndrawMouseCursor()
01586 {
01587   /* Don't undraw the mouse cursor if the screen is not ready */
01588   if (_screen.dst_ptr == NULL) return;
01589 
01590   if (_cursor.visible) {
01591     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01592     _cursor.visible = false;
01593     blitter->CopyFromBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), _cursor_backup.GetBuffer(), _cursor.draw_size.x, _cursor.draw_size.y);
01594     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01595   }
01596 }
01597 
01598 void DrawMouseCursor()
01599 {
01600 #if defined(WINCE)
01601   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01602   return;
01603 #endif
01604 
01605   /* Don't draw the mouse cursor if the screen is not ready */
01606   if (_screen.dst_ptr == NULL) return;
01607 
01608   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01609   int x;
01610   int y;
01611   int w;
01612   int h;
01613 
01614   /* Redraw mouse cursor but only when it's inside the window */
01615   if (!_cursor.in_window) return;
01616 
01617   /* Don't draw the mouse cursor if it's already drawn */
01618   if (_cursor.visible) {
01619     if (!_cursor.dirty) return;
01620     UndrawMouseCursor();
01621   }
01622 
01623   w = _cursor.size.x;
01624   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01625   if (x < 0) {
01626     w += x;
01627     x = 0;
01628   }
01629   if (w > _screen.width - x) w = _screen.width - x;
01630   if (w <= 0) return;
01631   _cursor.draw_pos.x = x;
01632   _cursor.draw_size.x = w;
01633 
01634   h = _cursor.size.y;
01635   y = _cursor.pos.y + _cursor.offs.y;
01636   if (y < 0) {
01637     h += y;
01638     y = 0;
01639   }
01640   if (h > _screen.height - y) h = _screen.height - y;
01641   if (h <= 0) return;
01642   _cursor.draw_pos.y = y;
01643   _cursor.draw_size.y = h;
01644 
01645   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01646 
01647   /* Make backup of stuff below cursor */
01648   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01649 
01650   /* Draw cursor on screen */
01651   _cur_dpi = &_screen;
01652   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01653 
01654   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01655 
01656   _cursor.visible = true;
01657   _cursor.dirty = false;
01658 }
01659 
01660 void RedrawScreenRect(int left, int top, int right, int bottom)
01661 {
01662   assert(right <= _screen.width && bottom <= _screen.height);
01663   if (_cursor.visible) {
01664     if (right > _cursor.draw_pos.x &&
01665         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01666         bottom > _cursor.draw_pos.y &&
01667         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01668       UndrawMouseCursor();
01669     }
01670   }
01671 
01672 #ifdef ENABLE_NETWORK
01673   if (_networking) NetworkUndrawChatMessage();
01674 #endif /* ENABLE_NETWORK */
01675 
01676   DrawOverlappedWindowForAll(left, top, right, bottom);
01677 
01678   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01679 }
01680 
01686 void DrawDirtyBlocks()
01687 {
01688   byte *b = _dirty_blocks;
01689   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01690   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01691   int x;
01692   int y;
01693 
01694   if (HasModalProgress()) {
01695     /* We are generating the world, so release our rights to the map and
01696      * painting while we are waiting a bit. */
01697     _modal_progress_paint_mutex->EndCritical();
01698     _modal_progress_work_mutex->EndCritical();
01699 
01700     /* Wait a while and update _realtime_tick so we are given the rights */
01701     if (!IsFirstModalProgressLoop()) CSleep(MODAL_PROGRESS_REDRAW_TIMEOUT);
01702     _realtime_tick += MODAL_PROGRESS_REDRAW_TIMEOUT;
01703     _modal_progress_paint_mutex->BeginCritical();
01704     _modal_progress_work_mutex->BeginCritical();
01705 
01706     if (_switch_mode != SM_NONE && !HasModalProgress()) {
01707       SwitchToMode(_switch_mode);
01708       _switch_mode = SM_NONE;
01709     }
01710   }
01711 
01712   y = 0;
01713   do {
01714     x = 0;
01715     do {
01716       if (*b != 0) {
01717         int left;
01718         int top;
01719         int right = x + DIRTY_BLOCK_WIDTH;
01720         int bottom = y;
01721         byte *p = b;
01722         int h2;
01723 
01724         /* First try coalescing downwards */
01725         do {
01726           *p = 0;
01727           p += _dirty_bytes_per_line;
01728           bottom += DIRTY_BLOCK_HEIGHT;
01729         } while (bottom != h && *p != 0);
01730 
01731         /* Try coalescing to the right too. */
01732         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01733         assert(h2 > 0);
01734         p = b;
01735 
01736         while (right != w) {
01737           byte *p2 = ++p;
01738           int h = h2;
01739           /* Check if a full line of dirty flags is set. */
01740           do {
01741             if (!*p2) goto no_more_coalesc;
01742             p2 += _dirty_bytes_per_line;
01743           } while (--h != 0);
01744 
01745           /* Wohoo, can combine it one step to the right!
01746            * Do that, and clear the bits. */
01747           right += DIRTY_BLOCK_WIDTH;
01748 
01749           h = h2;
01750           p2 = p;
01751           do {
01752             *p2 = 0;
01753             p2 += _dirty_bytes_per_line;
01754           } while (--h != 0);
01755         }
01756         no_more_coalesc:
01757 
01758         left = x;
01759         top = y;
01760 
01761         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01762         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01763         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01764         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01765 
01766         if (left < right && top < bottom) {
01767           RedrawScreenRect(left, top, right, bottom);
01768         }
01769 
01770       }
01771     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01772   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01773 
01774   _invalid_rect.left = w;
01775   _invalid_rect.top = h;
01776   _invalid_rect.right = 0;
01777   _invalid_rect.bottom = 0;
01778 }
01779 
01795 void SetDirtyBlocks(int left, int top, int right, int bottom)
01796 {
01797   byte *b;
01798   int width;
01799   int height;
01800 
01801   if (left < 0) left = 0;
01802   if (top < 0) top = 0;
01803   if (right > _screen.width) right = _screen.width;
01804   if (bottom > _screen.height) bottom = _screen.height;
01805 
01806   if (left >= right || top >= bottom) return;
01807 
01808   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01809   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01810   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01811   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01812 
01813   left /= DIRTY_BLOCK_WIDTH;
01814   top  /= DIRTY_BLOCK_HEIGHT;
01815 
01816   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01817 
01818   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01819   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01820 
01821   assert(width > 0 && height > 0);
01822 
01823   do {
01824     int i = width;
01825 
01826     do b[--i] = 0xFF; while (i != 0);
01827 
01828     b += _dirty_bytes_per_line;
01829   } while (--height != 0);
01830 }
01831 
01838 void MarkWholeScreenDirty()
01839 {
01840   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01841 }
01842 
01857 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01858 {
01859   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01860   const DrawPixelInfo *o = _cur_dpi;
01861 
01862   n->zoom = ZOOM_LVL_NORMAL;
01863 
01864   assert(width > 0);
01865   assert(height > 0);
01866 
01867   if ((left -= o->left) < 0) {
01868     width += left;
01869     if (width <= 0) return false;
01870     n->left = -left;
01871     left = 0;
01872   } else {
01873     n->left = 0;
01874   }
01875 
01876   if (width > o->width - left) {
01877     width = o->width - left;
01878     if (width <= 0) return false;
01879   }
01880   n->width = width;
01881 
01882   if ((top -= o->top) < 0) {
01883     height += top;
01884     if (height <= 0) return false;
01885     n->top = -top;
01886     top = 0;
01887   } else {
01888     n->top = 0;
01889   }
01890 
01891   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01892   n->pitch = o->pitch;
01893 
01894   if (height > o->height - top) {
01895     height = o->height - top;
01896     if (height <= 0) return false;
01897   }
01898   n->height = height;
01899 
01900   return true;
01901 }
01902 
01907 void UpdateCursorSize()
01908 {
01909   CursorVars *cv = &_cursor;
01910   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01911 
01912   cv->size.y = UnScaleByZoom(p->height, ZOOM_LVL_GUI);
01913   cv->size.x = UnScaleByZoom(p->width, ZOOM_LVL_GUI);
01914   cv->offs.x = UnScaleByZoom(p->x_offs, ZOOM_LVL_GUI);
01915   cv->offs.y = UnScaleByZoom(p->y_offs, ZOOM_LVL_GUI);
01916 
01917   cv->dirty = true;
01918 }
01919 
01925 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01926 {
01927   CursorVars *cv = &_cursor;
01928   if (cv->sprite == cursor) return;
01929 
01930   cv->sprite = cursor;
01931   cv->pal    = pal;
01932   UpdateCursorSize();
01933 
01934   cv->short_vehicle_offset = 0;
01935 }
01936 
01937 static void SwitchAnimatedCursor()
01938 {
01939   const AnimCursor *cur = _cursor.animate_cur;
01940 
01941   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01942 
01943   SetCursorSprite(cur->sprite, _cursor.pal);
01944 
01945   _cursor.animate_timeout = cur->display_time;
01946   _cursor.animate_cur     = cur + 1;
01947 }
01948 
01949 void CursorTick()
01950 {
01951   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01952     SwitchAnimatedCursor();
01953   }
01954 }
01955 
01962 void SetMouseCursor(CursorID sprite, PaletteID pal)
01963 {
01964   /* Turn off animation */
01965   _cursor.animate_timeout = 0;
01966   /* Set cursor */
01967   SetCursorSprite(sprite, pal);
01968 }
01969 
01975 void SetAnimatedMouseCursor(const AnimCursor *table)
01976 {
01977   _cursor.animate_list = table;
01978   _cursor.animate_cur = NULL;
01979   _cursor.pal = PAL_NONE;
01980   SwitchAnimatedCursor();
01981 }
01982 
01983 bool ChangeResInGame(int width, int height)
01984 {
01985   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
01986 }
01987 
01988 bool ToggleFullScreen(bool fs)
01989 {
01990   bool result = _video_driver->ToggleFullscreen(fs);
01991   if (_fullscreen != fs && _num_resolutions == 0) {
01992     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
01993   }
01994   return result;
01995 }
01996 
01997 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
01998 {
01999   int x = pa->width - pb->width;
02000   if (x != 0) return x;
02001   return pa->height - pb->height;
02002 }
02003 
02004 void SortResolutions(int count)
02005 {
02006   QSortT(_resolutions, count, &compare_res);
02007 }