gfx.cpp

Go to the documentation of this file.
00001 /* $Id: gfx.cpp 21157 2010-11-13 09:56:25Z rubidium $ */
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 "genworld.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 int _pal_first_dirty;
00048 int _pal_count_dirty;
00049 
00050 Colour _cur_palette[256];
00051 
00052 static int _max_char_height; 
00053 static int _max_char_width;  
00054 static byte _stringwidth_table[FS_END][224]; 
00055 DrawPixelInfo *_cur_dpi;
00056 byte _colour_gradient[COLOUR_END][8];
00057 
00058 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
00059 
00064 struct DrawStringParams {
00065   FontSize fontsize;
00066   TextColour cur_colour, prev_colour;
00067 
00068   DrawStringParams(TextColour colour) : fontsize(FS_NORMAL), cur_colour(colour), prev_colour(colour) {}
00069 
00074   FORCEINLINE void SetColour(TextColour c)
00075   {
00076     assert(c >=  TC_BLUE && c <= TC_BLACK);
00077     this->prev_colour = this->cur_colour;
00078     this->cur_colour = c;
00079   }
00080 
00082   FORCEINLINE void SetPreviousColour()
00083   {
00084     Swap(this->cur_colour, this->prev_colour);
00085   }
00086 
00091   FORCEINLINE void SetFontSize(FontSize f)
00092   {
00093     this->fontsize = f;
00094   }
00095 };
00096 
00097 static ReusableBuffer<uint8> _cursor_backup;
00098 
00106 static Rect _invalid_rect;
00107 static const byte *_colour_remap_ptr;
00108 static byte _string_colourremap[3]; 
00109 
00110 static const uint DIRTY_BLOCK_HEIGHT   = 8;
00111 static const uint DIRTY_BLOCK_WIDTH    = 64;
00112 
00113 static uint _dirty_bytes_per_line = 0;
00114 static byte *_dirty_blocks = NULL;
00115 
00116 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
00117 {
00118   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00119 
00120   if (xo == 0 && yo == 0) return;
00121 
00122   if (_cursor.visible) UndrawMouseCursor();
00123 
00124 #ifdef ENABLE_NETWORK
00125   if (_networking) NetworkUndrawChatMessage();
00126 #endif /* ENABLE_NETWORK */
00127 
00128   blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
00129   /* This part of the screen is now dirty. */
00130   _video_driver->MakeDirty(left, top, width, height);
00131 }
00132 
00133 
00148 void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
00149 {
00150   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00151   const DrawPixelInfo *dpi = _cur_dpi;
00152   void *dst;
00153   const int otop = top;
00154   const int oleft = left;
00155 
00156   if (dpi->zoom != ZOOM_LVL_NORMAL) return;
00157   if (left > right || top > bottom) return;
00158   if (right < dpi->left || left >= dpi->left + dpi->width) return;
00159   if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
00160 
00161   if ( (left -= dpi->left) < 0) left = 0;
00162   right = right - dpi->left + 1;
00163   if (right > dpi->width) right = dpi->width;
00164   right -= left;
00165   assert(right > 0);
00166 
00167   if ( (top -= dpi->top) < 0) top = 0;
00168   bottom = bottom - dpi->top + 1;
00169   if (bottom > dpi->height) bottom = dpi->height;
00170   bottom -= top;
00171   assert(bottom > 0);
00172 
00173   dst = blitter->MoveTo(dpi->dst_ptr, left, top);
00174 
00175   switch (mode) {
00176     default: // FILLRECT_OPAQUE
00177       blitter->DrawRect(dst, right, bottom, (uint8)colour);
00178       break;
00179 
00180     case FILLRECT_RECOLOUR:
00181       blitter->DrawColourMappingRect(dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
00182       break;
00183 
00184     case FILLRECT_CHECKER: {
00185       byte bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
00186       do {
00187         for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, (uint8)colour);
00188         dst = blitter->MoveTo(dst, 0, 1);
00189       } while (--bottom > 0);
00190       break;
00191     }
00192   }
00193 }
00194 
00195 void GfxDrawLine(int x, int y, int x2, int y2, int colour)
00196 {
00197   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
00198   DrawPixelInfo *dpi = _cur_dpi;
00199 
00200   x -= dpi->left;
00201   x2 -= dpi->left;
00202   y -= dpi->top;
00203   y2 -= dpi->top;
00204 
00205   /* Check clipping */
00206   if (x < 0 && x2 < 0) return;
00207   if (y < 0 && y2 < 0) return;
00208   if (x > dpi->width  && x2 > dpi->width)  return;
00209   if (y > dpi->height && y2 > dpi->height) return;
00210 
00211   blitter->DrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour);
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);
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 = 15;
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   if (colour & IS_PALETTE_COLOUR) {
00288     _string_colourremap[1] = colour & ~IS_PALETTE_COLOUR;
00289     _string_colourremap[2] = (_use_palette == PAL_DOS) ? 1 : 215;
00290   } else {
00291     _string_colourremap[1] = _string_colourmap[_use_palette][colour].text;
00292     _string_colourremap[2] = _string_colourmap[_use_palette][colour].shadow;
00293   }
00294   _colour_remap_ptr = _string_colourremap;
00295 }
00296 
00297 #if !defined(WITH_ICU)
00298 typedef WChar UChar;
00299 static UChar *HandleBiDiAndArabicShapes(UChar *text) { return text; }
00300 #else
00301 #include <unicode/ubidi.h>
00302 #include <unicode/ushape.h>
00303 
00333 static UChar *HandleBiDiAndArabicShapes(UChar *buffer)
00334 {
00335   static UChar input_output[DRAW_STRING_BUFFER];
00336   UChar intermediate[DRAW_STRING_BUFFER];
00337 
00338   UChar *t = buffer;
00339   size_t length = 0;
00340   while (*t != '\0' && length < lengthof(input_output) - 1) {
00341     input_output[length++] = *t++;
00342   }
00343   input_output[length] = 0;
00344 
00345   UErrorCode err = U_ZERO_ERROR;
00346   UBiDi *para = ubidi_openSized((int32_t)length, 0, &err);
00347   if (para == NULL) return buffer;
00348 
00349   ubidi_setPara(para, input_output, (int32_t)length, _current_text_dir == TD_RTL ? UBIDI_DEFAULT_RTL : UBIDI_DEFAULT_LTR, NULL, &err);
00350   ubidi_writeReordered(para, intermediate, (int32_t)length, UBIDI_REMOVE_BIDI_CONTROLS, &err);
00351   length = u_shapeArabic(intermediate, (int32_t)length, input_output, lengthof(input_output), U_SHAPE_TEXT_DIRECTION_VISUAL_LTR | U_SHAPE_LETTERS_SHAPE, &err);
00352   ubidi_close(para);
00353 
00354   if (U_FAILURE(err)) return buffer;
00355 
00356   input_output[length] = '\0';
00357   return input_output;
00358 }
00359 #endif /* WITH_ICU */
00360 
00361 
00371 static int TruncateString(char *str, int maxw, bool ignore_setxy, FontSize start_fontsize)
00372 {
00373   int w = 0;
00374   FontSize size = start_fontsize;
00375   int ddd, ddd_w;
00376 
00377   WChar c;
00378   char *ddd_pos;
00379 
00380   ddd_w = ddd = GetCharacterWidth(size, '.') * 3;
00381 
00382   for (ddd_pos = str; (c = Utf8Consume(const_cast<const char **>(&str))) != '\0'; ) {
00383     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00384       w += GetCharacterWidth(size, c);
00385 
00386       if (w > maxw) {
00387         /* string got too big... insert dotdotdot, but make sure we do not
00388          * print anything beyond the string termination character. */
00389         for (int i = 0; *ddd_pos != '\0' && i < 3; i++, ddd_pos++) *ddd_pos = '.';
00390         *ddd_pos = '\0';
00391         return ddd_w;
00392       }
00393     } else {
00394       if (c == SCC_SETX) {
00395         if (!ignore_setxy) w = *str;
00396         str++;
00397       } else if (c == SCC_SETXY) {
00398         if (!ignore_setxy) w = *str;
00399         str += 2;
00400       } else if (c == SCC_TINYFONT) {
00401         size = FS_SMALL;
00402         ddd = GetCharacterWidth(size, '.') * 3;
00403       } else if (c == SCC_BIGFONT) {
00404         size = FS_LARGE;
00405         ddd = GetCharacterWidth(size, '.') * 3;
00406       } else if (c == '\n') {
00407         DEBUG(misc, 0, "Drawing string using newlines with DrawString instead of DrawStringMultiLine. Please notify the developers of this: [%s]", str);
00408       }
00409     }
00410 
00411     /* Remember the last position where three dots fit. */
00412     if (w + ddd < maxw) {
00413       ddd_w = w + ddd;
00414       ddd_pos = str;
00415     }
00416   }
00417 
00418   return w;
00419 }
00420 
00421 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped = false);
00422 
00429 static int GetStringWidth(const UChar *str, FontSize start_fontsize)
00430 {
00431   FontSize size = start_fontsize;
00432   int max_width;
00433   int width;
00434   WChar c;
00435 
00436   width = max_width = 0;
00437   for (;;) {
00438     c = *str++;
00439     if (c == 0) break;
00440     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00441       width += GetCharacterWidth(size, c);
00442     } else {
00443       switch (c) {
00444         case SCC_SETX:
00445         case SCC_SETXY:
00446           /* At this point there is no SCC_SETX(Y) anymore */
00447           NOT_REACHED();
00448           break;
00449         case SCC_TINYFONT: size = FS_SMALL; break;
00450         case SCC_BIGFONT:  size = FS_LARGE; break;
00451         case '\n':
00452           max_width = max(max_width, width);
00453           break;
00454       }
00455     }
00456   }
00457 
00458   return max(max_width, width);
00459 }
00460 
00479 static int DrawString(int left, int right, int top, char *str, const char *last, DrawStringParams &params, StringAlignment align, bool underline = false, bool truncate = true)
00480 {
00481   /* We need the outer limits of both left/right */
00482   int min_left = INT32_MAX;
00483   int max_right = INT32_MIN;
00484 
00485   int initial_left = left;
00486   int initial_right = right;
00487   int initial_top = top;
00488 
00489   if (truncate) TruncateString(str, right - left + 1, (align & SA_STRIP) == SA_STRIP, params.fontsize);
00490 
00491   /*
00492    * To support SETX and SETXY properly with RTL languages we have to
00493    * calculate the offsets from the right. To do this we need to split
00494    * the string and draw the parts separated by SETX(Y).
00495    * So here we split
00496    */
00497   static SmallVector<UChar *, 4> setx_offsets;
00498   setx_offsets.Clear();
00499 
00500   UChar draw_buffer[DRAW_STRING_BUFFER];
00501   UChar *p = draw_buffer;
00502 
00503   *setx_offsets.Append() = p;
00504 
00505   char *loc = str;
00506   for (;;) {
00507     WChar c;
00508     /* We cannot use Utf8Consume as we need the location of the SETX(Y) */
00509     size_t len = Utf8Decode(&c, loc);
00510     *p++ = c;
00511 
00512     if (c == '\0') break;
00513     if (p >= lastof(draw_buffer) - 3) {
00514       /* Make sure we never overflow (even if copying SCC_SETX(Y)). */
00515       *p = '\0';
00516       break;
00517     }
00518     if (c != SCC_SETX && c != SCC_SETXY) {
00519       loc += len;
00520       continue;
00521     }
00522 
00523     if (align & SA_STRIP) {
00524       /* We do not want to keep the SETX(Y)!. It was already copied, so
00525        * remove it and undo the incrementing of the pointer! */
00526       *p-- = '\0';
00527       loc += len + (c == SCC_SETXY ? 2 : 1);
00528       continue;
00529     }
00530 
00531     if ((align & SA_HOR_MASK) != SA_LEFT) {
00532       DEBUG(grf, 1, "Using SETX and/or SETXY when not aligned to the left. Fixing alignment...");
00533 
00534       /* For left alignment and change the left so it will roughly be in the
00535        * middle. This will never cause the string to be completely centered,
00536        * but once SETX is used you cannot be sure the actual content of the
00537        * string is centered, so it doesn't really matter. */
00538       align = SA_LEFT | SA_FORCE;
00539       initial_left = left = max(left, (left + right - (int)GetStringBoundingBox(str).width) / 2);
00540     }
00541 
00542     /* We add the begin of the string, but don't add it twice */
00543     if (p != draw_buffer) {
00544       *setx_offsets.Append() = p;
00545       p[-1] = '\0';
00546       *p++ = c;
00547     }
00548 
00549     /* Skip the SCC_SETX(Y) ... */
00550     loc += len;
00551     /* ... copy the x coordinate ... */
00552     *p++ = *loc++;
00553     /* ... and finally copy the y coordinate if it exists */
00554     if (c == SCC_SETXY) *p++ = *loc++;
00555   }
00556 
00557   /* In case we have a RTL language we swap the alignment. */
00558   if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && !(align & SA_STRIP) && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
00559 
00560   for (UChar **iter = setx_offsets.Begin(); iter != setx_offsets.End(); iter++) {
00561     UChar *to_draw = *iter;
00562     int offset = 0;
00563 
00564     /* Skip the SETX(Y) and set the appropriate offsets. */
00565     if (*to_draw == SCC_SETX || *to_draw == SCC_SETXY) {
00566       to_draw++;
00567       offset = *to_draw++;
00568       if (*to_draw == SCC_SETXY) top = initial_top + *to_draw++;
00569     }
00570 
00571     to_draw = HandleBiDiAndArabicShapes(to_draw);
00572     int w = GetStringWidth(to_draw, params.fontsize);
00573 
00574     /* right is the right most position to draw on. In this case we want to do
00575      * calculations with the width of the string. In comparison right can be
00576      * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
00577      * So most +1/-1 additions are to move from lengthof to 'indices'.
00578      */
00579     switch (align & SA_HOR_MASK) {
00580       case SA_LEFT:
00581         /* right + 1 = left + w */
00582         left = initial_left + offset;
00583         right = left + w - 1;
00584         break;
00585 
00586       case SA_HOR_CENTER:
00587         left  = RoundDivSU(initial_right + 1 + initial_left - w, 2);
00588         /* right + 1 = left + w */
00589         right = left + w - 1;
00590         break;
00591 
00592       case SA_RIGHT:
00593         left = initial_right + 1 - w - offset;
00594         break;
00595 
00596       default:
00597         NOT_REACHED();
00598     }
00599 
00600     min_left  = min(left, min_left);
00601     max_right = max(right, max_right);
00602 
00603     ReallyDoDrawString(to_draw, left, top, params, !truncate);
00604     if (underline) {
00605       GfxFillRect(left, top + FONT_HEIGHT_NORMAL, right, top + FONT_HEIGHT_NORMAL, _string_colourremap[1]);
00606     }
00607   }
00608 
00609   return (align & SA_HOR_MASK) == SA_RIGHT ? min_left : max_right;
00610 }
00611 
00625 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline)
00626 {
00627   char buffer[DRAW_STRING_BUFFER];
00628   strecpy(buffer, str, lastof(buffer));
00629   DrawStringParams params(colour);
00630   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00631 }
00632 
00646 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline)
00647 {
00648   char buffer[DRAW_STRING_BUFFER];
00649   GetString(buffer, str, lastof(buffer));
00650   DrawStringParams params(colour);
00651   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00652 }
00653 
00674 uint32 FormatStringLinebreaks(char *str, const char *last, int maxw, FontSize size)
00675 {
00676   int num = 0;
00677 
00678   assert(maxw > 0);
00679 
00680   for (;;) {
00681     /* The character *after* the last space. */
00682     char *last_space = NULL;
00683     int w = 0;
00684 
00685     for (;;) {
00686       WChar c = Utf8Consume(const_cast<const char **>(&str));
00687       /* whitespace is where we will insert the line-break */
00688       if (IsWhitespace(c)) last_space = str;
00689 
00690       if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00691         int char_w = GetCharacterWidth(size, c);
00692         w += char_w;
00693         if (w > maxw) {
00694           /* The string is longer than maximum width so we need to decide
00695            * what to do with it. */
00696           if (w == char_w) {
00697             /* The character is wider than allowed width; don't know
00698              * what to do with this case... bail out! */
00699             return num + (size << 16);
00700           }
00701           if (last_space == NULL) {
00702             /* No space has been found. Just terminate at our current
00703              * location. This usually happens for languages that do not
00704              * require spaces in strings, like Chinese, Japanese and
00705              * Korean. For other languages terminating mid-word might
00706              * not be the best, but terminating the whole string instead
00707              * of continuing the word at the next line is worse. */
00708             str = Utf8PrevChar(str);
00709             size_t len = strlen(str);
00710             char *terminator = str + len;
00711 
00712             /* The string location + length of the string + 1 for '\0'
00713              * always fits; otherwise there's no trailing '\0' and it
00714              * it not a valid string. */
00715             assert(terminator <= last);
00716             assert(*terminator == '\0');
00717 
00718             /* If the string is too long we have to terminate it earlier. */
00719             if (terminator == last) {
00720               /* Get the 'begin' of the previous character and make that
00721                * the terminator of the string; we truncate it 'early'. */
00722               *Utf8PrevChar(terminator) = '\0';
00723               len = strlen(str);
00724             }
00725             /* Also move the terminator! */
00726             memmove(str + 1, str, len + 1);
00727             *str = '\0';
00728             /* str needs to point to the character *after* the last space */
00729             str++;
00730           } else {
00731             /* A space is found; perfect place to terminate */
00732             str = last_space;
00733           }
00734           break;
00735         }
00736       } else {
00737         switch (c) {
00738           case '\0': return num + (size << 16);
00739           case SCC_SETX:  str++; break;
00740           case SCC_SETXY: str += 2; break;
00741           case SCC_TINYFONT: size = FS_SMALL; break;
00742           case SCC_BIGFONT:  size = FS_LARGE; break;
00743           case '\n': goto end_of_inner_loop;
00744         }
00745       }
00746     }
00747 end_of_inner_loop:
00748     /* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
00749      * and increase linecount. We use Utf8PrevChar() as also non 1 char long
00750      * whitespace seperators are supported */
00751     num++;
00752     char *s = Utf8PrevChar(str);
00753     *s++ = '\0';
00754 
00755     /* In which case (see above) we will shift remainder to left and close the gap */
00756     if (str - s >= 1) {
00757       for (; str[-1] != '\0';) *s++ = *str++;
00758     }
00759   }
00760 }
00761 
00762 
00771 static int GetMultilineStringHeight(const char *src, int num, FontSize start_fontsize)
00772 {
00773   int maxy = 0;
00774   int y = 0;
00775   int fh = GetCharacterHeight(start_fontsize);
00776 
00777   for (;;) {
00778     WChar c = Utf8Consume(&src);
00779 
00780     switch (c) {
00781       case 0:            y += fh; if (--num < 0) return maxy; break;
00782       case '\n':         y += fh;                             break;
00783       case SCC_SETX:     src++;                               break;
00784       case SCC_SETXY:    src++; y = (int)*src++;              break;
00785       case SCC_TINYFONT: fh = GetCharacterHeight(FS_SMALL);   break;
00786       case SCC_BIGFONT:  fh = GetCharacterHeight(FS_LARGE);   break;
00787       default:           maxy = max<int>(maxy, y + fh);       break;
00788     }
00789   }
00790 }
00791 
00792 
00799 int GetStringHeight(StringID str, int maxw)
00800 {
00801   char buffer[DRAW_STRING_BUFFER];
00802 
00803   GetString(buffer, str, lastof(buffer));
00804 
00805   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00806 
00807   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00808 }
00809 
00816 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00817 {
00818   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00819   return box;
00820 }
00821 
00837 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline)
00838 {
00839   int maxw = right - left + 1;
00840   int maxh = bottom - top + 1;
00841 
00842   /* It makes no sense to even try if it can't be drawn anyway, or
00843    * do we really want to support fonts of 0 or less pixels high? */
00844   if (maxh <= 0) return top;
00845 
00846   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
00847   int num = GB(tmp, 0, 16) + 1;
00848 
00849   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
00850   int total_height = num * mt;
00851 
00852   int skip_lines = 0;
00853   if (total_height > maxh) {
00854     if (maxh < mt) return top; //  Not enough room for a single line.
00855     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
00856       skip_lines = num;
00857       num = maxh / mt;
00858       skip_lines -= num;
00859     } else {
00860       num = maxh / mt;
00861     }
00862     total_height = num * mt;
00863   }
00864 
00865   int y;
00866   switch (align & SA_VERT_MASK) {
00867     case SA_TOP:
00868       y = top;
00869       break;
00870 
00871     case SA_VERT_CENTER:
00872       y = RoundDivSU(bottom + top - total_height, 2);
00873       break;
00874 
00875     case SA_BOTTOM:
00876       y = bottom - total_height;
00877       break;
00878 
00879     default: NOT_REACHED();
00880   }
00881 
00882   const char *src = str;
00883   DrawStringParams params(colour);
00884   int written_top = bottom; // Uppermost position of rendering a line of text
00885   for (;;) {
00886     if (skip_lines == 0) {
00887       char buf2[DRAW_STRING_BUFFER];
00888       strecpy(buf2, src, lastof(buf2));
00889       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
00890       if (written_top > y) written_top = y;
00891       y += mt;
00892       num--;
00893     }
00894 
00895     for (;;) {
00896       WChar c = Utf8Consume(&src);
00897       if (c == 0) {
00898         break;
00899       } else if (c == SCC_SETX) {
00900         src++;
00901       } else if (c == SCC_SETXY) {
00902         src += 2;
00903       } else if (skip_lines > 0) {
00904         /* Skipped drawing, so do additional processing to update params. */
00905         if (c >= SCC_BLUE && c <= SCC_BLACK) {
00906           params.SetColour((TextColour)(c - SCC_BLUE));
00907         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
00908           params.SetPreviousColour();
00909         } else if (c == SCC_TINYFONT) {
00910           params.SetFontSize(FS_SMALL);
00911         } else if (c == SCC_BIGFONT) {
00912           params.SetFontSize(FS_LARGE);
00913         }
00914 
00915       }
00916     }
00917     if (skip_lines > 0) skip_lines--;
00918     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
00919   }
00920 }
00921 
00936 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline)
00937 {
00938   char buffer[DRAW_STRING_BUFFER];
00939   strecpy(buffer, str, lastof(buffer));
00940   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00941 }
00942 
00957 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline)
00958 {
00959   char buffer[DRAW_STRING_BUFFER];
00960   GetString(buffer, str, lastof(buffer));
00961   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00962 }
00963 
00974 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
00975 {
00976   FontSize size = start_fontsize;
00977   Dimension br;
00978   uint max_width;
00979   WChar c;
00980 
00981   br.width = br.height = max_width = 0;
00982   for (;;) {
00983     c = Utf8Consume(&str);
00984     if (c == 0) break;
00985     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00986       br.width += GetCharacterWidth(size, c);
00987     } else {
00988       switch (c) {
00989         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
00990         case SCC_SETXY:
00991           br.width  = max((uint)*str++, br.width);
00992           br.height = max((uint)*str++, br.height);
00993           break;
00994         case SCC_TINYFONT: size = FS_SMALL; break;
00995         case SCC_BIGFONT:  size = FS_LARGE; break;
00996         case '\n':
00997           br.height += GetCharacterHeight(size);
00998           if (br.width > max_width) max_width = br.width;
00999           br.width = 0;
01000           break;
01001       }
01002     }
01003   }
01004   br.height += GetCharacterHeight(size);
01005 
01006   br.width  = max(br.width, max_width);
01007   return br;
01008 }
01009 
01016 Dimension GetStringBoundingBox(StringID strid)
01017 {
01018   char buffer[DRAW_STRING_BUFFER];
01019 
01020   GetString(buffer, strid, lastof(buffer));
01021   return GetStringBoundingBox(buffer);
01022 }
01023 
01031 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
01032 {
01033   SetColourRemap(colour);
01034   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
01035 }
01036 
01054 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
01055 {
01056   DrawPixelInfo *dpi = _cur_dpi;
01057   UChar c;
01058   int xo = x;
01059 
01060   if (!parse_string_also_when_clipped) {
01061     /* in "mode multiline", the available space have been verified. Not in regular one.
01062      * So if the string cannot be drawn, return the original start to say so.*/
01063     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
01064   }
01065 
01066 switch_colour:;
01067   SetColourRemap(params.cur_colour);
01068 
01069 check_bounds:
01070   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
01071 skip_char:;
01072     for (;;) {
01073       c = *string++;
01074       if (!IsPrintable(c)) goto skip_cont;
01075     }
01076   }
01077 
01078   for (;;) {
01079     c = *string++;
01080 skip_cont:;
01081     if (c == 0) {
01082       return x;  // Nothing more to draw, get out. And here is the new x position
01083     }
01084     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01085       if (x >= dpi->left + dpi->width) goto skip_char;
01086       if (x + _max_char_width >= dpi->left) {
01087         GfxMainBlitter(GetGlyph(params.fontsize, c), x, y, BM_COLOUR_REMAP);
01088       }
01089       x += GetCharacterWidth(params.fontsize, c);
01090     } else if (c == '\n') { // newline = {}
01091       x = xo;  // We require a new line, so the x coordinate is reset
01092       y += GetCharacterHeight(params.fontsize);
01093       goto check_bounds;
01094     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
01095       params.SetColour((TextColour)(c - SCC_BLUE));
01096       goto switch_colour;
01097     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
01098       params.SetPreviousColour();
01099       goto switch_colour;
01100     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
01101       /* The characters are handled before calling this. */
01102       NOT_REACHED();
01103     } else if (c == SCC_TINYFONT) { // {TINYFONT}
01104       params.SetFontSize(FS_SMALL);
01105     } else if (c == SCC_BIGFONT) { // {BIGFONT}
01106       params.SetFontSize(FS_LARGE);
01107     } else if (!IsTextDirectionChar(c)) {
01108       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
01109     }
01110   }
01111 }
01112 
01119 Dimension GetSpriteSize(SpriteID sprid)
01120 {
01121   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
01122 
01123   Dimension d;
01124   d.width  = max<int>(0, sprite->x_offs + sprite->width);
01125   d.height = max<int>(0, sprite->y_offs + sprite->height);
01126   return d;
01127 }
01128 
01137 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
01138 {
01139   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01140   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01141     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01142     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
01143   } else if (pal != PAL_NONE) {
01144     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01145     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
01146   } else {
01147     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
01148   }
01149 }
01150 
01151 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
01152 {
01153   const DrawPixelInfo *dpi = _cur_dpi;
01154   Blitter::BlitterParams bp;
01155 
01156   /* Amount of pixels to clip from the source sprite */
01157   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
01158   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
01159   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
01160   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
01161 
01162   if (clip_left + clip_right >= sprite->width) return;
01163   if (clip_top + clip_bottom >= sprite->height) return;
01164 
01165   /* Move to the correct offset */
01166   x += sprite->x_offs;
01167   y += sprite->y_offs;
01168 
01169   /* Copy the main data directly from the sprite */
01170   bp.sprite = sprite->data;
01171   bp.sprite_width = sprite->width;
01172   bp.sprite_height = sprite->height;
01173   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
01174   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
01175   bp.top = 0;
01176   bp.left = 0;
01177   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
01178   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
01179 
01180   x += ScaleByZoom(bp.skip_left, dpi->zoom);
01181   y += ScaleByZoom(bp.skip_top, dpi->zoom);
01182 
01183   bp.dst = dpi->dst_ptr;
01184   bp.pitch = dpi->pitch;
01185   bp.remap = _colour_remap_ptr;
01186 
01187   assert(sprite->width > 0);
01188   assert(sprite->height > 0);
01189 
01190   if (bp.width <= 0) return;
01191   if (bp.height <= 0) return;
01192 
01193   y -= dpi->top;
01194   /* Check for top overflow */
01195   if (y < 0) {
01196     bp.height -= -UnScaleByZoom(y, dpi->zoom);
01197     if (bp.height <= 0) return;
01198     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
01199     y = 0;
01200   } else {
01201     bp.top = UnScaleByZoom(y, dpi->zoom);
01202   }
01203 
01204   /* Check for bottom overflow */
01205   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
01206   if (y > 0) {
01207     bp.height -= UnScaleByZoom(y, dpi->zoom);
01208     if (bp.height <= 0) return;
01209   }
01210 
01211   x -= dpi->left;
01212   /* Check for left overflow */
01213   if (x < 0) {
01214     bp.width -= -UnScaleByZoom(x, dpi->zoom);
01215     if (bp.width <= 0) return;
01216     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
01217     x = 0;
01218   } else {
01219     bp.left = UnScaleByZoom(x, dpi->zoom);
01220   }
01221 
01222   /* Check for right overflow */
01223   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
01224   if (x > 0) {
01225     bp.width -= UnScaleByZoom(x, dpi->zoom);
01226     if (bp.width <= 0) return;
01227   }
01228 
01229   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
01230   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
01231 
01232   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01233   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01234     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01235     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01236     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01237 
01238     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01239 
01240     if (topleft <= clicked && clicked <= bottomright) {
01241       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01242       if (offset < (uint)bp.width) {
01243         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01244       }
01245     }
01246   }
01247 
01248   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
01249 }
01250 
01251 void DoPaletteAnimations();
01252 
01253 void GfxInitPalettes()
01254 {
01255   memcpy(_cur_palette, _palettes[_use_palette], sizeof(_cur_palette));
01256 
01257   DoPaletteAnimations();
01258   _pal_first_dirty = 0;
01259   _pal_count_dirty = 256;
01260 }
01261 
01262 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01263 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01264 
01265 void DoPaletteAnimations()
01266 {
01267   /* Animation counter for the palette animation. */
01268   static int palette_animation_counter = 0;
01269   palette_animation_counter += 8;
01270 
01271   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01272   const Colour *s;
01273   const ExtraPaletteValues *ev = &_extra_palette_values;
01274   /* Amount of colours to be rotated.
01275    * A few more for the DOS palette, because the water colours are
01276    * 245-254 for DOS and 217-226 for Windows.  */
01277   const int colour_rotation_amount = (_use_palette == PAL_DOS) ? PALETTE_ANIM_SIZE_DOS : PALETTE_ANIM_SIZE_WIN;
01278   Colour old_val[PALETTE_ANIM_SIZE_DOS];
01279   const int oldval_size = colour_rotation_amount * sizeof(*old_val);
01280   const uint old_tc = palette_animation_counter;
01281   uint i;
01282   uint j;
01283 
01284   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01285     palette_animation_counter = 0;
01286   }
01287 
01288   Colour *palette_pos = &_cur_palette[PALETTE_ANIM_SIZE_START];  // Points to where animations are taking place on the palette
01289   /* Makes a copy of the current anmation palette in old_val,
01290    * so the work on the current palette could be compared, see if there has been any changes */
01291   memcpy(old_val, palette_pos, oldval_size);
01292 
01293   /* Dark blue water */
01294   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01295   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01296   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01297     *palette_pos++ = s[j];
01298     j++;
01299     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01300   }
01301 
01302   /* Glittery water; jumps over 3 colours each cycle! */
01303   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01304   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01305   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01306     *palette_pos++ = s[j];
01307     j += 3;
01308     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01309   }
01310 
01311   /* Fizzy Drink bubbles animation */
01312   s = ev->fizzy_drink;
01313   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01314   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01315     *palette_pos++ = s[j];
01316     j++;
01317     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01318   }
01319 
01320   /* Oil refinery fire animation */
01321   s = ev->oil_refinery;
01322   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01323   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01324     *palette_pos++ = s[j];
01325     j++;
01326     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01327   }
01328 
01329   /* Radio tower blinking */
01330   {
01331     byte i = (palette_animation_counter >> 1) & 0x7F;
01332     byte v;
01333 
01334     if (i < 0x3f) {
01335       v = 255;
01336     } else if (i < 0x4A || i >= 0x75) {
01337       v = 128;
01338     } else {
01339       v = 20;
01340     }
01341     palette_pos->r = v;
01342     palette_pos->g = 0;
01343     palette_pos->b = 0;
01344     palette_pos++;
01345 
01346     i ^= 0x40;
01347     if (i < 0x3f) {
01348       v = 255;
01349     } else if (i < 0x4A || i >= 0x75) {
01350       v = 128;
01351     } else {
01352       v = 20;
01353     }
01354     palette_pos->r = v;
01355     palette_pos->g = 0;
01356     palette_pos->b = 0;
01357     palette_pos++;
01358   }
01359 
01360   /* Handle lighthouse and stadium animation */
01361   s = ev->lighthouse;
01362   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01363   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01364     *palette_pos++ = s[j];
01365     j++;
01366     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01367   }
01368 
01369   /* Animate water for old DOS graphics */
01370   if (_use_palette == PAL_DOS) {
01371     /* Dark blue water DOS */
01372     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01373     j = EXTR(320, EPV_CYCLES_DARK_WATER);
01374     for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01375       *palette_pos++ = s[j];
01376       j++;
01377       if (j == EPV_CYCLES_DARK_WATER) j = 0;
01378     }
01379 
01380     /* Glittery water DOS */
01381     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01382     j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01383     for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01384       *palette_pos++ = s[j];
01385       j += 3;
01386       if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01387     }
01388   }
01389 
01390   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01391     palette_animation_counter = old_tc;
01392   } else {
01393     if (memcmp(old_val, &_cur_palette[PALETTE_ANIM_SIZE_START], oldval_size) != 0) {
01394       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01395       _pal_first_dirty = PALETTE_ANIM_SIZE_START;
01396       _pal_count_dirty = colour_rotation_amount;
01397     }
01398   }
01399 }
01400 
01401 
01403 void LoadStringWidthTable()
01404 {
01405   _max_char_height = 0;
01406   _max_char_width  = 0;
01407 
01408   for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
01409     _max_char_height = max<int>(_max_char_height, GetCharacterHeight(fs));
01410     for (uint i = 0; i != 224; i++) {
01411       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01412       _max_char_width = max<int>(_max_char_width, _stringwidth_table[fs][i]);
01413     }
01414   }
01415 
01416   /* Needed because they need to be 1 more than the widest. */
01417   _max_char_height++;
01418   _max_char_width++;
01419 
01420   ReInitAllWindows();
01421 }
01422 
01429 byte GetCharacterWidth(FontSize size, WChar key)
01430 {
01431   /* Use _stringwidth_table cache if possible */
01432   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01433 
01434   return GetGlyphWidth(size, key);
01435 }
01436 
01442 byte GetDigitWidth(FontSize size)
01443 {
01444   byte width = 0;
01445   for (char c = '0'; c <= '9'; c++) {
01446     width = max(GetCharacterWidth(size, c), width);
01447   }
01448   return width;
01449 }
01450 
01451 
01452 void ScreenSizeChanged()
01453 {
01454   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01455   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01456 
01457   /* check the dirty rect */
01458   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01459   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01460 
01461   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01462   _cursor.visible = false;
01463 }
01464 
01465 void UndrawMouseCursor()
01466 {
01467   /* Don't undraw the mouse cursor if the screen is not ready */
01468   if (_screen.dst_ptr == NULL) return;
01469 
01470   if (_cursor.visible) {
01471     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01472     _cursor.visible = false;
01473     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);
01474     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01475   }
01476 }
01477 
01478 void DrawMouseCursor()
01479 {
01480 #if defined(WINCE)
01481   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01482   return;
01483 #endif
01484 
01485   /* Don't draw the mouse cursor if the screen is not ready */
01486   if (_screen.dst_ptr == NULL) return;
01487 
01488   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01489   int x;
01490   int y;
01491   int w;
01492   int h;
01493 
01494   /* Redraw mouse cursor but only when it's inside the window */
01495   if (!_cursor.in_window) return;
01496 
01497   /* Don't draw the mouse cursor if it's already drawn */
01498   if (_cursor.visible) {
01499     if (!_cursor.dirty) return;
01500     UndrawMouseCursor();
01501   }
01502 
01503   w = _cursor.size.x;
01504   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01505   if (x < 0) {
01506     w += x;
01507     x = 0;
01508   }
01509   if (w > _screen.width - x) w = _screen.width - x;
01510   if (w <= 0) return;
01511   _cursor.draw_pos.x = x;
01512   _cursor.draw_size.x = w;
01513 
01514   h = _cursor.size.y;
01515   y = _cursor.pos.y + _cursor.offs.y;
01516   if (y < 0) {
01517     h += y;
01518     y = 0;
01519   }
01520   if (h > _screen.height - y) h = _screen.height - y;
01521   if (h <= 0) return;
01522   _cursor.draw_pos.y = y;
01523   _cursor.draw_size.y = h;
01524 
01525   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01526 
01527   /* Make backup of stuff below cursor */
01528   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01529 
01530   /* Draw cursor on screen */
01531   _cur_dpi = &_screen;
01532   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01533 
01534   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01535 
01536   _cursor.visible = true;
01537   _cursor.dirty = false;
01538 }
01539 
01540 void RedrawScreenRect(int left, int top, int right, int bottom)
01541 {
01542   assert(right <= _screen.width && bottom <= _screen.height);
01543   if (_cursor.visible) {
01544     if (right > _cursor.draw_pos.x &&
01545         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01546         bottom > _cursor.draw_pos.y &&
01547         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01548       UndrawMouseCursor();
01549     }
01550   }
01551 
01552 #ifdef ENABLE_NETWORK
01553   if (_networking) NetworkUndrawChatMessage();
01554 #endif /* ENABLE_NETWORK */
01555 
01556   DrawOverlappedWindowForAll(left, top, right, bottom);
01557 
01558   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01559 }
01560 
01566 void DrawDirtyBlocks()
01567 {
01568   byte *b = _dirty_blocks;
01569   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01570   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01571   int x;
01572   int y;
01573 
01574   if (IsGeneratingWorld()) {
01575     /* We are generating the world, so release our rights to the map and
01576      * painting while we are waiting a bit. */
01577     _genworld_paint_mutex->EndCritical();
01578     _genworld_mapgen_mutex->EndCritical();
01579 
01580     /* Wait a while and update _realtime_tick so we are given the rights */
01581     CSleep(GENWORLD_REDRAW_TIMEOUT);
01582     _realtime_tick += GENWORLD_REDRAW_TIMEOUT;
01583     _genworld_paint_mutex->BeginCritical();
01584     _genworld_mapgen_mutex->BeginCritical();
01585   }
01586 
01587   y = 0;
01588   do {
01589     x = 0;
01590     do {
01591       if (*b != 0) {
01592         int left;
01593         int top;
01594         int right = x + DIRTY_BLOCK_WIDTH;
01595         int bottom = y;
01596         byte *p = b;
01597         int h2;
01598 
01599         /* First try coalescing downwards */
01600         do {
01601           *p = 0;
01602           p += _dirty_bytes_per_line;
01603           bottom += DIRTY_BLOCK_HEIGHT;
01604         } while (bottom != h && *p != 0);
01605 
01606         /* Try coalescing to the right too. */
01607         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01608         assert(h2 > 0);
01609         p = b;
01610 
01611         while (right != w) {
01612           byte *p2 = ++p;
01613           int h = h2;
01614           /* Check if a full line of dirty flags is set. */
01615           do {
01616             if (!*p2) goto no_more_coalesc;
01617             p2 += _dirty_bytes_per_line;
01618           } while (--h != 0);
01619 
01620           /* Wohoo, can combine it one step to the right!
01621            * Do that, and clear the bits. */
01622           right += DIRTY_BLOCK_WIDTH;
01623 
01624           h = h2;
01625           p2 = p;
01626           do {
01627             *p2 = 0;
01628             p2 += _dirty_bytes_per_line;
01629           } while (--h != 0);
01630         }
01631         no_more_coalesc:
01632 
01633         left = x;
01634         top = y;
01635 
01636         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01637         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01638         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01639         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01640 
01641         if (left < right && top < bottom) {
01642           RedrawScreenRect(left, top, right, bottom);
01643         }
01644 
01645       }
01646     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01647   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01648 
01649   _invalid_rect.left = w;
01650   _invalid_rect.top = h;
01651   _invalid_rect.right = 0;
01652   _invalid_rect.bottom = 0;
01653 }
01654 
01670 void SetDirtyBlocks(int left, int top, int right, int bottom)
01671 {
01672   byte *b;
01673   int width;
01674   int height;
01675 
01676   if (left < 0) left = 0;
01677   if (top < 0) top = 0;
01678   if (right > _screen.width) right = _screen.width;
01679   if (bottom > _screen.height) bottom = _screen.height;
01680 
01681   if (left >= right || top >= bottom) return;
01682 
01683   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01684   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01685   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01686   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01687 
01688   left /= DIRTY_BLOCK_WIDTH;
01689   top  /= DIRTY_BLOCK_HEIGHT;
01690 
01691   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01692 
01693   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01694   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01695 
01696   assert(width > 0 && height > 0);
01697 
01698   do {
01699     int i = width;
01700 
01701     do b[--i] = 0xFF; while (i);
01702 
01703     b += _dirty_bytes_per_line;
01704   } while (--height != 0);
01705 }
01706 
01712 void MarkWholeScreenDirty()
01713 {
01714   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01715 }
01716 
01731 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01732 {
01733   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01734   const DrawPixelInfo *o = _cur_dpi;
01735 
01736   n->zoom = ZOOM_LVL_NORMAL;
01737 
01738   assert(width > 0);
01739   assert(height > 0);
01740 
01741   if ((left -= o->left) < 0) {
01742     width += left;
01743     if (width <= 0) return false;
01744     n->left = -left;
01745     left = 0;
01746   } else {
01747     n->left = 0;
01748   }
01749 
01750   if (width > o->width - left) {
01751     width = o->width - left;
01752     if (width <= 0) return false;
01753   }
01754   n->width = width;
01755 
01756   if ((top -= o->top) < 0) {
01757     height += top;
01758     if (height <= 0) return false;
01759     n->top = -top;
01760     top = 0;
01761   } else {
01762     n->top = 0;
01763   }
01764 
01765   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01766   n->pitch = o->pitch;
01767 
01768   if (height > o->height - top) {
01769     height = o->height - top;
01770     if (height <= 0) return false;
01771   }
01772   n->height = height;
01773 
01774   return true;
01775 }
01776 
01781 void UpdateCursorSize()
01782 {
01783   CursorVars *cv = &_cursor;
01784   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01785 
01786   cv->size.y = p->height;
01787   cv->size.x = p->width;
01788   cv->offs.x = p->x_offs;
01789   cv->offs.y = p->y_offs;
01790 
01791   cv->dirty = true;
01792 }
01793 
01799 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01800 {
01801   CursorVars *cv = &_cursor;
01802   if (cv->sprite == cursor) return;
01803 
01804   cv->sprite = cursor;
01805   cv->pal    = pal;
01806   UpdateCursorSize();
01807 
01808   cv->short_vehicle_offset = 0;
01809 }
01810 
01811 static void SwitchAnimatedCursor()
01812 {
01813   const AnimCursor *cur = _cursor.animate_cur;
01814 
01815   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01816 
01817   SetCursorSprite(cur->sprite, _cursor.pal);
01818 
01819   _cursor.animate_timeout = cur->display_time;
01820   _cursor.animate_cur     = cur + 1;
01821 }
01822 
01823 void CursorTick()
01824 {
01825   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01826     SwitchAnimatedCursor();
01827   }
01828 }
01829 
01836 void SetMouseCursor(CursorID sprite, PaletteID pal)
01837 {
01838   /* Turn off animation */
01839   _cursor.animate_timeout = 0;
01840   /* Set cursor */
01841   SetCursorSprite(sprite, pal);
01842 }
01843 
01849 void SetAnimatedMouseCursor(const AnimCursor *table)
01850 {
01851   _cursor.animate_list = table;
01852   _cursor.animate_cur = NULL;
01853   _cursor.pal = PAL_NONE;
01854   SwitchAnimatedCursor();
01855 }
01856 
01857 bool ChangeResInGame(int width, int height)
01858 {
01859   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
01860 }
01861 
01862 bool ToggleFullScreen(bool fs)
01863 {
01864   bool result = _video_driver->ToggleFullscreen(fs);
01865   if (_fullscreen != fs && _num_resolutions == 0) {
01866     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
01867   }
01868   return result;
01869 }
01870 
01871 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
01872 {
01873   int x = pa->width - pb->width;
01874   if (x != 0) return x;
01875   return pa->height - pb->height;
01876 }
01877 
01878 void SortResolutions(int count)
01879 {
01880   QSortT(_resolutions, count, &compare_res);
01881 }

Generated on Thu Dec 23 23:41:25 2010 for OpenTTD by  doxygen 1.6.1