gfx.cpp

Go to the documentation of this file.
00001 /* $Id: gfx.cpp 21845 2011-01-18 22:31:06Z 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   /* 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[_use_palette][colour];
00294   _string_colourremap[2] = no_shade ? 0 : (_use_palette == PAL_DOS ? 1 : 215);
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 
00626 int DrawString(int left, int right, int top, const char *str, TextColour colour, StringAlignment align, bool underline)
00627 {
00628   char buffer[DRAW_STRING_BUFFER];
00629   strecpy(buffer, str, lastof(buffer));
00630   DrawStringParams params(colour);
00631   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00632 }
00633 
00647 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline)
00648 {
00649   char buffer[DRAW_STRING_BUFFER];
00650   GetString(buffer, str, lastof(buffer));
00651   DrawStringParams params(colour);
00652   return DrawString(left, right, top, buffer, lastof(buffer), params, align, underline);
00653 }
00654 
00675 uint32 FormatStringLinebreaks(char *str, const char *last, int maxw, FontSize size)
00676 {
00677   int num = 0;
00678 
00679   assert(maxw > 0);
00680 
00681   for (;;) {
00682     /* The character *after* the last space. */
00683     char *last_space = NULL;
00684     int w = 0;
00685 
00686     for (;;) {
00687       WChar c = Utf8Consume(const_cast<const char **>(&str));
00688       /* whitespace is where we will insert the line-break */
00689       if (IsWhitespace(c)) last_space = str;
00690 
00691       if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00692         int char_w = GetCharacterWidth(size, c);
00693         w += char_w;
00694         if (w > maxw) {
00695           /* The string is longer than maximum width so we need to decide
00696            * what to do with it. */
00697           if (w == char_w) {
00698             /* The character is wider than allowed width; don't know
00699              * what to do with this case... bail out! */
00700             return num + (size << 16);
00701           }
00702           if (last_space == NULL) {
00703             /* No space has been found. Just terminate at our current
00704              * location. This usually happens for languages that do not
00705              * require spaces in strings, like Chinese, Japanese and
00706              * Korean. For other languages terminating mid-word might
00707              * not be the best, but terminating the whole string instead
00708              * of continuing the word at the next line is worse. */
00709             str = Utf8PrevChar(str);
00710             size_t len = strlen(str);
00711             char *terminator = str + len;
00712 
00713             /* The string location + length of the string + 1 for '\0'
00714              * always fits; otherwise there's no trailing '\0' and it
00715              * it not a valid string. */
00716             assert(terminator <= last);
00717             assert(*terminator == '\0');
00718 
00719             /* If the string is too long we have to terminate it earlier. */
00720             if (terminator == last) {
00721               /* Get the 'begin' of the previous character and make that
00722                * the terminator of the string; we truncate it 'early'. */
00723               *Utf8PrevChar(terminator) = '\0';
00724               len = strlen(str);
00725             }
00726             /* Also move the terminator! */
00727             memmove(str + 1, str, len + 1);
00728             *str = '\0';
00729             /* str needs to point to the character *after* the last space */
00730             str++;
00731           } else {
00732             /* A space is found; perfect place to terminate */
00733             str = last_space;
00734           }
00735           break;
00736         }
00737       } else {
00738         switch (c) {
00739           case '\0': return num + (size << 16);
00740           case SCC_SETX:  str++; break;
00741           case SCC_SETXY: str += 2; break;
00742           case SCC_TINYFONT: size = FS_SMALL; break;
00743           case SCC_BIGFONT:  size = FS_LARGE; break;
00744           case '\n': goto end_of_inner_loop;
00745         }
00746       }
00747     }
00748 end_of_inner_loop:
00749     /* String didn't fit on line (or a '\n' was encountered), so 'dummy' terminate
00750      * and increase linecount. We use Utf8PrevChar() as also non 1 char long
00751      * whitespace seperators are supported */
00752     num++;
00753     char *s = Utf8PrevChar(str);
00754     *s++ = '\0';
00755 
00756     /* In which case (see above) we will shift remainder to left and close the gap */
00757     if (str - s >= 1) {
00758       for (; str[-1] != '\0';) *s++ = *str++;
00759     }
00760   }
00761 }
00762 
00763 
00772 static int GetMultilineStringHeight(const char *src, int num, FontSize start_fontsize)
00773 {
00774   int maxy = 0;
00775   int y = 0;
00776   int fh = GetCharacterHeight(start_fontsize);
00777 
00778   for (;;) {
00779     WChar c = Utf8Consume(&src);
00780 
00781     switch (c) {
00782       case 0:            y += fh; if (--num < 0) return maxy; break;
00783       case '\n':         y += fh;                             break;
00784       case SCC_SETX:     src++;                               break;
00785       case SCC_SETXY:    src++; y = (int)*src++;              break;
00786       case SCC_TINYFONT: fh = GetCharacterHeight(FS_SMALL);   break;
00787       case SCC_BIGFONT:  fh = GetCharacterHeight(FS_LARGE);   break;
00788       default:           maxy = max<int>(maxy, y + fh);       break;
00789     }
00790   }
00791 }
00792 
00793 
00800 int GetStringHeight(StringID str, int maxw)
00801 {
00802   char buffer[DRAW_STRING_BUFFER];
00803 
00804   GetString(buffer, str, lastof(buffer));
00805 
00806   uint32 tmp = FormatStringLinebreaks(buffer, lastof(buffer), maxw);
00807 
00808   return GetMultilineStringHeight(buffer, GB(tmp, 0, 16), FS_NORMAL);
00809 }
00810 
00817 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
00818 {
00819   Dimension box = {suggestion.width, GetStringHeight(str, suggestion.width)};
00820   return box;
00821 }
00822 
00838 static int DrawStringMultiLine(int left, int right, int top, int bottom, char *str, const char *last, TextColour colour, StringAlignment align, bool underline)
00839 {
00840   int maxw = right - left + 1;
00841   int maxh = bottom - top + 1;
00842 
00843   /* It makes no sense to even try if it can't be drawn anyway, or
00844    * do we really want to support fonts of 0 or less pixels high? */
00845   if (maxh <= 0) return top;
00846 
00847   uint32 tmp = FormatStringLinebreaks(str, last, maxw);
00848   int num = GB(tmp, 0, 16) + 1;
00849 
00850   int mt = GetCharacterHeight((FontSize)GB(tmp, 16, 16));
00851   int total_height = num * mt;
00852 
00853   int skip_lines = 0;
00854   if (total_height > maxh) {
00855     if (maxh < mt) return top; //  Not enough room for a single line.
00856     if ((align & SA_VERT_MASK) == SA_BOTTOM) {
00857       skip_lines = num;
00858       num = maxh / mt;
00859       skip_lines -= num;
00860     } else {
00861       num = maxh / mt;
00862     }
00863     total_height = num * mt;
00864   }
00865 
00866   int y;
00867   switch (align & SA_VERT_MASK) {
00868     case SA_TOP:
00869       y = top;
00870       break;
00871 
00872     case SA_VERT_CENTER:
00873       y = RoundDivSU(bottom + top - total_height, 2);
00874       break;
00875 
00876     case SA_BOTTOM:
00877       y = bottom - total_height;
00878       break;
00879 
00880     default: NOT_REACHED();
00881   }
00882 
00883   const char *src = str;
00884   DrawStringParams params(colour);
00885   int written_top = bottom; // Uppermost position of rendering a line of text
00886   for (;;) {
00887     if (skip_lines == 0) {
00888       char buf2[DRAW_STRING_BUFFER];
00889       strecpy(buf2, src, lastof(buf2));
00890       DrawString(left, right, y, buf2, lastof(buf2), params, align, underline, false);
00891       if (written_top > y) written_top = y;
00892       y += mt;
00893       num--;
00894     }
00895 
00896     for (;;) {
00897       WChar c = Utf8Consume(&src);
00898       if (c == 0) {
00899         break;
00900       } else if (c == SCC_SETX) {
00901         src++;
00902       } else if (c == SCC_SETXY) {
00903         src += 2;
00904       } else if (skip_lines > 0) {
00905         /* Skipped drawing, so do additional processing to update params. */
00906         if (c >= SCC_BLUE && c <= SCC_BLACK) {
00907           params.SetColour((TextColour)(c - SCC_BLUE));
00908         } else if (c == SCC_PREVIOUS_COLOUR) { // Revert to the previous colour.
00909           params.SetPreviousColour();
00910         } else if (c == SCC_TINYFONT) {
00911           params.SetFontSize(FS_SMALL);
00912         } else if (c == SCC_BIGFONT) {
00913           params.SetFontSize(FS_LARGE);
00914         }
00915 
00916       }
00917     }
00918     if (skip_lines > 0) skip_lines--;
00919     if (num == 0) return ((align & SA_VERT_MASK) == SA_BOTTOM) ? written_top : y;
00920   }
00921 }
00922 
00937 int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour, StringAlignment align, bool underline)
00938 {
00939   char buffer[DRAW_STRING_BUFFER];
00940   strecpy(buffer, str, lastof(buffer));
00941   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00942 }
00943 
00958 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline)
00959 {
00960   char buffer[DRAW_STRING_BUFFER];
00961   GetString(buffer, str, lastof(buffer));
00962   return DrawStringMultiLine(left, right, top, bottom, buffer, lastof(buffer), colour, align, underline);
00963 }
00964 
00975 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
00976 {
00977   FontSize size = start_fontsize;
00978   Dimension br;
00979   uint max_width;
00980   WChar c;
00981 
00982   br.width = br.height = max_width = 0;
00983   for (;;) {
00984     c = Utf8Consume(&str);
00985     if (c == 0) break;
00986     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
00987       br.width += GetCharacterWidth(size, c);
00988     } else {
00989       switch (c) {
00990         case SCC_SETX: br.width = max((uint)*str++, br.width); break;
00991         case SCC_SETXY:
00992           br.width  = max((uint)*str++, br.width);
00993           br.height = max((uint)*str++, br.height);
00994           break;
00995         case SCC_TINYFONT: size = FS_SMALL; break;
00996         case SCC_BIGFONT:  size = FS_LARGE; break;
00997         case '\n':
00998           br.height += GetCharacterHeight(size);
00999           if (br.width > max_width) max_width = br.width;
01000           br.width = 0;
01001           break;
01002       }
01003     }
01004   }
01005   br.height += GetCharacterHeight(size);
01006 
01007   br.width  = max(br.width, max_width);
01008   return br;
01009 }
01010 
01017 Dimension GetStringBoundingBox(StringID strid)
01018 {
01019   char buffer[DRAW_STRING_BUFFER];
01020 
01021   GetString(buffer, strid, lastof(buffer));
01022   return GetStringBoundingBox(buffer);
01023 }
01024 
01032 void DrawCharCentered(WChar c, int x, int y, TextColour colour)
01033 {
01034   SetColourRemap(colour);
01035   GfxMainBlitter(GetGlyph(FS_NORMAL, c), x - GetCharacterWidth(FS_NORMAL, c) / 2, y, BM_COLOUR_REMAP);
01036 }
01037 
01055 static int ReallyDoDrawString(const UChar *string, int x, int y, DrawStringParams &params, bool parse_string_also_when_clipped)
01056 {
01057   DrawPixelInfo *dpi = _cur_dpi;
01058   UChar c;
01059   int xo = x;
01060 
01061   if (!parse_string_also_when_clipped) {
01062     /* in "mode multiline", the available space have been verified. Not in regular one.
01063      * So if the string cannot be drawn, return the original start to say so.*/
01064     if (x >= dpi->left + dpi->width || y >= dpi->top + dpi->height) return x;
01065   }
01066 
01067 switch_colour:;
01068   SetColourRemap(params.cur_colour);
01069 
01070 check_bounds:
01071   if (y + _max_char_height <= dpi->top || dpi->top + dpi->height <= y) {
01072 skip_char:;
01073     for (;;) {
01074       c = *string++;
01075       if (!IsPrintable(c)) goto skip_cont;
01076     }
01077   }
01078 
01079   for (;;) {
01080     c = *string++;
01081 skip_cont:;
01082     if (c == 0) {
01083       return x;  // Nothing more to draw, get out. And here is the new x position
01084     }
01085     if (IsPrintable(c) && !IsTextDirectionChar(c)) {
01086       if (x >= dpi->left + dpi->width) goto skip_char;
01087       if (x + _max_char_width >= dpi->left) {
01088         GfxMainBlitter(GetGlyph(params.fontsize, c), x, y, BM_COLOUR_REMAP);
01089       }
01090       x += GetCharacterWidth(params.fontsize, c);
01091     } else if (c == '\n') { // newline = {}
01092       x = xo;  // We require a new line, so the x coordinate is reset
01093       y += GetCharacterHeight(params.fontsize);
01094       goto check_bounds;
01095     } else if (c >= SCC_BLUE && c <= SCC_BLACK) { // change colour?
01096       params.SetColour((TextColour)(c - SCC_BLUE));
01097       goto switch_colour;
01098     } else if (c == SCC_PREVIOUS_COLOUR) { // revert to the previous colour
01099       params.SetPreviousColour();
01100       goto switch_colour;
01101     } else if (c == SCC_SETX || c == SCC_SETXY) { // {SETX}/{SETXY}
01102       /* The characters are handled before calling this. */
01103       NOT_REACHED();
01104     } else if (c == SCC_TINYFONT) { // {TINYFONT}
01105       params.SetFontSize(FS_SMALL);
01106     } else if (c == SCC_BIGFONT) { // {BIGFONT}
01107       params.SetFontSize(FS_LARGE);
01108     } else if (!IsTextDirectionChar(c)) {
01109       DEBUG(misc, 0, "[utf8] unknown string command character %d", c);
01110     }
01111   }
01112 }
01113 
01120 Dimension GetSpriteSize(SpriteID sprid)
01121 {
01122   const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
01123 
01124   Dimension d;
01125   d.width  = max<int>(0, sprite->x_offs + sprite->width);
01126   d.height = max<int>(0, sprite->y_offs + sprite->height);
01127   return d;
01128 }
01129 
01138 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
01139 {
01140   SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
01141   if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
01142     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01143     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_TRANSPARENT, sub, real_sprite);
01144   } else if (pal != PAL_NONE) {
01145     _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
01146     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_COLOUR_REMAP, sub, real_sprite);
01147   } else {
01148     GfxMainBlitter(GetSprite(real_sprite, ST_NORMAL), x, y, BM_NORMAL, sub, real_sprite);
01149   }
01150 }
01151 
01152 static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
01153 {
01154   const DrawPixelInfo *dpi = _cur_dpi;
01155   Blitter::BlitterParams bp;
01156 
01157   /* Amount of pixels to clip from the source sprite */
01158   int clip_left   = (sub != NULL ? max(0,                   -sprite->x_offs + sub->left       ) : 0);
01159   int clip_top    = (sub != NULL ? max(0,                   -sprite->y_offs + sub->top        ) : 0);
01160   int clip_right  = (sub != NULL ? max(0, sprite->width  - (-sprite->x_offs + sub->right  + 1)) : 0);
01161   int clip_bottom = (sub != NULL ? max(0, sprite->height - (-sprite->y_offs + sub->bottom + 1)) : 0);
01162 
01163   if (clip_left + clip_right >= sprite->width) return;
01164   if (clip_top + clip_bottom >= sprite->height) return;
01165 
01166   /* Move to the correct offset */
01167   x += sprite->x_offs;
01168   y += sprite->y_offs;
01169 
01170   /* Copy the main data directly from the sprite */
01171   bp.sprite = sprite->data;
01172   bp.sprite_width = sprite->width;
01173   bp.sprite_height = sprite->height;
01174   bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, dpi->zoom);
01175   bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, dpi->zoom);
01176   bp.top = 0;
01177   bp.left = 0;
01178   bp.skip_left = UnScaleByZoomLower(clip_left, dpi->zoom);
01179   bp.skip_top = UnScaleByZoomLower(clip_top, dpi->zoom);
01180 
01181   x += ScaleByZoom(bp.skip_left, dpi->zoom);
01182   y += ScaleByZoom(bp.skip_top, dpi->zoom);
01183 
01184   bp.dst = dpi->dst_ptr;
01185   bp.pitch = dpi->pitch;
01186   bp.remap = _colour_remap_ptr;
01187 
01188   assert(sprite->width > 0);
01189   assert(sprite->height > 0);
01190 
01191   if (bp.width <= 0) return;
01192   if (bp.height <= 0) return;
01193 
01194   y -= dpi->top;
01195   /* Check for top overflow */
01196   if (y < 0) {
01197     bp.height -= -UnScaleByZoom(y, dpi->zoom);
01198     if (bp.height <= 0) return;
01199     bp.skip_top += -UnScaleByZoom(y, dpi->zoom);
01200     y = 0;
01201   } else {
01202     bp.top = UnScaleByZoom(y, dpi->zoom);
01203   }
01204 
01205   /* Check for bottom overflow */
01206   y += ScaleByZoom(bp.height, dpi->zoom) - dpi->height;
01207   if (y > 0) {
01208     bp.height -= UnScaleByZoom(y, dpi->zoom);
01209     if (bp.height <= 0) return;
01210   }
01211 
01212   x -= dpi->left;
01213   /* Check for left overflow */
01214   if (x < 0) {
01215     bp.width -= -UnScaleByZoom(x, dpi->zoom);
01216     if (bp.width <= 0) return;
01217     bp.skip_left += -UnScaleByZoom(x, dpi->zoom);
01218     x = 0;
01219   } else {
01220     bp.left = UnScaleByZoom(x, dpi->zoom);
01221   }
01222 
01223   /* Check for right overflow */
01224   x += ScaleByZoom(bp.width, dpi->zoom) - dpi->width;
01225   if (x > 0) {
01226     bp.width -= UnScaleByZoom(x, dpi->zoom);
01227     if (bp.width <= 0) return;
01228   }
01229 
01230   assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, dpi->zoom));
01231   assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, dpi->zoom));
01232 
01233   /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
01234   if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
01235     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01236     void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
01237     void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
01238 
01239     void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
01240 
01241     if (topleft <= clicked && clicked <= bottomright) {
01242       uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
01243       if (offset < (uint)bp.width) {
01244         _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
01245       }
01246     }
01247   }
01248 
01249   BlitterFactoryBase::GetCurrentBlitter()->Draw(&bp, mode, dpi->zoom);
01250 }
01251 
01252 void DoPaletteAnimations();
01253 
01254 void GfxInitPalettes()
01255 {
01256   memcpy(_cur_palette, _palettes[_use_palette], sizeof(_cur_palette));
01257 
01258   DoPaletteAnimations();
01259   _pal_first_dirty = 0;
01260   _pal_count_dirty = 256;
01261 }
01262 
01263 #define EXTR(p, q) (((uint16)(palette_animation_counter * (p)) * (q)) >> 16)
01264 #define EXTR2(p, q) (((uint16)(~palette_animation_counter * (p)) * (q)) >> 16)
01265 
01266 void DoPaletteAnimations()
01267 {
01268   /* Animation counter for the palette animation. */
01269   static int palette_animation_counter = 0;
01270   palette_animation_counter += 8;
01271 
01272   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01273   const Colour *s;
01274   const ExtraPaletteValues *ev = &_extra_palette_values;
01275   /* Amount of colours to be rotated.
01276    * A few more for the DOS palette, because the water colours are
01277    * 245-254 for DOS and 217-226 for Windows.  */
01278   const int colour_rotation_amount = (_use_palette == PAL_DOS) ? PALETTE_ANIM_SIZE_DOS : PALETTE_ANIM_SIZE_WIN;
01279   Colour old_val[PALETTE_ANIM_SIZE_DOS];
01280   const int oldval_size = colour_rotation_amount * sizeof(*old_val);
01281   const uint old_tc = palette_animation_counter;
01282   uint i;
01283   uint j;
01284 
01285   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01286     palette_animation_counter = 0;
01287   }
01288 
01289   Colour *palette_pos = &_cur_palette[PALETTE_ANIM_SIZE_START];  // Points to where animations are taking place on the palette
01290   /* Makes a copy of the current anmation palette in old_val,
01291    * so the work on the current palette could be compared, see if there has been any changes */
01292   memcpy(old_val, palette_pos, oldval_size);
01293 
01294   /* Dark blue water */
01295   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01296   j = EXTR(320, EPV_CYCLES_DARK_WATER);
01297   for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01298     *palette_pos++ = s[j];
01299     j++;
01300     if (j == EPV_CYCLES_DARK_WATER) j = 0;
01301   }
01302 
01303   /* Glittery water; jumps over 3 colours each cycle! */
01304   s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01305   j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01306   for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01307     *palette_pos++ = s[j];
01308     j += 3;
01309     if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01310   }
01311 
01312   /* Fizzy Drink bubbles animation */
01313   s = ev->fizzy_drink;
01314   j = EXTR2(512, EPV_CYCLES_FIZZY_DRINK);
01315   for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
01316     *palette_pos++ = s[j];
01317     j++;
01318     if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
01319   }
01320 
01321   /* Oil refinery fire animation */
01322   s = ev->oil_refinery;
01323   j = EXTR2(512, EPV_CYCLES_OIL_REFINERY);
01324   for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
01325     *palette_pos++ = s[j];
01326     j++;
01327     if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
01328   }
01329 
01330   /* Radio tower blinking */
01331   {
01332     byte i = (palette_animation_counter >> 1) & 0x7F;
01333     byte v;
01334 
01335     if (i < 0x3f) {
01336       v = 255;
01337     } else if (i < 0x4A || i >= 0x75) {
01338       v = 128;
01339     } else {
01340       v = 20;
01341     }
01342     palette_pos->r = v;
01343     palette_pos->g = 0;
01344     palette_pos->b = 0;
01345     palette_pos++;
01346 
01347     i ^= 0x40;
01348     if (i < 0x3f) {
01349       v = 255;
01350     } else if (i < 0x4A || i >= 0x75) {
01351       v = 128;
01352     } else {
01353       v = 20;
01354     }
01355     palette_pos->r = v;
01356     palette_pos->g = 0;
01357     palette_pos->b = 0;
01358     palette_pos++;
01359   }
01360 
01361   /* Handle lighthouse and stadium animation */
01362   s = ev->lighthouse;
01363   j = EXTR(256, EPV_CYCLES_LIGHTHOUSE);
01364   for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
01365     *palette_pos++ = s[j];
01366     j++;
01367     if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
01368   }
01369 
01370   /* Animate water for old DOS graphics */
01371   if (_use_palette == PAL_DOS) {
01372     /* Dark blue water DOS */
01373     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
01374     j = EXTR(320, EPV_CYCLES_DARK_WATER);
01375     for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
01376       *palette_pos++ = s[j];
01377       j++;
01378       if (j == EPV_CYCLES_DARK_WATER) j = 0;
01379     }
01380 
01381     /* Glittery water DOS */
01382     s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
01383     j = EXTR(128, EPV_CYCLES_GLITTER_WATER);
01384     for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
01385       *palette_pos++ = s[j];
01386       j += 3;
01387       if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
01388     }
01389   }
01390 
01391   if (blitter != NULL && blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE) {
01392     palette_animation_counter = old_tc;
01393   } else {
01394     if (memcmp(old_val, &_cur_palette[PALETTE_ANIM_SIZE_START], oldval_size) != 0) {
01395       /* Did we changed anything on the palette? Seems so.  Mark it as dirty */
01396       _pal_first_dirty = PALETTE_ANIM_SIZE_START;
01397       _pal_count_dirty = colour_rotation_amount;
01398     }
01399   }
01400 }
01401 
01402 
01404 void LoadStringWidthTable()
01405 {
01406   _max_char_height = 0;
01407   _max_char_width  = 0;
01408 
01409   for (FontSize fs = FS_BEGIN; fs < FS_END; fs++) {
01410     _max_char_height = max<int>(_max_char_height, GetCharacterHeight(fs));
01411     for (uint i = 0; i != 224; i++) {
01412       _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
01413       _max_char_width = max<int>(_max_char_width, _stringwidth_table[fs][i]);
01414     }
01415   }
01416 
01417   /* Needed because they need to be 1 more than the widest. */
01418   _max_char_height++;
01419   _max_char_width++;
01420 
01421   ReInitAllWindows();
01422 }
01423 
01430 byte GetCharacterWidth(FontSize size, WChar key)
01431 {
01432   /* Use _stringwidth_table cache if possible */
01433   if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
01434 
01435   return GetGlyphWidth(size, key);
01436 }
01437 
01443 byte GetDigitWidth(FontSize size)
01444 {
01445   byte width = 0;
01446   for (char c = '0'; c <= '9'; c++) {
01447     width = max(GetCharacterWidth(size, c), width);
01448   }
01449   return width;
01450 }
01451 
01452 
01453 void ScreenSizeChanged()
01454 {
01455   _dirty_bytes_per_line = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
01456   _dirty_blocks = ReallocT<byte>(_dirty_blocks, _dirty_bytes_per_line * CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT));
01457 
01458   /* check the dirty rect */
01459   if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
01460   if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
01461 
01462   /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
01463   _cursor.visible = false;
01464 }
01465 
01466 void UndrawMouseCursor()
01467 {
01468   /* Don't undraw the mouse cursor if the screen is not ready */
01469   if (_screen.dst_ptr == NULL) return;
01470 
01471   if (_cursor.visible) {
01472     Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01473     _cursor.visible = false;
01474     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);
01475     _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01476   }
01477 }
01478 
01479 void DrawMouseCursor()
01480 {
01481 #if defined(WINCE)
01482   /* Don't ever draw the mouse for WinCE, as we work with a stylus */
01483   return;
01484 #endif
01485 
01486   /* Don't draw the mouse cursor if the screen is not ready */
01487   if (_screen.dst_ptr == NULL) return;
01488 
01489   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01490   int x;
01491   int y;
01492   int w;
01493   int h;
01494 
01495   /* Redraw mouse cursor but only when it's inside the window */
01496   if (!_cursor.in_window) return;
01497 
01498   /* Don't draw the mouse cursor if it's already drawn */
01499   if (_cursor.visible) {
01500     if (!_cursor.dirty) return;
01501     UndrawMouseCursor();
01502   }
01503 
01504   w = _cursor.size.x;
01505   x = _cursor.pos.x + _cursor.offs.x + _cursor.short_vehicle_offset;
01506   if (x < 0) {
01507     w += x;
01508     x = 0;
01509   }
01510   if (w > _screen.width - x) w = _screen.width - x;
01511   if (w <= 0) return;
01512   _cursor.draw_pos.x = x;
01513   _cursor.draw_size.x = w;
01514 
01515   h = _cursor.size.y;
01516   y = _cursor.pos.y + _cursor.offs.y;
01517   if (y < 0) {
01518     h += y;
01519     y = 0;
01520   }
01521   if (h > _screen.height - y) h = _screen.height - y;
01522   if (h <= 0) return;
01523   _cursor.draw_pos.y = y;
01524   _cursor.draw_size.y = h;
01525 
01526   uint8 *buffer = _cursor_backup.Allocate(blitter->BufferSize(w, h));
01527 
01528   /* Make backup of stuff below cursor */
01529   blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
01530 
01531   /* Draw cursor on screen */
01532   _cur_dpi = &_screen;
01533   DrawSprite(_cursor.sprite, _cursor.pal, _cursor.pos.x + _cursor.short_vehicle_offset, _cursor.pos.y);
01534 
01535   _video_driver->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
01536 
01537   _cursor.visible = true;
01538   _cursor.dirty = false;
01539 }
01540 
01541 void RedrawScreenRect(int left, int top, int right, int bottom)
01542 {
01543   assert(right <= _screen.width && bottom <= _screen.height);
01544   if (_cursor.visible) {
01545     if (right > _cursor.draw_pos.x &&
01546         left < _cursor.draw_pos.x + _cursor.draw_size.x &&
01547         bottom > _cursor.draw_pos.y &&
01548         top < _cursor.draw_pos.y + _cursor.draw_size.y) {
01549       UndrawMouseCursor();
01550     }
01551   }
01552 
01553 #ifdef ENABLE_NETWORK
01554   if (_networking) NetworkUndrawChatMessage();
01555 #endif /* ENABLE_NETWORK */
01556 
01557   DrawOverlappedWindowForAll(left, top, right, bottom);
01558 
01559   _video_driver->MakeDirty(left, top, right - left, bottom - top);
01560 }
01561 
01567 void DrawDirtyBlocks()
01568 {
01569   byte *b = _dirty_blocks;
01570   const int w = Align(_screen.width,  DIRTY_BLOCK_WIDTH);
01571   const int h = Align(_screen.height, DIRTY_BLOCK_HEIGHT);
01572   int x;
01573   int y;
01574 
01575   if (IsGeneratingWorld()) {
01576     /* We are generating the world, so release our rights to the map and
01577      * painting while we are waiting a bit. */
01578     _genworld_paint_mutex->EndCritical();
01579     _genworld_mapgen_mutex->EndCritical();
01580 
01581     /* Wait a while and update _realtime_tick so we are given the rights */
01582     CSleep(GENWORLD_REDRAW_TIMEOUT);
01583     _realtime_tick += GENWORLD_REDRAW_TIMEOUT;
01584     _genworld_paint_mutex->BeginCritical();
01585     _genworld_mapgen_mutex->BeginCritical();
01586   }
01587 
01588   y = 0;
01589   do {
01590     x = 0;
01591     do {
01592       if (*b != 0) {
01593         int left;
01594         int top;
01595         int right = x + DIRTY_BLOCK_WIDTH;
01596         int bottom = y;
01597         byte *p = b;
01598         int h2;
01599 
01600         /* First try coalescing downwards */
01601         do {
01602           *p = 0;
01603           p += _dirty_bytes_per_line;
01604           bottom += DIRTY_BLOCK_HEIGHT;
01605         } while (bottom != h && *p != 0);
01606 
01607         /* Try coalescing to the right too. */
01608         h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
01609         assert(h2 > 0);
01610         p = b;
01611 
01612         while (right != w) {
01613           byte *p2 = ++p;
01614           int h = h2;
01615           /* Check if a full line of dirty flags is set. */
01616           do {
01617             if (!*p2) goto no_more_coalesc;
01618             p2 += _dirty_bytes_per_line;
01619           } while (--h != 0);
01620 
01621           /* Wohoo, can combine it one step to the right!
01622            * Do that, and clear the bits. */
01623           right += DIRTY_BLOCK_WIDTH;
01624 
01625           h = h2;
01626           p2 = p;
01627           do {
01628             *p2 = 0;
01629             p2 += _dirty_bytes_per_line;
01630           } while (--h != 0);
01631         }
01632         no_more_coalesc:
01633 
01634         left = x;
01635         top = y;
01636 
01637         if (left   < _invalid_rect.left  ) left   = _invalid_rect.left;
01638         if (top    < _invalid_rect.top   ) top    = _invalid_rect.top;
01639         if (right  > _invalid_rect.right ) right  = _invalid_rect.right;
01640         if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
01641 
01642         if (left < right && top < bottom) {
01643           RedrawScreenRect(left, top, right, bottom);
01644         }
01645 
01646       }
01647     } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
01648   } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
01649 
01650   _invalid_rect.left = w;
01651   _invalid_rect.top = h;
01652   _invalid_rect.right = 0;
01653   _invalid_rect.bottom = 0;
01654 }
01655 
01671 void SetDirtyBlocks(int left, int top, int right, int bottom)
01672 {
01673   byte *b;
01674   int width;
01675   int height;
01676 
01677   if (left < 0) left = 0;
01678   if (top < 0) top = 0;
01679   if (right > _screen.width) right = _screen.width;
01680   if (bottom > _screen.height) bottom = _screen.height;
01681 
01682   if (left >= right || top >= bottom) return;
01683 
01684   if (left   < _invalid_rect.left  ) _invalid_rect.left   = left;
01685   if (top    < _invalid_rect.top   ) _invalid_rect.top    = top;
01686   if (right  > _invalid_rect.right ) _invalid_rect.right  = right;
01687   if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
01688 
01689   left /= DIRTY_BLOCK_WIDTH;
01690   top  /= DIRTY_BLOCK_HEIGHT;
01691 
01692   b = _dirty_blocks + top * _dirty_bytes_per_line + left;
01693 
01694   width  = ((right  - 1) / DIRTY_BLOCK_WIDTH)  - left + 1;
01695   height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top  + 1;
01696 
01697   assert(width > 0 && height > 0);
01698 
01699   do {
01700     int i = width;
01701 
01702     do b[--i] = 0xFF; while (i);
01703 
01704     b += _dirty_bytes_per_line;
01705   } while (--height != 0);
01706 }
01707 
01714 void MarkWholeScreenDirty()
01715 {
01716   SetDirtyBlocks(0, 0, _screen.width, _screen.height);
01717 }
01718 
01733 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
01734 {
01735   Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
01736   const DrawPixelInfo *o = _cur_dpi;
01737 
01738   n->zoom = ZOOM_LVL_NORMAL;
01739 
01740   assert(width > 0);
01741   assert(height > 0);
01742 
01743   if ((left -= o->left) < 0) {
01744     width += left;
01745     if (width <= 0) return false;
01746     n->left = -left;
01747     left = 0;
01748   } else {
01749     n->left = 0;
01750   }
01751 
01752   if (width > o->width - left) {
01753     width = o->width - left;
01754     if (width <= 0) return false;
01755   }
01756   n->width = width;
01757 
01758   if ((top -= o->top) < 0) {
01759     height += top;
01760     if (height <= 0) return false;
01761     n->top = -top;
01762     top = 0;
01763   } else {
01764     n->top = 0;
01765   }
01766 
01767   n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
01768   n->pitch = o->pitch;
01769 
01770   if (height > o->height - top) {
01771     height = o->height - top;
01772     if (height <= 0) return false;
01773   }
01774   n->height = height;
01775 
01776   return true;
01777 }
01778 
01783 void UpdateCursorSize()
01784 {
01785   CursorVars *cv = &_cursor;
01786   const Sprite *p = GetSprite(GB(cv->sprite, 0, SPRITE_WIDTH), ST_NORMAL);
01787 
01788   cv->size.y = p->height;
01789   cv->size.x = p->width;
01790   cv->offs.x = p->x_offs;
01791   cv->offs.y = p->y_offs;
01792 
01793   cv->dirty = true;
01794 }
01795 
01801 static void SetCursorSprite(CursorID cursor, PaletteID pal)
01802 {
01803   CursorVars *cv = &_cursor;
01804   if (cv->sprite == cursor) return;
01805 
01806   cv->sprite = cursor;
01807   cv->pal    = pal;
01808   UpdateCursorSize();
01809 
01810   cv->short_vehicle_offset = 0;
01811 }
01812 
01813 static void SwitchAnimatedCursor()
01814 {
01815   const AnimCursor *cur = _cursor.animate_cur;
01816 
01817   if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor.animate_list;
01818 
01819   SetCursorSprite(cur->sprite, _cursor.pal);
01820 
01821   _cursor.animate_timeout = cur->display_time;
01822   _cursor.animate_cur     = cur + 1;
01823 }
01824 
01825 void CursorTick()
01826 {
01827   if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
01828     SwitchAnimatedCursor();
01829   }
01830 }
01831 
01838 void SetMouseCursor(CursorID sprite, PaletteID pal)
01839 {
01840   /* Turn off animation */
01841   _cursor.animate_timeout = 0;
01842   /* Set cursor */
01843   SetCursorSprite(sprite, pal);
01844 }
01845 
01851 void SetAnimatedMouseCursor(const AnimCursor *table)
01852 {
01853   _cursor.animate_list = table;
01854   _cursor.animate_cur = NULL;
01855   _cursor.pal = PAL_NONE;
01856   SwitchAnimatedCursor();
01857 }
01858 
01859 bool ChangeResInGame(int width, int height)
01860 {
01861   return (_screen.width == width && _screen.height == height) || _video_driver->ChangeResolution(width, height);
01862 }
01863 
01864 bool ToggleFullScreen(bool fs)
01865 {
01866   bool result = _video_driver->ToggleFullscreen(fs);
01867   if (_fullscreen != fs && _num_resolutions == 0) {
01868     DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
01869   }
01870   return result;
01871 }
01872 
01873 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
01874 {
01875   int x = pa->width - pb->width;
01876   if (x != 0) return x;
01877   return pa->height - pb->height;
01878 }
01879 
01880 void SortResolutions(int count)
01881 {
01882   QSortT(_resolutions, count, &compare_res);
01883 }

Generated on Thu Jan 20 22:57:34 2011 for OpenTTD by  doxygen 1.6.1