Add GlyphPos for a visual run glyph and its position
[openttd/fttd.git] / src / gfx.cpp
blob5ccace8bfad263c3a1c335e147bab2c59d802029
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file gfx.cpp Handling of drawing text and other gfx related stuff. */
12 #include "stdafx.h"
13 #include "debug.h"
14 #include "gfx_layout.h"
15 #include "progress.h"
16 #include "zoom_func.h"
17 #include "blitter/blitter.h"
18 #include "video/video_driver.hpp"
19 #include "strings_func.h"
20 #include "settings_type.h"
21 #include "network/network.h"
22 #include "network/network_func.h"
23 #include "window_func.h"
24 #include "newgrf_debug.h"
26 #include "table/palettes.h"
27 #include "table/string_colours.h"
28 #include "table/sprites.h"
29 #include "table/control_codes.h"
31 byte _dirkeys; ///< 1 = left, 2 = up, 4 = right, 8 = down
32 bool _fullscreen;
33 byte _support8bpp;
34 CursorVars _cursor;
35 static const AnimCursor *_cursor_animate_list; ///< in case of animated cursor, list of frames
36 static const AnimCursor *_cursor_animate_cur; ///< in case of animated cursor, current frame
37 static uint _cursor_animate_timeout; ///< in case of animated cursor, number of ticks to show the current cursor
39 bool _ctrl_pressed; ///< Is Ctrl pressed?
40 bool _shift_pressed; ///< Is Shift pressed?
41 byte _fast_forward;
42 bool _left_button_down; ///< Is left mouse button pressed?
43 bool _left_button_clicked; ///< Is left mouse button clicked?
44 bool _right_button_down; ///< Is right mouse button pressed?
45 bool _right_button_clicked; ///< Is right mouse button clicked?
47 ttd_unique_ptr <Blitter::Surface> _screen_surface;
48 int _screen_width, _screen_height;
50 bool _exit_game;
51 GameMode _game_mode;
52 SwitchMode _switch_mode; ///< The next mainloop command.
53 PauseModeByte _pause_mode;
54 Palette _cur_palette;
56 byte _colour_gradient[COLOUR_END][8];
58 static void GfxMainBlitterViewport (DrawPixelInfo *dpi, const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = NULL, SpriteID sprite_id = SPR_CURSOR_MOUSE);
59 static void GfxMainBlitter (BlitArea *dpi, const Sprite *sprite, int x, int y, BlitterMode mode, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZOOM_LVL_NORMAL);
61 static Blitter::Buffer _cursor_backup;
63 ZoomLevelByte _gui_zoom; ///< GUI Zoom level
65 /**
66 * The rect for repaint.
68 * This rectangle defines the area which should be repaint by the video driver.
70 * @ingroup dirty
72 static Rect _invalid_rect;
73 static const byte *_colour_remap_ptr;
74 static byte _string_colourremap[3]; ///< Recoloursprite for stringdrawing. The grf loader ensures that #ST_FONT sprites only use colours 0 to 2.
76 static const uint DIRTY_BLOCK_HEIGHT = 8;
77 static const uint DIRTY_BLOCK_WIDTH = 64;
79 static uint _dirty_bytes_per_line = 0;
80 static byte *_dirty_blocks = NULL;
81 extern uint _dirty_block_colour;
83 void GfxScroll(int left, int top, int width, int height, int xo, int yo)
85 if (xo == 0 && yo == 0) return;
87 if (_cursor.visible) UndrawMouseCursor();
89 #ifdef ENABLE_NETWORK
90 if (_networking) NetworkUndrawChatMessage();
91 #endif /* ENABLE_NETWORK */
93 _screen_surface->scroll (_screen_surface->ptr, left, top, width, height, xo, yo);
94 /* This part of the screen is now dirty. */
95 VideoDriver::GetActiveDriver()->MakeDirty(left, top, width, height);
99 /**
100 * Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
102 * @pre dpi->zoom == ZOOM_LVL_NORMAL, right >= left, bottom >= top
103 * @param dpi Area to blit to
104 * @param left Minimum X (inclusive)
105 * @param top Minimum Y (inclusive)
106 * @param right Maximum X (inclusive)
107 * @param bottom Maximum Y (inclusive)
108 * @param colour A 8 bit palette index (FILLRECT_OPAQUE and FILLRECT_CHECKER) or a recolour spritenumber (FILLRECT_RECOLOUR)
109 * @param mode
110 * FILLRECT_OPAQUE: Fill the rectangle with the specified colour
111 * FILLRECT_CHECKER: Like FILLRECT_OPAQUE, but only draw every second pixel (used to grey out things)
112 * FILLRECT_RECOLOUR: Apply a recolour sprite to every pixel in the rectangle currently on screen
114 void GfxFillRect (BlitArea *dpi, int left, int top, int right, int bottom, int colour, FillRectMode mode)
116 void *dst;
117 const int otopleft = top + left;
119 if (left > right || top > bottom) return;
120 if (right < dpi->left || left >= dpi->left + dpi->width) return;
121 if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
123 if ( (left -= dpi->left) < 0) left = 0;
124 right = right - dpi->left + 1;
125 if (right > dpi->width) right = dpi->width;
126 right -= left;
127 assert(right > 0);
129 if ( (top -= dpi->top) < 0) top = 0;
130 bottom = bottom - dpi->top + 1;
131 if (bottom > dpi->height) bottom = dpi->height;
132 bottom -= top;
133 assert(bottom > 0);
135 dst = dpi->surface->move (dpi->dst_ptr, left, top);
137 switch (mode) {
138 default: // FILLRECT_OPAQUE
139 dpi->surface->draw_rect (dst, right, bottom, (uint8)colour);
140 break;
142 case FILLRECT_RECOLOUR:
143 dpi->surface->recolour_rect (dst, right, bottom, GB(colour, 0, PALETTE_WIDTH));
144 break;
146 case FILLRECT_CHECKER: {
147 byte bo = (otopleft - left + dpi->left - top + dpi->top) & 1;
148 dpi->surface->draw_checker (dst, right, bottom, colour, bo);
149 break;
155 * Check line clipping by using a linear equation and draw the visible part of
156 * the line given by x/y and x2/y2.
157 * @param dpi Area to blit to.
158 * @param x X coordinate of first point.
159 * @param y Y coordinate of first point.
160 * @param x2 X coordinate of second point.
161 * @param y2 Y coordinate of second point.
162 * @param screen_width With of the screen to check clipping against.
163 * @param screen_height Height of the screen to check clipping against.
164 * @param colour Colour of the line.
165 * @param width Width of the line.
166 * @param dash Length of dashes for dashed lines. 0 means solid line.
168 static inline void GfxDoDrawLine (BlitArea *dpi, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8 colour, int width, int dash = 0)
170 assert(width > 0);
172 if (y2 == y || x2 == x) {
173 /* Special case: horizontal/vertical line. All checks already done in GfxPreprocessLine. */
174 } else {
175 int grade_y = y2 - y;
176 int grade_x = x2 - x;
178 /* Clipping rectangle. Slightly extended so we can ignore the width of the line. */
179 int extra = (int)CeilDiv(3 * width, 4); // not less then "width * sqrt(2) / 2"
180 int clip_left = -extra - x;
181 int clip_right = screen_width - 1 + extra - x;
183 /* prevent integer overflows. */
184 int margin = 1;
185 int dinf = max (abs (clip_left), abs (clip_right));
186 while (INT_MAX / abs(grade_y) < dinf) {
187 grade_y /= 2;
188 grade_x /= 2;
189 margin *= 2; // account for rounding errors
192 /* Imagine that the line is infinitely long and it intersects
193 * with infinitely long left and right edges of the clipping
194 * rectangle. If both intersection points are outside the
195 * clipping rectangle and both on the same side of it,
196 * we don't need to draw anything. */
197 int left_isec_y = y + clip_left * grade_y / grade_x;
198 int right_isec_y = y + clip_right * grade_y / grade_x;
200 int clip_bottom = screen_height - 1 + extra + margin;
201 if (left_isec_y > clip_bottom && right_isec_y > clip_bottom) return;
203 int clip_top = -extra - margin;
204 if (left_isec_y < clip_top && right_isec_y < clip_top) return;
206 /* It is possible to use the line equation to further reduce
207 * the amount of work the blitter has to do by shortening the
208 * effective line segment. However, in order to get that right
209 * and prevent the flickering effects of rounding errors so
210 * much additional code has to be run here that in the general
211 * case the effect is not noticable. */
214 dpi->surface->draw_line (dpi->dst_ptr, x, y, x2, y2, screen_width, screen_height, colour, width, dash);
218 * Align parameters of a line to the given DPI and check simple clipping.
219 * @param dpi Screen parameters to align with.
220 * @param x X coordinate of first point.
221 * @param y Y coordinate of first point.
222 * @param x2 X coordinate of second point.
223 * @param y2 Y coordinate of second point.
224 * @param width Width of the line.
225 * @return True if the line is likely to be visible, false if it's certainly
226 * invisible.
228 static inline bool GfxPreprocessLine (BlitArea *dpi, int &x, int &y, int &x2, int &y2, int width)
230 x -= dpi->left;
231 x2 -= dpi->left;
232 y -= dpi->top;
233 y2 -= dpi->top;
235 /* Check simple clipping */
236 if (x + width / 2 < 0 && x2 + width / 2 < 0 ) return false;
237 if (y + width / 2 < 0 && y2 + width / 2 < 0 ) return false;
238 if (x - width / 2 > dpi->width && x2 - width / 2 > dpi->width ) return false;
239 if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return false;
240 return true;
243 void GfxDrawLine (BlitArea *dpi, int x, int y, int x2, int y2, int colour, int width, int dash)
245 if (GfxPreprocessLine(dpi, x, y, x2, y2, width)) {
246 GfxDoDrawLine (dpi, x, y, x2, y2, dpi->width, dpi->height, colour, width, dash);
250 static void GfxDrawLineUnscaled (DrawPixelInfo *dpi, int x, int y, int x2, int y2, int colour)
252 if (GfxPreprocessLine(dpi, x, y, x2, y2, 1)) {
253 GfxDoDrawLine (dpi,
254 UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
255 UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
256 UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
261 * Draws the projection of a parallelepiped.
262 * This can be used to draw boxes in world coordinates.
263 * @param dpi Screen parameters to align with.
264 * @param x Screen X-coordinate of top front corner.
265 * @param y Screen Y-coordinate of top front corner.
266 * @param dx1 Screen X-length of first edge.
267 * @param dy1 Screen Y-length of first edge.
268 * @param dx2 Screen X-length of second edge.
269 * @param dy2 Screen Y-length of second edge.
270 * @param dx3 Screen X-length of third edge.
271 * @param dy3 Screen Y-length of third edge.
273 void DrawBox (DrawPixelInfo *dpi, int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
275 /* ....
276 * .. ....
277 * .. ....
278 * .. ^
279 * <--__(dx1,dy1) /(dx2,dy2)
280 * : --__ / :
281 * : --__ / :
282 * : *(x,y) :
283 * : | :
284 * : | ..
285 * .... |(dx3,dy3)
286 * .... | ..
287 * ....V.
290 static const byte colour = PC_WHITE;
292 GfxDrawLineUnscaled (dpi, x, y, x + dx1, y + dy1, colour);
293 GfxDrawLineUnscaled (dpi, x, y, x + dx2, y + dy2, colour);
294 GfxDrawLineUnscaled (dpi, x, y, x + dx3, y + dy3, colour);
296 GfxDrawLineUnscaled (dpi, x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
297 GfxDrawLineUnscaled (dpi, x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
298 GfxDrawLineUnscaled (dpi, x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
299 GfxDrawLineUnscaled (dpi, x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
300 GfxDrawLineUnscaled (dpi, x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
301 GfxDrawLineUnscaled (dpi, x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
305 * Set the colour remap to be for the given colour.
306 * @param colour the new colour of the remap.
308 static void SetColourRemap(TextColour colour)
310 if (colour == TC_INVALID) return;
312 /* Black strings have no shading ever; the shading is black, so it
313 * would be invisible at best, but it actually makes it illegible. */
314 bool no_shade = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
315 bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
316 colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR);
318 _string_colourremap[1] = raw_colour ? (byte)colour : _string_colourmap[colour];
319 _string_colourremap[2] = no_shade ? 0 : 1;
320 _colour_remap_ptr = _string_colourremap;
324 * Drawing routine for drawing a laid out line of text.
325 * @param line String to draw.
326 * @param dpi The area to draw on.
327 * @param y The top most position to draw on.
328 * @param left The left most position to draw on.
329 * @param right The right most position to draw on.
330 * @param align The alignment of the string when drawing left-to-right. In the
331 * case a right-to-left language is chosen this is inverted so it
332 * will be drawn in the right direction.
333 * @param underline Whether to underline what has been drawn or not.
334 * @param truncation Whether to perform string truncation or not.
336 * @return In case of left or center alignment the right most pixel we have drawn to.
337 * In case of right alignment the left most pixel we have drawn to.
339 static int DrawLayoutLine (const ParagraphLayouter::Line *line,
340 BlitArea *dpi, int y, int left, int right,
341 StringAlignment align, bool underline, bool truncation)
343 if (line->CountRuns() == 0) return 0;
345 int w = line->GetWidth();
346 int h = line->GetLeading();
349 * The following is needed for truncation.
350 * Depending on the text direction, we either remove bits at the rear
351 * or the front. For this we shift the entire area to draw so it fits
352 * within the left/right bounds and the side we do not truncate it on.
353 * Then we determine the truncation location, i.e. glyphs that fall
354 * outside of the range min_x - max_x will not be drawn; they are thus
355 * the truncated glyphs.
357 * At a later step we insert the dots.
360 int max_w = right - left + 1; // The maximum width.
362 int offset_x = 0; // The offset we need for positioning the glyphs
363 int min_x = left; // The minimum x position to draw normal glyphs on.
364 int max_x = right; // The maximum x position to draw normal glyphs on.
366 truncation &= max_w < w; // Whether we need to do truncation.
367 int dot_width = 0; // Cache for the width of the dot.
368 const Sprite *dot_sprite = NULL; // Cache for the sprite of the dot.
370 if (truncation) {
372 * Assumption may be made that all fonts of a run are of the same size.
373 * In any case, we'll use these dots for the abbreviation, so even if
374 * another size would be chosen it won't have truncated too little for
375 * the truncation dots.
377 FontCache *fc = line->GetVisualRun(0)->GetFont()->fc;
378 GlyphID dot_glyph = fc->MapCharToGlyph('.');
379 dot_width = fc->GetGlyphWidth(dot_glyph);
380 dot_sprite = fc->GetGlyph(dot_glyph);
382 if (_current_text_dir == TD_RTL) {
383 min_x += 3 * dot_width;
384 offset_x = w - 3 * dot_width - max_w;
385 } else {
386 max_x -= 3 * dot_width;
389 w = max_w;
392 /* In case we have a RTL language we swap the alignment. */
393 if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
395 /* right is the right most position to draw on. In this case we want to do
396 * calculations with the width of the string. In comparison right can be
397 * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
398 * So most +1/-1 additions are to move from lengthof to 'indices'.
400 switch (align & SA_HOR_MASK) {
401 case SA_LEFT:
402 /* right + 1 = left + w */
403 right = left + w - 1;
404 break;
406 case SA_HOR_CENTER:
407 left = RoundDivSU(right + 1 + left - w, 2);
408 /* right + 1 = left + w */
409 right = left + w - 1;
410 break;
412 case SA_RIGHT:
413 left = right + 1 - w;
414 break;
416 default:
417 NOT_REACHED();
420 TextColour colour = TC_BLACK;
421 bool draw_shadow = false;
422 for (int run_index = 0; run_index < line->CountRuns(); run_index++) {
423 const ParagraphLayouter::VisualRun *run = line->GetVisualRun(run_index);
424 const FontBase *f = run->GetFont();
426 FontCache *fc = f->fc;
427 colour = f->colour;
428 SetColourRemap(colour);
430 int dpi_left = dpi->left;
431 int dpi_right = dpi->left + dpi->width - 1;
433 draw_shadow = colour != TC_BLACK && (colour & TC_NO_SHADE) == 0 && fc->GetDrawGlyphShadow();
435 for (int i = 0; i < run->GetGlyphCount(); i++) {
436 ParagraphLayouter::GlyphPos gp;
437 /* Not a valid glyph (empty) */
438 if (!run->GetGlyphPos (&gp, i)) continue;
440 int begin_x = gp.x0 + left - offset_x;
441 int end_x = gp.x1 + left - offset_x - 1;
442 int top = gp.y + y;
444 /* Truncated away. */
445 if (truncation && (begin_x < min_x || end_x > max_x)) continue;
447 const Sprite *sprite = fc->GetGlyph (gp.glyph);
448 /* Check clipping (the "+ 1" is for the shadow). */
449 if (begin_x + sprite->x_offs > dpi_right || begin_x + sprite->x_offs + sprite->width /* - 1 + 1 */ < dpi_left) continue;
451 if (draw_shadow && (gp.glyph & SPRITE_GLYPH) == 0) {
452 SetColourRemap(TC_BLACK);
453 GfxMainBlitter (dpi, sprite, begin_x + 1, top + 1, BM_COLOUR_REMAP);
454 SetColourRemap(colour);
456 GfxMainBlitter (dpi, sprite, begin_x, top, BM_COLOUR_REMAP);
460 if (truncation) {
461 int x = (_current_text_dir == TD_RTL) ? left : (right - 3 * dot_width);
462 for (int i = 0; i < 3; i++, x += dot_width) {
463 if (draw_shadow) {
464 SetColourRemap(TC_BLACK);
465 GfxMainBlitter (dpi, dot_sprite, x + 1, y + 1, BM_COLOUR_REMAP);
466 SetColourRemap(colour);
468 GfxMainBlitter (dpi, dot_sprite, x, y, BM_COLOUR_REMAP);
472 if (underline) {
473 GfxFillRect (dpi, left, y + h, right, y + h, _string_colourremap[1]);
476 return (align & SA_HOR_MASK) == SA_RIGHT ? left : right;
480 * Draw string, possibly truncated to make it fit in its allocated space
482 * @param dpi The area to draw on.
483 * @param left The left most position to draw on.
484 * @param right The right most position to draw on.
485 * @param top The top most position to draw on.
486 * @param str String to draw.
487 * @param colour Colour used for drawing the string, see DoDrawString() for details
488 * @param align The alignment of the string when drawing left-to-right. In the
489 * case a right-to-left language is chosen this is inverted so it
490 * will be drawn in the right direction.
491 * @param underline Whether to underline what has been drawn or not.
492 * @param fontsize The size of the initial characters.
493 * @return In case of left or center alignment the right most pixel we have drawn to.
494 * In case of right alignment the left most pixel we have drawn to.
496 int DrawString (BlitArea *dpi, int left, int right, int top,
497 const char *str, TextColour colour, StringAlignment align,
498 bool underline, FontSize fontsize)
500 /* The string may contain control chars to change the font, just use the biggest font for clipping. */
501 int max_height = max(max(FONT_HEIGHT_SMALL, FONT_HEIGHT_NORMAL), max(FONT_HEIGHT_LARGE, FONT_HEIGHT_MONO));
503 /* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
504 int extra = max_height / 2;
506 if (dpi->top + dpi->height + extra < top || dpi->top > top + max_height + extra ||
507 dpi->left + dpi->width + extra < left || dpi->left > right + extra) {
508 return 0;
511 Layouter layout(str, INT32_MAX, colour, fontsize);
512 if (layout.empty()) return 0;
514 return DrawLayoutLine (layout.front().get(), dpi, top, left, right, align, underline, true);
518 * Draw string, possibly truncated to make it fit in its allocated space
520 * @param dpi The area to draw on.
521 * @param left The left most position to draw on.
522 * @param right The right most position to draw on.
523 * @param top The top most position to draw on.
524 * @param str String to draw.
525 * @param colour Colour used for drawing the string, see DoDrawString() for details
526 * @param align The alignment of the string when drawing left-to-right. In the
527 * case a right-to-left language is chosen this is inverted so it
528 * will be drawn in the right direction.
529 * @param underline Whether to underline what has been drawn or not.
530 * @param fontsize The size of the initial characters.
531 * @return In case of left or center alignment the right most pixel we have drawn to.
532 * In case of right alignment the left most pixel we have drawn to.
534 int DrawString (BlitArea *dpi, int left, int right, int top,
535 StringID str, TextColour colour, StringAlignment align,
536 bool underline, FontSize fontsize)
538 char buffer[DRAW_STRING_BUFFER];
539 GetString (buffer, str);
540 return DrawString (dpi, left, right, top, buffer, colour, align, underline, fontsize);
544 * Calculates height of string (in pixels). The string is changed to a multiline string if needed.
545 * @param str string to check
546 * @param maxw maximum string width
547 * @return height of pixels of string when it is drawn
549 uint GetStringHeight (const char *str, int maxw, FontSize fontsize)
551 Layouter layout(str, maxw, TC_FROMSTRING, fontsize);
552 return layout.GetBounds().height;
556 * Calculates height of string (in pixels). The string is changed to a multiline string if needed.
557 * @param str string to check
558 * @param maxw maximum string width
559 * @return height of pixels of string when it is drawn
561 uint GetStringHeight (StringID str, int maxw)
563 char buffer[DRAW_STRING_BUFFER];
564 GetString (buffer, str);
565 return GetStringHeight(buffer, maxw);
569 * Calculates number of lines of string. The string is changed to a multiline string if needed.
570 * @param str string to check
571 * @param maxw maximum string width
572 * @return number of lines of string when it is drawn
574 int GetStringLineCount(StringID str, int maxw)
576 char buffer[DRAW_STRING_BUFFER];
577 GetString (buffer, str);
579 Layouter layout(buffer, maxw);
580 return layout.size();
584 * Draw string, possibly over multiple lines.
586 * @param dpi The area to draw on.
587 * @param left The left most position to draw on.
588 * @param right The right most position to draw on.
589 * @param top The top most position to draw on.
590 * @param bottom The bottom most position to draw on.
591 * @param str String to draw.
592 * @param colour Colour used for drawing the string, see DoDrawString() for details
593 * @param align The horizontal and vertical alignment of the string.
594 * @param underline Whether to underline all strings
595 * @param fontsize The size of the initial characters.
597 * @return If \a align is #SA_BOTTOM, the top to where we have written, else the bottom to where we have written.
599 int DrawStringMultiLine (BlitArea *dpi, int left, int right, int top, int bottom,
600 const char *str, TextColour colour, StringAlignment align,
601 bool underline, FontSize fontsize)
603 int maxw = right - left + 1;
604 int maxh = bottom - top + 1;
606 /* It makes no sense to even try if it can't be drawn anyway, or
607 * do we really want to support fonts of 0 or less pixels high? */
608 if (maxh <= 0) return top;
610 Layouter layout(str, maxw, colour, fontsize);
611 int total_height = layout.GetBounds().height;
612 int y;
613 switch (align & SA_VERT_MASK) {
614 case SA_TOP:
615 y = top;
616 break;
618 case SA_VERT_CENTER:
619 y = RoundDivSU(bottom + top - total_height, 2);
620 break;
622 case SA_BOTTOM:
623 y = bottom - total_height;
624 break;
626 default: NOT_REACHED();
629 int last_line = top;
630 int first_line = bottom;
632 for (Layouter::const_iterator iter (layout.begin()); iter != layout.end(); iter++) {
633 const ParagraphLayouter::Line *line = iter->get();
635 int line_height = line->GetLeading();
636 if (y >= top && y < bottom) {
637 last_line = y + line_height;
638 if (first_line > y) first_line = y;
640 DrawLayoutLine (line, dpi, y, left, right, align, underline, false);
642 y += line_height;
645 return ((align & SA_VERT_MASK) == SA_BOTTOM) ? first_line : last_line;
649 * Draw string, possibly over multiple lines.
651 * @param dpi The area to draw on.
652 * @param left The left most position to draw on.
653 * @param right The right most position to draw on.
654 * @param top The top most position to draw on.
655 * @param bottom The bottom most position to draw on.
656 * @param str String to draw.
657 * @param colour Colour used for drawing the string, see DoDrawString() for details
658 * @param align The horizontal and vertical alignment of the string.
659 * @param underline Whether to underline all strings
660 * @param fontsize The size of the initial characters.
662 * @return If \a align is #SA_BOTTOM, the top to where we have written, else the bottom to where we have written.
664 int DrawStringMultiLine (BlitArea *dpi, int left, int right, int top, int bottom,
665 StringID str, TextColour colour, StringAlignment align,
666 bool underline, FontSize fontsize)
668 char buffer[DRAW_STRING_BUFFER];
669 GetString (buffer, str);
670 return DrawStringMultiLine (dpi, left, right, top, bottom, buffer, colour, align, underline, fontsize);
674 * Return the string dimension in pixels. The height and width are returned
675 * in a single Dimension value. TINYFONT, BIGFONT modifiers are only
676 * supported as the first character of the string. The returned dimensions
677 * are therefore a rough estimation correct for all the current strings
678 * but not every possible combination
679 * @param str string to calculate pixel-width
680 * @param start_fontsize Fontsize to start the text with
681 * @return string width and height in pixels
683 Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize)
685 Layouter layout(str, INT32_MAX, TC_FROMSTRING, start_fontsize);
686 return layout.GetBounds();
690 * Get bounding box of a string. Uses parameters set by #DParam if needed.
691 * Has the same restrictions as #GetStringBoundingBox(const char *str).
692 * @param strid String to examine.
693 * @return Width and height of the bounding box for the string in pixels.
695 Dimension GetStringBoundingBox(StringID strid)
697 char buffer[DRAW_STRING_BUFFER];
699 GetString (buffer, strid);
700 return GetStringBoundingBox(buffer);
704 * Draw single character horizontally centered around (x,y)
705 * @param dpi The area to draw on.
706 * @param c Character (glyph) to draw
707 * @param x X position to draw character
708 * @param y Y position to draw character
709 * @param colour Colour to use, see DoDrawString() for details
711 void DrawCharCentered (BlitArea *dpi, WChar c, int x, int y, TextColour colour)
713 SetColourRemap(colour);
714 FontCache *fc = FontCache::Get (FS_NORMAL);
715 GfxMainBlitter (dpi, fc->GetCharGlyph (c),
716 x - fc->GetCharacterWidth(c) / 2, y, BM_COLOUR_REMAP);
720 * Get the size of a sprite.
721 * @param sprid Sprite to examine.
722 * @param [out] offset Optionally returns the sprite position offset.
723 * @return Sprite size in pixels.
724 * @note The size assumes (0, 0) as top-left coordinate and ignores any part of the sprite drawn at the left or above that position.
726 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
728 const Sprite *sprite = GetSprite(sprid, ST_NORMAL);
730 if (offset != NULL) {
731 offset->x = UnScaleByZoom(sprite->x_offs, zoom);
732 offset->y = UnScaleByZoom(sprite->y_offs, zoom);
735 Dimension d;
736 d.width = max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
737 d.height = max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
738 return d;
742 * Set up the colour remap for a sprite.
743 * @param img The sprite to draw.
744 * @param pal The palette to use.
745 * @return The BlitterMode to use for drawing.
747 static BlitterMode GetBlitterMode (SpriteID img, PaletteID pal)
749 if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
750 _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
751 return BM_TRANSPARENT;
752 } else if (pal == PAL_NONE) {
753 return BM_NORMAL;
754 } else if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) {
755 SetColourRemap ((TextColour)GB(pal, 0, PALETTE_WIDTH));
756 return BM_COLOUR_REMAP;
757 } else {
758 _colour_remap_ptr = GetNonSprite (GB(pal, 0, PALETTE_WIDTH), ST_RECOLOUR) + 1;
759 switch (pal) {
760 case PALETTE_CRASH: return BM_CRASH_REMAP;
761 case PALETTE_ALL_BLACK: return BM_BLACK_REMAP;
762 default: return BM_COLOUR_REMAP;
768 * Draw a sprite in a viewport.
769 * @param dpi The area to draw on.
770 * @param img Image number to draw
771 * @param pal Palette to use.
772 * @param x Left coordinate of image in viewport, scaled by zoom
773 * @param y Top coordinate of image in viewport, scaled by zoom
774 * @param sub If available, draw only specified part of the sprite
776 void DrawSpriteViewport (DrawPixelInfo *dpi, SpriteID img, PaletteID pal,
777 int x, int y, const SubSprite *sub)
779 BlitterMode bm = GetBlitterMode (img, pal);
780 SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
781 GfxMainBlitterViewport (dpi, GetSprite (real_sprite, ST_NORMAL), x, y, bm, sub, real_sprite);
785 * Draw a sprite, not in a viewport
786 * @param dpi The area to draw on.
787 * @param img Image number to draw
788 * @param pal Palette to use.
789 * @param x Left coordinate of image in pixels
790 * @param y Top coordinate of image in pixels
792 void DrawSprite (BlitArea *dpi, SpriteID img, PaletteID pal, int x, int y)
794 BlitterMode bm = GetBlitterMode (img, pal);
795 SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
796 GfxMainBlitter (dpi, GetSprite (real_sprite, ST_NORMAL), x, y, bm, real_sprite, ZOOM_LVL_GUI);
800 * The code for setting up the blitter mode and sprite information before finally drawing the sprite.
801 * @param dpi The area to draw on.
802 * @param sprite The sprite to draw.
803 * @param x The X location to draw.
804 * @param y The Y location to draw.
805 * @param mode The settings for the blitter to pass.
806 * @param sub Whether to only draw a sub set of the sprite.
807 * @param zoom The zoom level at which to draw the sprites.
808 * @tparam SCALED_XY Whether the X and Y are scaled or unscaled.
810 template <bool SCALED_XY>
811 static void GfxBlitter (BlitArea *dpi, const Sprite * const sprite,
812 int x, int y, BlitterMode mode, const SubSprite * const sub,
813 SpriteID sprite_id, ZoomLevel zoom)
815 Blitter::BlitterParams bp;
817 if (SCALED_XY) {
818 /* Scale it */
819 x = ScaleByZoom(x, zoom);
820 y = ScaleByZoom(y, zoom);
823 /* Move to the correct offset */
824 x += sprite->x_offs;
825 y += sprite->y_offs;
827 if (sub == NULL) {
828 /* No clipping. */
829 bp.skip_left = 0;
830 bp.skip_top = 0;
831 bp.width = UnScaleByZoom(sprite->width, zoom);
832 bp.height = UnScaleByZoom(sprite->height, zoom);
833 } else {
834 assert (!SCALED_XY);
836 /* Amount of pixels to clip from the source sprite */
837 int clip_left = max (0, -sprite->x_offs + sub->left * ZOOM_LVL_BASE );
838 int clip_top = max (0, -sprite->y_offs + sub->top * ZOOM_LVL_BASE );
839 int clip_right = max (0, sprite->width - (-sprite->x_offs + (sub->right + 1) * ZOOM_LVL_BASE));
840 int clip_bottom = max (0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_LVL_BASE));
842 if (clip_left + clip_right >= sprite->width) return;
843 if (clip_top + clip_bottom >= sprite->height) return;
845 bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
846 bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
847 bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, zoom);
848 bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, zoom);
850 x += ScaleByZoom(bp.skip_left, zoom);
851 y += ScaleByZoom(bp.skip_top, zoom);
854 /* Copy the main data directly from the sprite */
855 bp.sprite = sprite;
856 bp.top = 0;
857 bp.left = 0;
859 bp.dst = dpi->dst_ptr;
860 bp.pitch = dpi->surface->pitch;
861 bp.remap = _colour_remap_ptr;
863 assert(sprite->width > 0);
864 assert(sprite->height > 0);
866 if (bp.width <= 0) return;
867 if (bp.height <= 0) return;
869 y -= SCALED_XY ? ScaleByZoom(dpi->top, zoom) : dpi->top;
870 int y_unscaled = UnScaleByZoom(y, zoom);
871 /* Check for top overflow */
872 if (y < 0) {
873 bp.height -= -y_unscaled;
874 if (bp.height <= 0) return;
875 bp.skip_top += -y_unscaled;
876 y = 0;
877 } else {
878 bp.top = y_unscaled;
881 /* Check for bottom overflow */
882 y += SCALED_XY ? ScaleByZoom(bp.height - dpi->height, zoom) : ScaleByZoom(bp.height, zoom) - dpi->height;
883 if (y > 0) {
884 bp.height -= UnScaleByZoom(y, zoom);
885 if (bp.height <= 0) return;
888 x -= SCALED_XY ? ScaleByZoom(dpi->left, zoom) : dpi->left;
889 int x_unscaled = UnScaleByZoom(x, zoom);
890 /* Check for left overflow */
891 if (x < 0) {
892 bp.width -= -x_unscaled;
893 if (bp.width <= 0) return;
894 bp.skip_left += -x_unscaled;
895 x = 0;
896 } else {
897 bp.left = x_unscaled;
900 /* Check for right overflow */
901 x += SCALED_XY ? ScaleByZoom(bp.width - dpi->width, zoom) : ScaleByZoom(bp.width, zoom) - dpi->width;
902 if (x > 0) {
903 bp.width -= UnScaleByZoom(x, zoom);
904 if (bp.width <= 0) return;
907 assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, zoom));
908 assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, zoom));
910 /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
911 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
912 void *topleft = dpi->surface->move (bp.dst, bp.left, bp.top);
913 void *bottomright = dpi->surface->move (topleft, bp.width - 1, bp.height - 1);
915 void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
917 if (topleft <= clicked && clicked <= bottomright) {
918 uint offset = (((size_t)clicked - (size_t)topleft) / (Blitter::get()->GetScreenDepth() / 8)) % bp.pitch;
919 if (offset < (uint)bp.width) {
920 _newgrf_debug_sprite_picker.sprites.Include(sprite_id);
925 dpi->surface->draw (&bp, mode, zoom);
928 static void GfxMainBlitterViewport (DrawPixelInfo *dpi, const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
930 GfxBlitter <false> (dpi, sprite, x, y, mode, sub, sprite_id, dpi->zoom);
933 static void GfxMainBlitter (BlitArea *dpi, const Sprite *sprite, int x, int y, BlitterMode mode, SpriteID sprite_id, ZoomLevel zoom)
935 GfxBlitter <true> (dpi, sprite, x, y, mode, NULL, sprite_id, zoom);
939 * Compute the cycle in an animation.
940 * @param x Global animation counter.
941 * @param n Number of cycles in the animation.
942 * @param s Animation speed factor (higher is slower).
944 static inline uint get_animation_cycle (uint x, uint n, uint s)
946 return ((x & ((1 << s) - 1)) * n) >> s;
949 void DoPaletteAnimations()
951 /* Animation counter for the palette animation. */
952 static uint palette_animation_counter = 0;
953 palette_animation_counter++;
955 Blitter *blitter = Blitter::get();
956 bool noanim = (blitter != NULL) && (blitter->UsePaletteAnimation() == Blitter::PALETTE_ANIMATION_NONE);
957 const uint tc = noanim ? 0 : palette_animation_counter;
959 const Colour *s;
960 const ExtraPaletteValues *ev = &_extra_palette_values;
961 Colour old_val[PALETTE_ANIM_SIZE];
962 uint i;
963 uint j;
965 Colour *palette_pos = &_cur_palette.palette[PALETTE_ANIM_START]; // Points to where animations are taking place on the palette
966 /* Makes a copy of the current animation palette in old_val,
967 * so the work on the current palette could be compared, see if there has been any changes */
968 memcpy(old_val, palette_pos, sizeof(old_val));
970 /* Fizzy Drink bubbles animation */
971 s = ev->fizzy_drink;
972 j = get_animation_cycle (~tc, EPV_CYCLES_FIZZY_DRINK, 4);
973 for (i = 0; i != EPV_CYCLES_FIZZY_DRINK; i++) {
974 *palette_pos++ = s[j];
975 j++;
976 if (j == EPV_CYCLES_FIZZY_DRINK) j = 0;
979 /* Oil refinery fire animation */
980 s = ev->oil_refinery;
981 j = get_animation_cycle (~tc, EPV_CYCLES_OIL_REFINERY, 4);
982 for (i = 0; i != EPV_CYCLES_OIL_REFINERY; i++) {
983 *palette_pos++ = s[j];
984 j++;
985 if (j == EPV_CYCLES_OIL_REFINERY) j = 0;
988 /* Radio tower blinking */
990 byte v = (((tc & 0x0F) - 0x3) > 0xA) ? 128 : 20;
991 bool b = (tc & 0x10) != 0;
993 palette_pos->r = b ? v : 255;
994 palette_pos->g = 0;
995 palette_pos->b = 0;
996 palette_pos++;
998 palette_pos->r = b ? 255 : v;
999 palette_pos->g = 0;
1000 palette_pos->b = 0;
1001 palette_pos++;
1004 /* Handle lighthouse and stadium animation */
1005 s = ev->lighthouse;
1006 j = get_animation_cycle (tc, EPV_CYCLES_LIGHTHOUSE, 5);
1007 for (i = 0; i != EPV_CYCLES_LIGHTHOUSE; i++) {
1008 *palette_pos++ = s[j];
1009 j++;
1010 if (j == EPV_CYCLES_LIGHTHOUSE) j = 0;
1013 /* Dark blue water */
1014 s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->dark_water_toyland : ev->dark_water;
1015 j = get_animation_cycle (tc * 10, EPV_CYCLES_DARK_WATER, 8);
1016 for (i = 0; i != EPV_CYCLES_DARK_WATER; i++) {
1017 *palette_pos++ = s[j];
1018 j++;
1019 if (j == EPV_CYCLES_DARK_WATER) j = 0;
1022 /* Glittery water */
1023 s = (_settings_game.game_creation.landscape == LT_TOYLAND) ? ev->glitter_water_toyland : ev->glitter_water;
1024 j = get_animation_cycle (tc, EPV_CYCLES_GLITTER_WATER, 6);
1025 for (i = 0; i != EPV_CYCLES_GLITTER_WATER / 3; i++) {
1026 *palette_pos++ = s[j];
1027 j += 3;
1028 if (j >= EPV_CYCLES_GLITTER_WATER) j -= EPV_CYCLES_GLITTER_WATER;
1031 if (!noanim && (memcmp (old_val, &_cur_palette.palette[PALETTE_ANIM_START], sizeof(old_val)) != 0)
1032 && (_cur_palette.count_dirty == 0)) {
1033 /* Did we changed anything on the palette? Seems so. Mark it as dirty */
1034 _cur_palette.first_dirty = PALETTE_ANIM_START;
1035 _cur_palette.count_dirty = PALETTE_ANIM_SIZE;
1039 void GfxInitPalettes()
1041 memcpy(&_cur_palette, &_palette, sizeof(_cur_palette));
1042 DoPaletteAnimations();
1046 * Determine a contrasty text colour for a coloured background.
1047 * @param background Background colour.
1048 * @return TC_BLACK or TC_WHITE depending on what gives a better contrast.
1050 TextColour GetContrastColour(uint8 background)
1052 Colour c = _cur_palette.palette[background];
1053 /* Compute brightness according to http://www.w3.org/TR/AERT#color-contrast.
1054 * The following formula computes 1000 * brightness^2, with brightness being in range 0 to 255. */
1055 uint sq1000_brightness = c.r * c.r * 299 + c.g * c.g * 587 + c.b * c.b * 114;
1056 /* Compare with threshold brightness 128 (50%) */
1057 return sq1000_brightness < 128 * 128 * 1000 ? TC_WHITE : TC_BLACK;
1061 * Initialize the font cache.
1062 * @param monospace Whether to load the monospace cache or the normal fonts.
1064 void LoadStringWidthTable(bool monospace)
1066 for (FontSize fs = monospace ? FS_MONO : FS_BEGIN; fs < (monospace ? FS_END : FS_MONO); fs++) {
1067 FontCache::Get(fs)->ClearFontCache();
1070 ReInitAllWindows();
1073 void ScreenSizeChanged()
1075 _dirty_bytes_per_line = CeilDiv (_screen_width, DIRTY_BLOCK_WIDTH);
1076 _dirty_blocks = xrealloct<byte> (_dirty_blocks, _dirty_bytes_per_line * CeilDiv (_screen_height, DIRTY_BLOCK_HEIGHT));
1078 /* check the dirty rect */
1079 if (_invalid_rect.right >= _screen_width) _invalid_rect.right = _screen_width;
1080 if (_invalid_rect.bottom >= _screen_height) _invalid_rect.bottom = _screen_height;
1082 /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
1083 _cursor.visible = false;
1086 void UndrawMouseCursor()
1088 /* Don't undraw the mouse cursor if the screen is not ready */
1089 if (!_screen_surface) return;
1091 if (_cursor.visible) {
1092 _cursor.visible = false;
1093 _screen_surface->paste (&_cursor_backup, _cursor.draw_pos.x, _cursor.draw_pos.y);
1094 VideoDriver::GetActiveDriver()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1098 void DrawMouseCursor()
1100 #if defined(WINCE)
1101 /* Don't ever draw the mouse for WinCE, as we work with a stylus */
1102 return;
1103 #endif
1105 /* Don't draw the mouse cursor if the screen is not ready */
1106 if (!_screen_surface) return;
1108 /* Redraw mouse cursor but only when it's inside the window */
1109 if (!_cursor.in_window) return;
1111 /* Don't draw the mouse cursor if it's already drawn */
1112 if (_cursor.visible) {
1113 if (!_cursor.dirty) return;
1114 UndrawMouseCursor();
1117 /* Determine visible area */
1118 int left = _cursor.pos.x + _cursor.total_offs.x;
1119 int width = _cursor.total_size.x;
1120 if (left < 0) {
1121 width += left;
1122 left = 0;
1124 if (left + width > _screen_width) {
1125 width = _screen_width - left;
1127 if (width <= 0) return;
1129 int top = _cursor.pos.y + _cursor.total_offs.y;
1130 int height = _cursor.total_size.y;
1131 if (top < 0) {
1132 height += top;
1133 top = 0;
1135 if (top + height > _screen_height) {
1136 height = _screen_height - top;
1138 if (height <= 0) return;
1140 _cursor.draw_pos.x = left;
1141 _cursor.draw_pos.y = top;
1142 _cursor.draw_size.x = width;
1143 _cursor.draw_size.y = height;
1145 /* Make backup of stuff below cursor */
1146 _screen_surface->copy (&_cursor_backup, _cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1148 /* Draw cursor on screen */
1149 BlitArea screen;
1150 screen.surface = _screen_surface.get();
1151 screen.dst_ptr = _screen_surface->ptr;
1152 screen.left = screen.top = 0;
1153 screen.width = _screen_width;
1154 screen.height = _screen_height;
1155 for (uint i = 0; i < _cursor.sprite_count; ++i) {
1156 DrawSprite (&screen, _cursor.sprite_seq[i].sprite, _cursor.sprite_seq[i].pal, _cursor.pos.x + _cursor.sprite_seq[i].pos, _cursor.pos.y);
1159 VideoDriver::GetActiveDriver()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1161 _cursor.visible = true;
1162 _cursor.dirty = false;
1165 void RedrawScreenRect(int left, int top, int right, int bottom)
1167 assert (right <= _screen_width && bottom <= _screen_height);
1168 if (_cursor.visible) {
1169 if (right > _cursor.draw_pos.x &&
1170 left < _cursor.draw_pos.x + _cursor.draw_size.x &&
1171 bottom > _cursor.draw_pos.y &&
1172 top < _cursor.draw_pos.y + _cursor.draw_size.y) {
1173 UndrawMouseCursor();
1177 #ifdef ENABLE_NETWORK
1178 if (_networking) NetworkUndrawChatMessage();
1179 #endif /* ENABLE_NETWORK */
1181 DrawOverlappedWindowForAll(left, top, right, bottom);
1183 VideoDriver::GetActiveDriver()->MakeDirty(left, top, right - left, bottom - top);
1187 * Repaints the rectangle blocks which are marked as 'dirty'.
1189 * @see SetDirtyBlocks
1191 void DrawDirtyBlocks()
1193 byte *b = _dirty_blocks;
1194 const int w = Align (_screen_width, DIRTY_BLOCK_WIDTH);
1195 const int h = Align (_screen_height, DIRTY_BLOCK_HEIGHT);
1196 int x;
1197 int y;
1199 if (HasModalProgress()) {
1200 /* We are generating the world, so release our rights to the map and
1201 * painting while we are waiting a bit. */
1202 _modal_progress_paint_mutex->EndCritical();
1203 _modal_progress_work_mutex->EndCritical();
1205 /* Wait a while and update _realtime_tick so we are given the rights */
1206 if (!IsFirstModalProgressLoop()) CSleep(MODAL_PROGRESS_REDRAW_TIMEOUT);
1207 _realtime_tick += MODAL_PROGRESS_REDRAW_TIMEOUT;
1208 _modal_progress_paint_mutex->BeginCritical();
1209 _modal_progress_work_mutex->BeginCritical();
1211 /* When we ended with the modal progress, do not draw the blocks.
1212 * Simply let the next run do so, otherwise we would be loading
1213 * the new state (and possibly change the blitter) when we hold
1214 * the drawing lock, which we must not do. */
1215 if (_switch_mode != SM_NONE && !HasModalProgress()) return;
1218 y = 0;
1219 do {
1220 x = 0;
1221 do {
1222 if (*b != 0) {
1223 int left;
1224 int top;
1225 int right = x + DIRTY_BLOCK_WIDTH;
1226 int bottom = y;
1227 byte *p = b;
1228 int h2;
1230 /* First try coalescing downwards */
1231 do {
1232 *p = 0;
1233 p += _dirty_bytes_per_line;
1234 bottom += DIRTY_BLOCK_HEIGHT;
1235 } while (bottom != h && *p != 0);
1237 /* Try coalescing to the right too. */
1238 h2 = (bottom - y) / DIRTY_BLOCK_HEIGHT;
1239 assert(h2 > 0);
1240 p = b;
1242 while (right != w) {
1243 byte *p2 = ++p;
1244 int h = h2;
1245 /* Check if a full line of dirty flags is set. */
1246 do {
1247 if (!*p2) goto no_more_coalesc;
1248 p2 += _dirty_bytes_per_line;
1249 } while (--h != 0);
1251 /* Wohoo, can combine it one step to the right!
1252 * Do that, and clear the bits. */
1253 right += DIRTY_BLOCK_WIDTH;
1255 h = h2;
1256 p2 = p;
1257 do {
1258 *p2 = 0;
1259 p2 += _dirty_bytes_per_line;
1260 } while (--h != 0);
1262 no_more_coalesc:
1264 left = x;
1265 top = y;
1267 if (left < _invalid_rect.left ) left = _invalid_rect.left;
1268 if (top < _invalid_rect.top ) top = _invalid_rect.top;
1269 if (right > _invalid_rect.right ) right = _invalid_rect.right;
1270 if (bottom > _invalid_rect.bottom) bottom = _invalid_rect.bottom;
1272 if (left < right && top < bottom) {
1273 RedrawScreenRect(left, top, right, bottom);
1277 } while (b++, (x += DIRTY_BLOCK_WIDTH) != w);
1278 } while (b += -(int)(w / DIRTY_BLOCK_WIDTH) + _dirty_bytes_per_line, (y += DIRTY_BLOCK_HEIGHT) != h);
1280 ++_dirty_block_colour;
1281 _invalid_rect.left = w;
1282 _invalid_rect.top = h;
1283 _invalid_rect.right = 0;
1284 _invalid_rect.bottom = 0;
1288 * This function extends the internal _invalid_rect rectangle as it
1289 * now contains the rectangle defined by the given parameters. Note
1290 * the point (0,0) is top left.
1292 * @param left The left edge of the rectangle
1293 * @param top The top edge of the rectangle
1294 * @param right The right edge of the rectangle
1295 * @param bottom The bottom edge of the rectangle
1296 * @see DrawDirtyBlocks
1298 * @todo The name of the function should be called like @c AddDirtyBlock as
1299 * it neither set a dirty rect nor add several dirty rects although
1300 * the function name is in plural. (Progman)
1302 void SetDirtyBlocks(int left, int top, int right, int bottom)
1304 byte *b;
1305 int width;
1306 int height;
1308 if (left < 0) left = 0;
1309 if (top < 0) top = 0;
1310 if (right > _screen_width) right = _screen_width;
1311 if (bottom > _screen_height) bottom = _screen_height;
1313 if (left >= right || top >= bottom) return;
1315 if (left < _invalid_rect.left ) _invalid_rect.left = left;
1316 if (top < _invalid_rect.top ) _invalid_rect.top = top;
1317 if (right > _invalid_rect.right ) _invalid_rect.right = right;
1318 if (bottom > _invalid_rect.bottom) _invalid_rect.bottom = bottom;
1320 left /= DIRTY_BLOCK_WIDTH;
1321 top /= DIRTY_BLOCK_HEIGHT;
1323 b = _dirty_blocks + top * _dirty_bytes_per_line + left;
1325 width = ((right - 1) / DIRTY_BLOCK_WIDTH) - left + 1;
1326 height = ((bottom - 1) / DIRTY_BLOCK_HEIGHT) - top + 1;
1328 assert(width > 0 && height > 0);
1330 do {
1331 int i = width;
1333 do b[--i] = 0xFF; while (i != 0);
1335 b += _dirty_bytes_per_line;
1336 } while (--height != 0);
1340 * This function mark the whole screen as dirty. This results in repainting
1341 * the whole screen. Use this with care as this function will break the
1342 * idea about marking only parts of the screen as 'dirty'.
1343 * @ingroup dirty
1345 void MarkWholeScreenDirty()
1347 SetDirtyBlocks (0, 0, _screen_width, _screen_height);
1351 * Set up a clipping area for only drawing into a certain area.
1352 * @param *o the parent BlitArea
1353 * @param *n the BlitArea that will be the clipping rectangle box allowed
1354 * for drawing
1355 * @param left,top,width,height the relative coordinates of the clipping
1356 * rectangle relative to the current area. This will most likely be the
1357 * offset from the calling window coordinates
1358 * @return return false if the requested rectangle is not possible with the
1359 * current dpi pointer. Only continue of the return value is true, or you'll
1360 * get some nasty results
1362 bool InitBlitArea (const BlitArea *o, BlitArea *n,
1363 int left, int top, int width, int height)
1365 assert(width > 0);
1366 assert(height > 0);
1368 if ((left -= o->left) < 0) {
1369 width += left;
1370 if (width <= 0) return false;
1371 n->left = -left;
1372 left = 0;
1373 } else {
1374 n->left = 0;
1377 if (width > o->width - left) {
1378 width = o->width - left;
1379 if (width <= 0) return false;
1381 n->width = width;
1383 if ((top -= o->top) < 0) {
1384 height += top;
1385 if (height <= 0) return false;
1386 n->top = -top;
1387 top = 0;
1388 } else {
1389 n->top = 0;
1392 n->dst_ptr = o->surface->move (o->dst_ptr, left, top);
1393 n->surface = o->surface;
1395 if (height > o->height - top) {
1396 height = o->height - top;
1397 if (height <= 0) return false;
1399 n->height = height;
1401 return true;
1405 * Update cursor dimension.
1406 * Called when changing cursor sprite resp. reloading grfs.
1408 void UpdateCursorSize()
1410 /* Ignore setting any cursor before the sprites are loaded. */
1411 if (GetMaxSpriteID() == 0) return;
1413 assert(_cursor.sprite_count <= lengthof(_cursor.sprite_seq));
1414 for (uint i = 0; i < _cursor.sprite_count; ++i) {
1415 const Sprite *p = GetSprite(GB(_cursor.sprite_seq[i].sprite, 0, SPRITE_WIDTH), ST_NORMAL);
1416 Point offs, size;
1417 offs.x = UnScaleGUI(p->x_offs) + _cursor.sprite_seq[i].pos;
1418 offs.y = UnScaleGUI(p->y_offs);
1419 size.x = UnScaleGUI(p->width);
1420 size.y = UnScaleGUI(p->height);
1422 if (i == 0) {
1423 _cursor.total_offs = offs;
1424 _cursor.total_size = size;
1425 } else {
1426 int right = max(_cursor.total_offs.x + _cursor.total_size.x, offs.x + size.x);
1427 int bottom = max(_cursor.total_offs.y + _cursor.total_size.y, offs.y + size.y);
1428 if (offs.x < _cursor.total_offs.x) _cursor.total_offs.x = offs.x;
1429 if (offs.y < _cursor.total_offs.y) _cursor.total_offs.y = offs.y;
1430 _cursor.total_size.x = right - _cursor.total_offs.x;
1431 _cursor.total_size.y = bottom - _cursor.total_offs.y;
1435 _cursor.dirty = true;
1439 * Switch cursor to different sprite.
1440 * @param cursor Sprite to draw for the cursor.
1441 * @param pal Palette to use for recolouring.
1443 static void SetCursorSprite(CursorID cursor, PaletteID pal)
1445 if (_cursor.sprite_count == 1 && _cursor.sprite_seq[0].sprite == cursor && _cursor.sprite_seq[0].pal == pal) return;
1447 _cursor.sprite_count = 1;
1448 _cursor.sprite_seq[0].sprite = cursor;
1449 _cursor.sprite_seq[0].pal = pal;
1450 _cursor.sprite_seq[0].pos = 0;
1452 UpdateCursorSize();
1455 static void SwitchAnimatedCursor()
1457 const AnimCursor *cur = _cursor_animate_cur;
1459 if (cur == NULL || cur->sprite == AnimCursor::LAST) cur = _cursor_animate_list;
1461 SetCursorSprite(cur->sprite, _cursor.sprite_seq[0].pal);
1463 _cursor_animate_timeout = cur->display_time;
1464 _cursor_animate_cur = cur + 1;
1467 void CursorTick()
1469 if (_cursor_animate_timeout != 0 && --_cursor_animate_timeout == 0) {
1470 SwitchAnimatedCursor();
1475 * Set or unset the ZZZ cursor.
1476 * @param busy Whether to show the ZZZ cursor.
1478 void SetMouseCursorBusy(bool busy)
1480 if (busy) {
1481 if (_cursor.sprite_seq[0].sprite == SPR_CURSOR_MOUSE) SetMouseCursor (SPR_CURSOR_ZZZ);
1482 } else {
1483 if (_cursor.sprite_seq[0].sprite == SPR_CURSOR_ZZZ) SetMouseCursor (SPR_CURSOR_MOUSE);
1488 * Assign a single non-animated sprite to the cursor.
1489 * @param sprite Sprite to draw for the cursor.
1490 * @see SetAnimatedMouseCursor
1492 void SetMouseCursor (CursorID sprite)
1494 /* Turn off animation */
1495 _cursor_animate_timeout = 0;
1496 /* Set cursor */
1497 SetCursorSprite (sprite, PAL_NONE);
1501 * Assign an animation to the cursor.
1502 * @param table Array of animation states.
1503 * @see SetMouseCursor
1505 void SetAnimatedMouseCursor(const AnimCursor *table)
1507 _cursor_animate_list = table;
1508 _cursor_animate_cur = NULL;
1509 _cursor.sprite_seq[0].pal = PAL_NONE;
1510 SwitchAnimatedCursor();
1514 * Update cursor position on mouse movement.
1515 * @param x New X position.
1516 * @param y New Y position.
1517 * @param queued True, if the OS queues mouse warps after pending mouse movement events.
1518 * False, if the warp applies instantaneous.
1519 * @return true, if the OS cursor position should be warped back to this->pos.
1521 bool CursorVars::UpdateCursorPosition(int x, int y, bool queued_warp)
1523 /* Detecting relative mouse movement is somewhat tricky.
1524 * - There may be multiple mouse move events in the video driver queue (esp. when OpenTTD lags a bit).
1525 * - When we request warping the mouse position (return true), a mouse move event is appended at the end of the queue.
1527 * So, when this->fix_at is active, we use the following strategy:
1528 * - The first movement triggers the warp to reset the mouse position.
1529 * - Subsequent events have to compute movement relative to the previous event.
1530 * - The relative movement is finished, when we receive the event matching the warp.
1533 if (x == this->pos.x && y == this->pos.y) {
1534 /* Warp finished. */
1535 this->queued_warp = false;
1537 this->delta.x = 0;
1538 this->delta.y = 0;
1540 this->last_position.x = x;
1541 this->last_position.y = y;
1543 return false;
1546 this->delta.x = x - (this->queued_warp ? this->last_position.x : this->pos.x);
1547 this->delta.y = y - (this->queued_warp ? this->last_position.y : this->pos.y);
1549 this->last_position.x = x;
1550 this->last_position.y = y;
1552 bool need_warp = false;
1553 if (!this->fix_at) {
1554 this->queued_warp = false; // Cancel warping, we are no longer confining the position.
1555 this->dirty = true;
1556 this->pos.x = x;
1557 this->pos.y = y;
1558 } else if (this->delta.x != 0 || this->delta.y != 0) {
1559 /* Trigger warp.
1560 * Note: We also trigger warping again, if there is already a pending warp.
1561 * This makes it more tolerant about the OS or other software inbetween
1562 * botchering the warp. */
1563 this->queued_warp = queued_warp;
1564 need_warp = true;
1566 return need_warp;
1569 bool ChangeResInGame(int width, int height)
1571 return (_screen_width == width && _screen_height == height) || VideoDriver::GetActiveDriver()->ChangeResolution(width, height);
1574 bool ToggleFullScreen(bool fs)
1576 bool result = VideoDriver::GetActiveDriver()->ToggleFullscreen(fs);
1577 if (_fullscreen != fs && _num_resolutions == 0) {
1578 DEBUG(driver, 0, "Could not find a suitable fullscreen resolution");
1580 return result;
1583 static int CDECL compare_res(const Dimension *pa, const Dimension *pb)
1585 int x = pa->width - pb->width;
1586 if (x != 0) return x;
1587 return pa->height - pb->height;
1590 void SortResolutions(int count)
1592 QSortT(_resolutions, count, &compare_res);