# gfx.cpp

Go to the documentation of this file.

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