OpenTTD Source: src/gfx.cpp Source File

OpenTTD Source 15.0-RC2

gfx.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
10#include "stdafx.h"
11#include "gfx_func.h"
12#include "gfx_layout.h"
13#include "progress.h"
14#include "zoom_func.h"
15#include "blitter/factory.hpp"
16#include "video/video_driver.hpp"
17#include "strings_func.h"
18#include "settings_type.h"
19#include "network/network.h"
20#include "network/network_func.h"
21#include "window_gui.h"
22#include "window_func.h"
23#include "newgrf_debug.h"
24#include "core/backup_type.hpp"
25#include "core/geometry_func.hpp"
26#include "viewport_func.h"
27
28#include "table/string_colours.h"
29#include "table/sprites.h"
30#include "table/control_codes.h"
31
32#include "safeguards.h"
33
34uint8_t _dirkeys;
35bool _fullscreen;
36uint8_t _support8bpp;
37 CursorVars _cursor;
38 bool _ctrl_pressed;
39 bool _shift_pressed;
40uint16_t _game_speed = 100;
41 bool _left_button_down;
42 bool _left_button_clicked;
43 bool _right_button_down;
44 bool _right_button_clicked;
45 DrawPixelInfo _screen;
46 bool _screen_disable_anim = false;
47std::atomic<bool> _exit_game;
48 GameMode _game_mode;
49 SwitchMode _switch_mode;
50 PauseModes _pause_mode;
51 GameSessionStats _game_session_stats;
52
53 static uint8_t _stringwidth_table[FS_END][224];
54 DrawPixelInfo *_cur_dpi;
55
56static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = nullptr, SpriteID sprite_id = SPR_CURSOR_MOUSE);
57static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub = nullptr, SpriteID sprite_id = SPR_CURSOR_MOUSE, ZoomLevel zoom = ZoomLevel::Min);
58
59static ReusableBuffer<uint8_t> _cursor_backup;
60
61 ZoomLevel _gui_zoom = ZoomLevel::Normal;
62 ZoomLevel _font_zoom = _gui_zoom;
63 int _gui_scale = MIN_INTERFACE_SCALE;
64 int _gui_scale_cfg;
65
73 static Rect _invalid_rect;
74static const uint8_t *_colour_remap_ptr;
75 static uint8_t _string_colourremap[3];
76
77static const uint DIRTY_BLOCK_HEIGHT = 8;
78static const uint DIRTY_BLOCK_WIDTH = 64;
79
80static size_t _dirty_blocks_per_row = 0;
81static size_t _dirty_blocks_per_column = 0;
82static std::vector<uint8_t> _dirty_blocks;
83extern uint _dirty_block_colour;
84
85void GfxScroll(int left, int top, int width, int height, int xo, int yo)
86{
87 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
88
89 if (xo == 0 && yo == 0) return;
90
91 if (_cursor.visible) UndrawMouseCursor();
92
93 if (_networking) NetworkUndrawChatMessage();
94
95 blitter->ScrollBuffer(_screen.dst_ptr, left, top, width, height, xo, yo);
96 /* This part of the screen is now dirty. */
97 VideoDriver::GetInstance()->MakeDirty(left, top, width, height);
98}
99
100
115 void GfxFillRect(int left, int top, int right, int bottom, const std::variant<PixelColour, PaletteID> &colour, FillRectMode mode)
116{
117 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
118 const DrawPixelInfo *dpi = _cur_dpi;
119 void *dst;
120 const int otop = top;
121 const int oleft = left;
122
123 if (dpi->zoom != ZoomLevel::Min) return;
124 if (left > right || top > bottom) return;
125 if (right < dpi->left || left >= dpi->left + dpi->width) return;
126 if (bottom < dpi->top || top >= dpi->top + dpi->height) return;
127
128 if ( (left -= dpi->left) < 0) left = 0;
129 right = right - dpi->left + 1;
130 if (right > dpi->width) right = dpi->width;
131 right -= left;
132 assert(right > 0);
133
134 if ( (top -= dpi->top) < 0) top = 0;
135 bottom = bottom - dpi->top + 1;
136 if (bottom > dpi->height) bottom = dpi->height;
137 bottom -= top;
138 assert(bottom > 0);
139
140 dst = blitter->MoveTo(dpi->dst_ptr, left, top);
141
142 switch (mode) {
143 default: // FILLRECT_OPAQUE
144 blitter->DrawRect(dst, right, bottom, std::get<PixelColour>(colour));
145 break;
146
147 case FILLRECT_RECOLOUR:
148 blitter->DrawColourMappingRect(dst, right, bottom, GB(std::get<PaletteID>(colour), 0, PALETTE_WIDTH));
149 break;
150
151 case FILLRECT_CHECKER: {
152 uint8_t bo = (oleft - left + dpi->left + otop - top + dpi->top) & 1;
153 PixelColour pc = std::get<PixelColour>(colour);
154 do {
155 for (int i = (bo ^= 1); i < right; i += 2) blitter->SetPixel(dst, i, 0, pc);
156 dst = blitter->MoveTo(dst, 0, 1);
157 } while (--bottom > 0);
158 break;
159 }
160 }
161}
162
163typedef std::pair<Point, Point> LineSegment;
164
173 static std::vector<LineSegment> MakePolygonSegments(std::span<const Point> shape, Point offset)
174{
175 std::vector<LineSegment> segments;
176 if (shape.size() < 3) return segments; // fewer than 3 will always result in an empty polygon
177 segments.reserve(shape.size());
178
179 /* Connect first and last point by having initial previous point be the last */
180 Point prev = shape.back();
181 prev.x -= offset.x;
182 prev.y -= offset.y;
183 for (Point pt : shape) {
184 pt.x -= offset.x;
185 pt.y -= offset.y;
186 /* Create segments for all non-horizontal lines in the polygon.
187 * The segments always have lowest Y coordinate first. */
188 if (prev.y > pt.y) {
189 segments.emplace_back(pt, prev);
190 } else if (prev.y < pt.y) {
191 segments.emplace_back(prev, pt);
192 }
193 prev = pt;
194 }
195
196 return segments;
197}
198
212 void GfxFillPolygon(std::span<const Point> shape, const std::variant<PixelColour, PaletteID> &colour, FillRectMode mode)
213{
214 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
215 const DrawPixelInfo *dpi = _cur_dpi;
216 if (dpi->zoom != ZoomLevel::Min) return;
217
218 std::vector<LineSegment> segments = MakePolygonSegments(shape, Point{ dpi->left, dpi->top });
219
220 /* Remove segments appearing entirely above or below the clipping area. */
221 segments.erase(std::remove_if(segments.begin(), segments.end(), [dpi](const LineSegment &s) { return s.second.y <= 0 || s.first.y >= dpi->height; }), segments.end());
222
223 /* Check that this wasn't an empty shape (all points on a horizontal line or outside clipping.) */
224 if (segments.empty()) return;
225
226 /* Sort the segments by first point Y coordinate. */
227 std::sort(segments.begin(), segments.end(), [](const LineSegment &a, const LineSegment &b) { return a.first.y < b.first.y; });
228
229 /* Segments intersecting current scanline. */
230 std::vector<LineSegment> active;
231 /* Intersection points with a scanline.
232 * Kept outside loop to avoid repeated re-allocations. */
233 std::vector<int> intersections;
234 /* Normal, reasonable polygons don't have many intersections per scanline. */
235 active.reserve(4);
236 intersections.reserve(4);
237
238 /* Scan through the segments and paint each scanline. */
239 int y = segments.front().first.y;
240 std::vector<LineSegment>::iterator nextseg = segments.begin();
241 while (!active.empty() || nextseg != segments.end()) {
242 /* Clean up segments that have ended. */
243 active.erase(std::remove_if(active.begin(), active.end(), [y](const LineSegment &s) { return s.second.y == y; }), active.end());
244
245 /* Activate all segments starting on this scanline. */
246 while (nextseg != segments.end() && nextseg->first.y == y) {
247 active.push_back(*nextseg);
248 ++nextseg;
249 }
250
251 /* Check clipping. */
252 if (y < 0) {
253 ++y;
254 continue;
255 }
256 if (y >= dpi->height) return;
257
258 /* Intersect scanline with all active segments. */
259 intersections.clear();
260 for (const LineSegment &s : active) {
261 const int sdx = s.second.x - s.first.x;
262 const int sdy = s.second.y - s.first.y;
263 const int ldy = y - s.first.y;
264 const int x = s.first.x + sdx * ldy / sdy;
265 intersections.push_back(x);
266 }
267
268 /* Fill between pairs of intersections. */
269 std::sort(intersections.begin(), intersections.end());
270 for (size_t i = 1; i < intersections.size(); i += 2) {
271 /* Check clipping. */
272 const int x1 = std::max(0, intersections[i - 1]);
273 const int x2 = std::min(intersections[i], dpi->width);
274 if (x2 < 0) continue;
275 if (x1 >= dpi->width) continue;
276
277 /* Fill line y from x1 to x2. */
278 void *dst = blitter->MoveTo(dpi->dst_ptr, x1, y);
279 switch (mode) {
280 default: // FILLRECT_OPAQUE
281 blitter->DrawRect(dst, x2 - x1, 1, std::get<PixelColour>(colour));
282 break;
283 case FILLRECT_RECOLOUR:
284 blitter->DrawColourMappingRect(dst, x2 - x1, 1, GB(std::get<PaletteID>(colour), 0, PALETTE_WIDTH));
285 break;
286 case FILLRECT_CHECKER: {
287 /* Fill every other pixel, offset such that the sum of filled pixels' X and Y coordinates is odd.
288 * This creates a checkerboard effect. */
289 PixelColour pc = std::get<PixelColour>(colour);
290 for (int x = (x1 + y) & 1; x < x2 - x1; x += 2) {
291 blitter->SetPixel(dst, x, 0, pc);
292 }
293 break;
294 }
295 }
296 }
297
298 /* Next line */
299 ++y;
300 }
301}
302
317 static inline void GfxDoDrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, PixelColour colour, int width, int dash = 0)
318{
319 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
320
321 assert(width > 0);
322
323 if (y2 == y || x2 == x) {
324 /* Special case: horizontal/vertical line. All checks already done in GfxPreprocessLine. */
325 blitter->DrawLine(video, x, y, x2, y2, screen_width, screen_height, colour, width, dash);
326 return;
327 }
328
329 int grade_y = y2 - y;
330 int grade_x = x2 - x;
331
332 /* Clipping rectangle. Slightly extended so we can ignore the width of the line. */
333 int extra = (int)CeilDiv(3 * width, 4); // not less then "width * sqrt(2) / 2"
334 Rect clip = { -extra, -extra, screen_width - 1 + extra, screen_height - 1 + extra };
335
336 /* prevent integer overflows. */
337 int margin = 1;
338 while (INT_MAX / abs(grade_y) < std::max(abs(clip.left - x), abs(clip.right - x))) {
339 grade_y /= 2;
340 grade_x /= 2;
341 margin *= 2; // account for rounding errors
342 }
343
344 /* Imagine that the line is infinitely long and it intersects with
345 * infinitely long left and right edges of the clipping rectangle.
346 * If both intersection points are outside the clipping rectangle
347 * and both on the same side of it, we don't need to draw anything. */
348 int left_isec_y = y + (clip.left - x) * grade_y / grade_x;
349 int right_isec_y = y + (clip.right - x) * grade_y / grade_x;
350 if ((left_isec_y > clip.bottom + margin && right_isec_y > clip.bottom + margin) ||
351 (left_isec_y < clip.top - margin && right_isec_y < clip.top - margin)) {
352 return;
353 }
354
355 /* It is possible to use the line equation to further reduce the amount of
356 * work the blitter has to do by shortening the effective line segment.
357 * However, in order to get that right and prevent the flickering effects
358 * of rounding errors so much additional code has to be run here that in
359 * the general case the effect is not noticeable. */
360
361 blitter->DrawLine(video, x, y, x2, y2, screen_width, screen_height, colour, width, dash);
362}
363
375 static inline bool GfxPreprocessLine(DrawPixelInfo *dpi, int &x, int &y, int &x2, int &y2, int width)
376{
377 x -= dpi->left;
378 x2 -= dpi->left;
379 y -= dpi->top;
380 y2 -= dpi->top;
381
382 /* Check simple clipping */
383 if (x + width / 2 < 0 && x2 + width / 2 < 0 ) return false;
384 if (y + width / 2 < 0 && y2 + width / 2 < 0 ) return false;
385 if (x - width / 2 > dpi->width && x2 - width / 2 > dpi->width ) return false;
386 if (y - width / 2 > dpi->height && y2 - width / 2 > dpi->height) return false;
387 return true;
388}
389
390void GfxDrawLine(int x, int y, int x2, int y2, PixelColour colour, int width, int dash)
391{
392 DrawPixelInfo *dpi = _cur_dpi;
393 if (GfxPreprocessLine(dpi, x, y, x2, y2, width)) {
394 GfxDoDrawLine(dpi->dst_ptr, x, y, x2, y2, dpi->width, dpi->height, colour, width, dash);
395 }
396}
397
398void GfxDrawLineUnscaled(int x, int y, int x2, int y2, PixelColour colour)
399{
400 DrawPixelInfo *dpi = _cur_dpi;
401 if (GfxPreprocessLine(dpi, x, y, x2, y2, 1)) {
402 GfxDoDrawLine(dpi->dst_ptr,
403 UnScaleByZoom(x, dpi->zoom), UnScaleByZoom(y, dpi->zoom),
404 UnScaleByZoom(x2, dpi->zoom), UnScaleByZoom(y2, dpi->zoom),
405 UnScaleByZoom(dpi->width, dpi->zoom), UnScaleByZoom(dpi->height, dpi->zoom), colour, 1);
406 }
407}
408
422 void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
423{
424 /* ....
425 * .. ....
426 * .. ....
427 * .. ^
428 * <--__(dx1,dy1) /(dx2,dy2)
429 * : --__ / :
430 * : --__ / :
431 * : *(x,y) :
432 * : | :
433 * : | ..
434 * .... |(dx3,dy3)
435 * .... | ..
436 * ....V.
437 */
438
439 static constexpr PixelColour colour = PC_WHITE;
440
441 GfxDrawLineUnscaled(x, y, x + dx1, y + dy1, colour);
442 GfxDrawLineUnscaled(x, y, x + dx2, y + dy2, colour);
443 GfxDrawLineUnscaled(x, y, x + dx3, y + dy3, colour);
444
445 GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx2, y + dy1 + dy2, colour);
446 GfxDrawLineUnscaled(x + dx1, y + dy1, x + dx1 + dx3, y + dy1 + dy3, colour);
447 GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx1, y + dy2 + dy1, colour);
448 GfxDrawLineUnscaled(x + dx2, y + dy2, x + dx2 + dx3, y + dy2 + dy3, colour);
449 GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx1, y + dy3 + dy1, colour);
450 GfxDrawLineUnscaled(x + dx3, y + dy3, x + dx3 + dx2, y + dy3 + dy2, colour);
451}
452
460 void DrawRectOutline(const Rect &r, PixelColour colour, int width, int dash)
461{
462 GfxDrawLine(r.left, r.top, r.right, r.top, colour, width, dash);
463 GfxDrawLine(r.left, r.top, r.left, r.bottom, colour, width, dash);
464 GfxDrawLine(r.right, r.top, r.right, r.bottom, colour, width, dash);
465 GfxDrawLine(r.left, r.bottom, r.right, r.bottom, colour, width, dash);
466}
467
472 static void SetColourRemap(TextColour colour)
473{
474 if (colour == TC_INVALID) return;
475
476 /* Black strings have no shading ever; the shading is black, so it
477 * would be invisible at best, but it actually makes it illegible. */
478 bool no_shade = (colour & TC_NO_SHADE) != 0 || colour == TC_BLACK;
479 bool raw_colour = (colour & TC_IS_PALETTE_COLOUR) != 0;
480 colour &= ~(TC_NO_SHADE | TC_IS_PALETTE_COLOUR | TC_FORCED);
481
482 _string_colourremap[1] = raw_colour ? (uint8_t)colour : _string_colourmap[colour].p;
483 _string_colourremap[2] = no_shade ? 0 : 1;
484 _colour_remap_ptr = _string_colourremap;
485}
486
503 static int DrawLayoutLine(const ParagraphLayouter::Line &line, int y, int left, int right, StringAlignment align, bool underline, bool truncation, TextColour default_colour)
504{
505 if (line.CountRuns() == 0) return 0;
506
507 int w = line.GetWidth();
508 int h = line.GetLeading();
509
510 /*
511 * The following is needed for truncation.
512 * Depending on the text direction, we either remove bits at the rear
513 * or the front. For this we shift the entire area to draw so it fits
514 * within the left/right bounds and the side we do not truncate it on.
515 * Then we determine the truncation location, i.e. glyphs that fall
516 * outside of the range min_x - max_x will not be drawn; they are thus
517 * the truncated glyphs.
518 *
519 * At a later step we insert the dots.
520 */
521
522 int max_w = right - left + 1; // The maximum width.
523
524 int offset_x = 0; // The offset we need for positioning the glyphs
525 int min_x = left; // The minimum x position to draw normal glyphs on.
526 int max_x = right; // The maximum x position to draw normal glyphs on.
527
528 truncation &= max_w < w; // Whether we need to do truncation.
529 int truncation_width = 0; // Width of the ellipsis string.
530
531 std::optional<Layouter> truncation_layout;
532 if (truncation) {
533 /*
534 * Assumption may be made that all fonts of a run are of the same size.
535 * In any case, we'll use these dots for the abbreviation, so even if
536 * another size would be chosen it won't have truncated too little for
537 * the truncation dots.
538 */
539 truncation_layout.emplace(GetEllipsis(), INT32_MAX, line.GetVisualRun(0).GetFont()->fc->GetSize());
540 truncation_width = truncation_layout->GetBounds().width;
541
542 /* Is there enough space even for an ellipsis? */
543 if (max_w < truncation_width) return (_current_text_dir == TD_RTL) ? left : right;
544
545 if (_current_text_dir == TD_RTL) {
546 min_x += truncation_width;
547 offset_x = w - max_w;
548 } else {
549 max_x -= truncation_width;
550 }
551
552 w = max_w;
553 }
554
555 /* In case we have a RTL language we swap the alignment. */
556 if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
557
558 /* right is the right most position to draw on. In this case we want to do
559 * calculations with the width of the string. In comparison right can be
560 * seen as lastof(todraw) and width as lengthof(todraw). They differ by 1.
561 * So most +1/-1 additions are to move from lengthof to 'indices'.
562 */
563 switch (align & SA_HOR_MASK) {
564 case SA_LEFT:
565 /* right + 1 = left + w */
566 right = left + w - 1;
567 break;
568
569 case SA_HOR_CENTER:
570 left = RoundDivSU(right + 1 + left - w, 2);
571 /* right + 1 = left + w */
572 right = left + w - 1;
573 break;
574
575 case SA_RIGHT:
576 left = right + 1 - w;
577 break;
578
579 default:
580 NOT_REACHED();
581 }
582
583 const uint shadow_offset = ScaleGUITrad(1);
584
585 auto draw_line = [&](const ParagraphLayouter::Line &line, bool do_shadow, int left, int min_x, int max_x, bool truncation, TextColour initial_colour) {
586 const DrawPixelInfo *dpi = _cur_dpi;
587 int dpi_left = dpi->left;
588 int dpi_right = dpi->left + dpi->width - 1;
589 TextColour last_colour = initial_colour;
590
591 for (int run_index = 0; run_index < line.CountRuns(); run_index++) {
592 const ParagraphLayouter::VisualRun &run = line.GetVisualRun(run_index);
593 const auto &glyphs = run.GetGlyphs();
594 const auto &positions = run.GetPositions();
595 const Font *f = run.GetFont();
596
597 FontCache *fc = f->fc;
598 TextColour colour = f->colour;
599 if (colour == TC_INVALID || HasFlag(initial_colour, TC_FORCED)) colour = initial_colour;
600 bool colour_has_shadow = (colour & TC_NO_SHADE) == 0 && colour != TC_BLACK;
601 /* Update the last colour for the truncation ellipsis. */
602 last_colour = colour;
603 if (do_shadow && (!fc->GetDrawGlyphShadow() || !colour_has_shadow)) continue;
604 SetColourRemap(do_shadow ? TC_BLACK : colour);
605
606 for (int i = 0; i < run.GetGlyphCount(); i++) {
607 GlyphID glyph = glyphs[i];
608
609 /* Not a valid glyph (empty) */
610 if (glyph == 0xFFFF) continue;
611
612 int begin_x = positions[i].left + left;
613 int end_x = positions[i].right + left;
614 int top = positions[i].top + y;
615
616 /* Truncated away. */
617 if (truncation && (begin_x < min_x || end_x > max_x)) continue;
618
619 const Sprite *sprite = fc->GetGlyph(glyph);
620 /* Check clipping (the "+ 1" is for the shadow). */
621 if (begin_x + sprite->x_offs > dpi_right || begin_x + sprite->x_offs + sprite->width /* - 1 + 1 */ < dpi_left) continue;
622
623 if (do_shadow && (glyph & SPRITE_GLYPH) != 0) continue;
624
625 GfxMainBlitter(sprite, begin_x + (do_shadow ? shadow_offset : 0), top + (do_shadow ? shadow_offset : 0), BlitterMode::ColourRemap);
626 }
627 }
628 return last_colour;
629 };
630
631 /* Draw shadow, then foreground */
632 for (bool do_shadow : {true, false}) {
633 TextColour colour = draw_line(line, do_shadow, left - offset_x, min_x, max_x, truncation, default_colour);
634
635 if (truncation) {
636 int x = (_current_text_dir == TD_RTL) ? left : (right - truncation_width);
637 draw_line(*truncation_layout->front(), do_shadow, x, INT32_MIN, INT32_MAX, false, colour);
638 }
639 }
640
641 if (underline) {
642 GfxFillRect(left, y + h, right, y + h + WidgetDimensions::scaled.bevel.top - 1, PixelColour{_string_colourremap[1]});
643 }
644
645 return (align & SA_HOR_MASK) == SA_RIGHT ? left : right;
646}
647
665 int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
666{
667 /* The string may contain control chars to change the font, just use the biggest font for clipping. */
668 int max_height = std::max({GetCharacterHeight(FS_SMALL), GetCharacterHeight(FS_NORMAL), GetCharacterHeight(FS_LARGE), GetCharacterHeight(FS_MONO)});
669
670 /* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
671 int extra = max_height / 2;
672
673 if (_cur_dpi->top + _cur_dpi->height + extra < top || _cur_dpi->top > top + max_height + extra ||
674 _cur_dpi->left + _cur_dpi->width + extra < left || _cur_dpi->left > right + extra) {
675 return 0;
676 }
677
678 Layouter layout(str, INT32_MAX, fontsize);
679 if (layout.empty()) return 0;
680
681 return DrawLayoutLine(*layout.front(), top, left, right, align, underline, true, colour);
682}
683
701 int DrawString(int left, int right, int top, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
702{
703 return DrawString(left, right, top, GetString(str), colour, align, underline, fontsize);
704}
705
712 int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
713{
714 assert(maxw > 0);
715 Layouter layout(str, maxw, fontsize);
716 return layout.GetBounds().height;
717}
718
725 int GetStringHeight(StringID str, int maxw)
726{
727 return GetStringHeight(GetString(str), maxw);
728}
729
736 int GetStringLineCount(std::string_view str, int maxw)
737{
738 Layouter layout(str, maxw);
739 return (uint)layout.size();
740}
741
748 Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
749{
750 Dimension box = {suggestion.width, (uint)GetStringHeight(str, suggestion.width)};
751 return box;
752}
753
760 Dimension GetStringMultiLineBoundingBox(std::string_view str, const Dimension &suggestion, FontSize fontsize)
761{
762 Dimension box = {suggestion.width, (uint)GetStringHeight(str, suggestion.width, fontsize)};
763 return box;
764}
765
782 int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
783{
784 int maxw = right - left + 1;
785 int maxh = bottom - top + 1;
786
787 /* It makes no sense to even try if it can't be drawn anyway, or
788 * do we really want to support fonts of 0 or less pixels high? */
789 if (maxh <= 0) return top;
790
791 Layouter layout(str, maxw, fontsize);
792 int total_height = layout.GetBounds().height;
793 int y;
794 switch (align & SA_VERT_MASK) {
795 case SA_TOP:
796 y = top;
797 break;
798
799 case SA_VERT_CENTER:
800 y = RoundDivSU(bottom + top - total_height, 2);
801 break;
802
803 case SA_BOTTOM:
804 y = bottom - total_height;
805 break;
806
807 default: NOT_REACHED();
808 }
809
810 int last_line = top;
811 int first_line = bottom;
812
813 for (const auto &line : layout) {
814
815 int line_height = line->GetLeading();
816 if (y >= top && y + line_height - 1 <= bottom) {
817 last_line = y + line_height;
818 if (first_line > y) first_line = y;
819
820 DrawLayoutLine(*line, y, left, right, align, underline, false, colour);
821 }
822 y += line_height;
823 }
824
825 return ((align & SA_VERT_MASK) == SA_BOTTOM) ? first_line : last_line;
826}
827
844 int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
845{
846 return DrawStringMultiLine(left, right, top, bottom, GetString(str), colour, align, underline, fontsize);
847}
848
867 bool DrawStringMultiLineWithClipping(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
868{
869 /* The string may contain control chars to change the font, just use the biggest font for clipping. */
870 int max_height = std::max({GetCharacterHeight(FS_SMALL), GetCharacterHeight(FS_NORMAL), GetCharacterHeight(FS_LARGE), GetCharacterHeight(FS_MONO)});
871
872 /* Funny glyphs may extent outside the usual bounds, so relax the clipping somewhat. */
873 int extra = max_height / 2;
874
875 if (_cur_dpi->top + _cur_dpi->height + extra < top || _cur_dpi->top > bottom + extra ||
876 _cur_dpi->left + _cur_dpi->width + extra < left || _cur_dpi->left > right + extra) {
877 return false;
878 }
879
880 DrawStringMultiLine(left, right, top, bottom, str, colour, align, underline, fontsize);
881 return true;
882}
883
894 Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
895{
896 Layouter layout(str, INT32_MAX, start_fontsize);
897 return layout.GetBounds();
898}
899
906 Dimension GetStringBoundingBox(StringID strid, FontSize start_fontsize)
907{
908 return GetStringBoundingBox(GetString(strid), start_fontsize);
909}
910
917uint GetStringListWidth(std::span<const StringID> list, FontSize fontsize)
918{
919 uint width = 0;
920 for (auto str : list) {
921 width = std::max(width, GetStringBoundingBox(str, fontsize).width);
922 }
923 return width;
924}
925
932 Dimension GetStringListBoundingBox(std::span<const StringID> list, FontSize fontsize)
933{
934 Dimension d{0, 0};
935 for (auto str : list) {
936 d = maxdim(d, GetStringBoundingBox(str, fontsize));
937 }
938 return d;
939}
940
948 void DrawCharCentered(char32_t c, const Rect &r, TextColour colour)
949{
950 SetColourRemap(colour);
951 GfxMainBlitter(GetGlyph(FS_NORMAL, c),
952 CentreBounds(r.left, r.right, GetCharacterWidth(FS_NORMAL, c)),
953 CentreBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)),
954 BlitterMode::ColourRemap);
955}
956
965 Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
966{
967 const Sprite *sprite = GetSprite(sprid, SpriteType::Normal);
968
969 if (offset != nullptr) {
970 offset->x = UnScaleByZoom(sprite->x_offs, zoom);
971 offset->y = UnScaleByZoom(sprite->y_offs, zoom);
972 }
973
974 Dimension d;
975 d.width = std::max<int>(0, UnScaleByZoom(sprite->x_offs + sprite->width, zoom));
976 d.height = std::max<int>(0, UnScaleByZoom(sprite->y_offs + sprite->height, zoom));
977 return d;
978}
979
985 static BlitterMode GetBlitterMode(PaletteID pal)
986{
987 switch (pal) {
988 case PAL_NONE: return BlitterMode::Normal;
989 case PALETTE_CRASH: return BlitterMode::CrashRemap;
990 case PALETTE_ALL_BLACK: return BlitterMode::BlackRemap;
991 default: return BlitterMode::ColourRemap;
992 }
993}
994
1003 void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
1004{
1005 SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
1006 if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
1007 pal = GB(pal, 0, PALETTE_WIDTH);
1008 _colour_remap_ptr = GetNonSprite(pal, SpriteType::Recolour) + 1;
1009 GfxMainBlitterViewport(GetSprite(real_sprite, SpriteType::Normal), x, y, pal == PALETTE_TO_TRANSPARENT ? BlitterMode::Transparent : BlitterMode::TransparentRemap, sub, real_sprite);
1010 } else if (pal != PAL_NONE) {
1011 if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) {
1012 SetColourRemap((TextColour)GB(pal, 0, PALETTE_WIDTH));
1013 } else {
1014 _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1;
1015 }
1016 GfxMainBlitterViewport(GetSprite(real_sprite, SpriteType::Normal), x, y, GetBlitterMode(pal), sub, real_sprite);
1017 } else {
1018 GfxMainBlitterViewport(GetSprite(real_sprite, SpriteType::Normal), x, y, BlitterMode::Normal, sub, real_sprite);
1019 }
1020}
1021
1031 void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
1032{
1033 SpriteID real_sprite = GB(img, 0, SPRITE_WIDTH);
1034 if (HasBit(img, PALETTE_MODIFIER_TRANSPARENT)) {
1035 pal = GB(pal, 0, PALETTE_WIDTH);
1036 _colour_remap_ptr = GetNonSprite(pal, SpriteType::Recolour) + 1;
1037 GfxMainBlitter(GetSprite(real_sprite, SpriteType::Normal), x, y, pal == PALETTE_TO_TRANSPARENT ? BlitterMode::Transparent : BlitterMode::TransparentRemap, sub, real_sprite, zoom);
1038 } else if (pal != PAL_NONE) {
1039 if (HasBit(pal, PALETTE_TEXT_RECOLOUR)) {
1040 SetColourRemap((TextColour)GB(pal, 0, PALETTE_WIDTH));
1041 } else {
1042 _colour_remap_ptr = GetNonSprite(GB(pal, 0, PALETTE_WIDTH), SpriteType::Recolour) + 1;
1043 }
1044 GfxMainBlitter(GetSprite(real_sprite, SpriteType::Normal), x, y, GetBlitterMode(pal), sub, real_sprite, zoom);
1045 } else {
1046 GfxMainBlitter(GetSprite(real_sprite, SpriteType::Normal), x, y, BlitterMode::Normal, sub, real_sprite, zoom);
1047 }
1048}
1049
1062template <int ZOOM_BASE, bool SCALED_XY>
1063 static void GfxBlitter(const Sprite * const sprite, int x, int y, BlitterMode mode, const SubSprite * const sub, SpriteID sprite_id, ZoomLevel zoom, const DrawPixelInfo *dst = nullptr)
1064{
1065 const DrawPixelInfo *dpi = (dst != nullptr) ? dst : _cur_dpi;
1066 Blitter::BlitterParams bp;
1067
1068 if (SCALED_XY) {
1069 /* Scale it */
1070 x = ScaleByZoom(x, zoom);
1071 y = ScaleByZoom(y, zoom);
1072 }
1073
1074 /* Move to the correct offset */
1075 x += sprite->x_offs;
1076 y += sprite->y_offs;
1077
1078 if (sub == nullptr) {
1079 /* No clipping. */
1080 bp.skip_left = 0;
1081 bp.skip_top = 0;
1082 bp.width = UnScaleByZoom(sprite->width, zoom);
1083 bp.height = UnScaleByZoom(sprite->height, zoom);
1084 } else {
1085 /* Amount of pixels to clip from the source sprite */
1086 int clip_left = std::max(0, -sprite->x_offs + sub->left * ZOOM_BASE );
1087 int clip_top = std::max(0, -sprite->y_offs + sub->top * ZOOM_BASE );
1088 int clip_right = std::max(0, sprite->width - (-sprite->x_offs + (sub->right + 1) * ZOOM_BASE));
1089 int clip_bottom = std::max(0, sprite->height - (-sprite->y_offs + (sub->bottom + 1) * ZOOM_BASE));
1090
1091 if (clip_left + clip_right >= sprite->width) return;
1092 if (clip_top + clip_bottom >= sprite->height) return;
1093
1094 bp.skip_left = UnScaleByZoomLower(clip_left, zoom);
1095 bp.skip_top = UnScaleByZoomLower(clip_top, zoom);
1096 bp.width = UnScaleByZoom(sprite->width - clip_left - clip_right, zoom);
1097 bp.height = UnScaleByZoom(sprite->height - clip_top - clip_bottom, zoom);
1098
1099 x += ScaleByZoom(bp.skip_left, zoom);
1100 y += ScaleByZoom(bp.skip_top, zoom);
1101 }
1102
1103 /* Copy the main data directly from the sprite */
1104 bp.sprite = sprite->data;
1105 bp.sprite_width = sprite->width;
1106 bp.sprite_height = sprite->height;
1107 bp.top = 0;
1108 bp.left = 0;
1109
1110 bp.dst = dpi->dst_ptr;
1111 bp.pitch = dpi->pitch;
1112 bp.remap = _colour_remap_ptr;
1113
1114 assert(sprite->width > 0);
1115 assert(sprite->height > 0);
1116
1117 if (bp.width <= 0) return;
1118 if (bp.height <= 0) return;
1119
1120 y -= SCALED_XY ? ScaleByZoom(dpi->top, zoom) : dpi->top;
1121 int y_unscaled = UnScaleByZoom(y, zoom);
1122 /* Check for top overflow */
1123 if (y < 0) {
1124 bp.height -= -y_unscaled;
1125 if (bp.height <= 0) return;
1126 bp.skip_top += -y_unscaled;
1127 y = 0;
1128 } else {
1129 bp.top = y_unscaled;
1130 }
1131
1132 /* Check for bottom overflow */
1133 y += SCALED_XY ? ScaleByZoom(bp.height - dpi->height, zoom) : ScaleByZoom(bp.height, zoom) - dpi->height;
1134 if (y > 0) {
1135 bp.height -= UnScaleByZoom(y, zoom);
1136 if (bp.height <= 0) return;
1137 }
1138
1139 x -= SCALED_XY ? ScaleByZoom(dpi->left, zoom) : dpi->left;
1140 int x_unscaled = UnScaleByZoom(x, zoom);
1141 /* Check for left overflow */
1142 if (x < 0) {
1143 bp.width -= -x_unscaled;
1144 if (bp.width <= 0) return;
1145 bp.skip_left += -x_unscaled;
1146 x = 0;
1147 } else {
1148 bp.left = x_unscaled;
1149 }
1150
1151 /* Check for right overflow */
1152 x += SCALED_XY ? ScaleByZoom(bp.width - dpi->width, zoom) : ScaleByZoom(bp.width, zoom) - dpi->width;
1153 if (x > 0) {
1154 bp.width -= UnScaleByZoom(x, zoom);
1155 if (bp.width <= 0) return;
1156 }
1157
1158 assert(bp.skip_left + bp.width <= UnScaleByZoom(sprite->width, zoom));
1159 assert(bp.skip_top + bp.height <= UnScaleByZoom(sprite->height, zoom));
1160
1161 /* We do not want to catch the mouse. However we also use that spritenumber for unknown (text) sprites. */
1162 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && sprite_id != SPR_CURSOR_MOUSE) {
1163 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1164 void *topleft = blitter->MoveTo(bp.dst, bp.left, bp.top);
1165 void *bottomright = blitter->MoveTo(topleft, bp.width - 1, bp.height - 1);
1166
1167 void *clicked = _newgrf_debug_sprite_picker.clicked_pixel;
1168
1169 if (topleft <= clicked && clicked <= bottomright) {
1170 uint offset = (((size_t)clicked - (size_t)topleft) / (blitter->GetScreenDepth() / 8)) % bp.pitch;
1171 if (offset < (uint)bp.width) {
1172 _newgrf_debug_sprite_picker.sprites.insert(sprite_id);
1173 }
1174 }
1175 }
1176
1177 BlitterFactory::GetCurrentBlitter()->Draw(&bp, mode, zoom);
1178}
1179
1187std::unique_ptr<uint32_t[]> DrawSpriteToRgbaBuffer(SpriteID spriteId, ZoomLevel zoom)
1188{
1189 /* Invalid zoom level requested? */
1190 if (zoom < _settings_client.gui.zoom_min || zoom > _settings_client.gui.zoom_max) return nullptr;
1191
1192 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1193 if (blitter->GetScreenDepth() != 8 && blitter->GetScreenDepth() != 32) return nullptr;
1194
1195 /* Gather information about the sprite to write, reserve memory */
1196 const SpriteID real_sprite = GB(spriteId, 0, SPRITE_WIDTH);
1197 const Sprite *sprite = GetSprite(real_sprite, SpriteType::Normal);
1198 Dimension dim = GetSpriteSize(real_sprite, nullptr, zoom);
1199 size_t dim_size = static_cast<size_t>(dim.width) * dim.height;
1200 std::unique_ptr<uint32_t[]> result = std::make_unique<uint32_t[]>(dim_size);
1201
1202 /* Prepare new DrawPixelInfo - Normally this would be the screen but we want to draw to another buffer here.
1203 * Normally, pitch would be scaled screen width, but in our case our "screen" is only the sprite width wide. */
1204 DrawPixelInfo dpi;
1205 dpi.dst_ptr = result.get();
1206 dpi.pitch = dim.width;
1207 dpi.left = 0;
1208 dpi.top = 0;
1209 dpi.width = dim.width;
1210 dpi.height = dim.height;
1211 dpi.zoom = zoom;
1212
1213 dim_size = static_cast<size_t>(dim.width) * dim.height;
1214
1215 /* If the current blitter is a paletted blitter, we have to render to an extra buffer and resolve the palette later. */
1216 std::unique_ptr<uint8_t[]> pal_buffer{};
1217 if (blitter->GetScreenDepth() == 8) {
1218 pal_buffer = std::make_unique<uint8_t[]>(dim_size);
1219 dpi.dst_ptr = pal_buffer.get();
1220 }
1221
1222 /* Temporarily disable screen animations while blitting - This prevents 40bpp_anim from writing to the animation buffer. */
1223 Backup<bool> disable_anim(_screen_disable_anim, true);
1224 GfxBlitter<1, true>(sprite, 0, 0, BlitterMode::Normal, nullptr, real_sprite, zoom, &dpi);
1225 disable_anim.Restore();
1226
1227 if (blitter->GetScreenDepth() == 8) {
1228 /* Resolve palette. */
1229 uint32_t *dst = result.get();
1230 const uint8_t *src = pal_buffer.get();
1231 for (size_t i = 0; i < dim_size; ++i) {
1232 *dst++ = _cur_palette.palette[*src++].data;
1233 }
1234 }
1235
1236 return result;
1237}
1238
1239static void GfxMainBlitterViewport(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id)
1240{
1241 GfxBlitter<ZOOM_BASE, false>(sprite, x, y, mode, sub, sprite_id, _cur_dpi->zoom);
1242}
1243
1244static void GfxMainBlitter(const Sprite *sprite, int x, int y, BlitterMode mode, const SubSprite *sub, SpriteID sprite_id, ZoomLevel zoom)
1245{
1246 GfxBlitter<1, true>(sprite, x, y, mode, sub, sprite_id, zoom);
1247}
1248
1253 void LoadStringWidthTable(FontSizes fontsizes)
1254{
1255 FontCache::ClearFontCaches(fontsizes);
1256
1257 for (FontSize fs : fontsizes) {
1258 for (uint i = 0; i != 224; i++) {
1259 _stringwidth_table[fs][i] = GetGlyphWidth(fs, i + 32);
1260 }
1261 }
1262}
1263
1270uint8_t GetCharacterWidth(FontSize size, char32_t key)
1271{
1272 /* Use _stringwidth_table cache if possible */
1273 if (key >= 32 && key < 256) return _stringwidth_table[size][key - 32];
1274
1275 return GetGlyphWidth(size, key);
1276}
1277
1283uint8_t GetDigitWidth(FontSize size)
1284{
1285 uint8_t width = 0;
1286 for (char c = '0'; c <= '9'; c++) {
1287 width = std::max(GetCharacterWidth(size, c), width);
1288 }
1289 return width;
1290}
1291
1299std::pair<uint8_t, uint8_t> GetBroadestDigit(FontSize size)
1300{
1301 uint8_t front = 0;
1302 uint8_t next = 0;
1303 int width = -1;
1304 for (char c = '9'; c >= '0'; c--) {
1305 int w = GetCharacterWidth(size, c);
1306 if (w <= width) continue;
1307
1308 width = w;
1309 next = c - '0';
1310 if (c != '0') front = c - '0';
1311 }
1312 return {front, next};
1313}
1314
1315void ScreenSizeChanged()
1316{
1317 _dirty_blocks_per_row = CeilDiv(_screen.width, DIRTY_BLOCK_WIDTH);
1318 _dirty_blocks_per_column = CeilDiv(_screen.height, DIRTY_BLOCK_HEIGHT);
1319 _dirty_blocks.resize(_dirty_blocks_per_column * _dirty_blocks_per_row);
1320
1321 /* check the dirty rect */
1322 if (_invalid_rect.right >= _screen.width) _invalid_rect.right = _screen.width;
1323 if (_invalid_rect.bottom >= _screen.height) _invalid_rect.bottom = _screen.height;
1324
1325 /* screen size changed and the old bitmap is invalid now, so we don't want to undraw it */
1326 _cursor.visible = false;
1327
1328 if (VideoDriver::GetInstance() != nullptr) {
1329 if (AdjustGUIZoom(true)) ReInitAllWindows(true);
1330 }
1331}
1332
1333void UndrawMouseCursor()
1334{
1335 /* Don't undraw mouse cursor if it is handled by the video driver. */
1336 if (VideoDriver::GetInstance()->UseSystemCursor()) return;
1337
1338 /* Don't undraw the mouse cursor if the screen is not ready */
1339 if (_screen.dst_ptr == nullptr) return;
1340
1341 if (_cursor.visible) {
1342 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1343 _cursor.visible = false;
1344 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);
1345 VideoDriver::GetInstance()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1346 }
1347}
1348
1349void DrawMouseCursor()
1350{
1351 /* Don't draw mouse cursor if it is handled by the video driver. */
1352 if (VideoDriver::GetInstance()->UseSystemCursor()) return;
1353
1354 /* Don't draw the mouse cursor if the screen is not ready */
1355 if (_screen.dst_ptr == nullptr) return;
1356
1357 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1358
1359 /* Redraw mouse cursor but only when it's inside the window */
1360 if (!_cursor.in_window) return;
1361
1362 /* Don't draw the mouse cursor if it's already drawn */
1363 if (_cursor.visible) {
1364 if (!_cursor.dirty) return;
1365 UndrawMouseCursor();
1366 }
1367
1368 /* Determine visible area */
1369 int left = _cursor.pos.x + _cursor.total_offs.x;
1370 int width = _cursor.total_size.x;
1371 if (left < 0) {
1372 width += left;
1373 left = 0;
1374 }
1375 if (left + width > _screen.width) {
1376 width = _screen.width - left;
1377 }
1378 if (width <= 0) return;
1379
1380 int top = _cursor.pos.y + _cursor.total_offs.y;
1381 int height = _cursor.total_size.y;
1382 if (top < 0) {
1383 height += top;
1384 top = 0;
1385 }
1386 if (top + height > _screen.height) {
1387 height = _screen.height - top;
1388 }
1389 if (height <= 0) return;
1390
1391 _cursor.draw_pos.x = left;
1392 _cursor.draw_pos.y = top;
1393 _cursor.draw_size.x = width;
1394 _cursor.draw_size.y = height;
1395
1396 uint8_t *buffer = _cursor_backup.Allocate(blitter->BufferSize(_cursor.draw_size.x, _cursor.draw_size.y));
1397
1398 /* Make backup of stuff below cursor */
1399 blitter->CopyToBuffer(blitter->MoveTo(_screen.dst_ptr, _cursor.draw_pos.x, _cursor.draw_pos.y), buffer, _cursor.draw_size.x, _cursor.draw_size.y);
1400
1401 /* Draw cursor on screen */
1402 _cur_dpi = &_screen;
1403 for (const auto &cs : _cursor.sprites) {
1404 DrawSprite(cs.image.sprite, cs.image.pal, _cursor.pos.x + cs.pos.x, _cursor.pos.y + cs.pos.y);
1405 }
1406
1407 VideoDriver::GetInstance()->MakeDirty(_cursor.draw_pos.x, _cursor.draw_pos.y, _cursor.draw_size.x, _cursor.draw_size.y);
1408
1409 _cursor.visible = true;
1410 _cursor.dirty = false;
1411}
1412
1423 void RedrawScreenRect(int left, int top, int right, int bottom)
1424{
1425 assert(right <= _screen.width && bottom <= _screen.height);
1426 if (_cursor.visible) {
1427 if (right > _cursor.draw_pos.x &&
1428 left < _cursor.draw_pos.x + _cursor.draw_size.x &&
1429 bottom > _cursor.draw_pos.y &&
1430 top < _cursor.draw_pos.y + _cursor.draw_size.y) {
1431 UndrawMouseCursor();
1432 }
1433 }
1434
1435 if (_networking) NetworkUndrawChatMessage();
1436
1437 DrawOverlappedWindowForAll(left, top, right, bottom);
1438
1439 VideoDriver::GetInstance()->MakeDirty(left, top, right - left, bottom - top);
1440}
1441
1449 void DrawDirtyBlocks()
1450{
1451 auto is_dirty = [](auto block) -> bool { return block != 0; };
1452 auto block = _dirty_blocks.begin();
1453
1454 for (size_t x = 0; x < _dirty_blocks_per_row; ++x) {
1455 auto last_of_column = block + _dirty_blocks_per_column;
1456 for (size_t y = 0; y < _dirty_blocks_per_column; ++y, ++block) {
1457 if (!is_dirty(*block)) continue;
1458
1459 /* First try coalescing downwards */
1460 size_t height = std::find_if_not(block + 1, last_of_column, is_dirty) - block;
1461 size_t width = 1;
1462
1463 /* Clear dirty state. */
1464 std::fill_n(block, height, 0);
1465
1466 /* Try coalescing to the right too. */
1467 auto block_right = block;
1468 for (size_t x_right = x + 1; x_right < _dirty_blocks_per_row; ++x_right, ++width) {
1469 block_right += _dirty_blocks_per_column;
1470 auto last_right = block_right + height;
1471
1472 if (std::find_if_not(block_right, last_right, is_dirty) != last_right) break;
1473
1474 /* Clear dirty state. */
1475 std::fill_n(block_right, height, 0);
1476 }
1477
1478 int left = static_cast<int>(x * DIRTY_BLOCK_WIDTH);
1479 int top = static_cast<int>(y * DIRTY_BLOCK_HEIGHT);
1480 int right = left + static_cast<int>(width * DIRTY_BLOCK_WIDTH);
1481 int bottom = top + static_cast<int>(height * DIRTY_BLOCK_HEIGHT);
1482
1483 left = std::max(_invalid_rect.left, left);
1484 top = std::max(_invalid_rect.top, top);
1485 right = std::min(_invalid_rect.right, right);
1486 bottom = std::min(_invalid_rect.bottom, bottom);
1487
1488 if (left < right && top < bottom) {
1489 RedrawScreenRect(left, top, right, bottom);
1490 }
1491 }
1492 }
1493
1494 ++_dirty_block_colour;
1495 _invalid_rect.left = _screen.width;
1496 _invalid_rect.top = _screen.height;
1497 _invalid_rect.right = 0;
1498 _invalid_rect.bottom = 0;
1499}
1500
1513 void AddDirtyBlock(int left, int top, int right, int bottom)
1514{
1515 if (left < 0) left = 0;
1516 if (top < 0) top = 0;
1517 if (right > _screen.width) right = _screen.width;
1518 if (bottom > _screen.height) bottom = _screen.height;
1519
1520 if (left >= right || top >= bottom) return;
1521
1522 _invalid_rect.left = std::min(_invalid_rect.left, left);
1523 _invalid_rect.top = std::min(_invalid_rect.top, top);
1524 _invalid_rect.right = std::max(_invalid_rect.right, right);
1525 _invalid_rect.bottom = std::max(_invalid_rect.bottom, bottom);
1526
1527 left /= DIRTY_BLOCK_WIDTH;
1528 top /= DIRTY_BLOCK_HEIGHT;
1529 right = CeilDiv(right, DIRTY_BLOCK_WIDTH);
1530 int height = CeilDiv(bottom, DIRTY_BLOCK_HEIGHT) - top;
1531
1532 assert(left < right && height > 0);
1533
1534 for (; left < right; ++left) {
1535 size_t offset = _dirty_blocks_per_column * left + top;
1536 std::fill_n(_dirty_blocks.begin() + offset, height, 0xFF);
1537 }
1538}
1539
1546 void MarkWholeScreenDirty()
1547{
1548 AddDirtyBlock(0, 0, _screen.width, _screen.height);
1549}
1550
1565 bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
1566{
1567 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
1568 const DrawPixelInfo *o = _cur_dpi;
1569
1570 n->zoom = ZoomLevel::Min;
1571
1572 assert(width > 0);
1573 assert(height > 0);
1574
1575 if ((left -= o->left) < 0) {
1576 width += left;
1577 if (width <= 0) return false;
1578 n->left = -left;
1579 left = 0;
1580 } else {
1581 n->left = 0;
1582 }
1583
1584 if (width > o->width - left) {
1585 width = o->width - left;
1586 if (width <= 0) return false;
1587 }
1588 n->width = width;
1589
1590 if ((top -= o->top) < 0) {
1591 height += top;
1592 if (height <= 0) return false;
1593 n->top = -top;
1594 top = 0;
1595 } else {
1596 n->top = 0;
1597 }
1598
1599 n->dst_ptr = blitter->MoveTo(o->dst_ptr, left, top);
1600 n->pitch = o->pitch;
1601
1602 if (height > o->height - top) {
1603 height = o->height - top;
1604 if (height <= 0) return false;
1605 }
1606 n->height = height;
1607
1608 return true;
1609}
1610
1615 void UpdateCursorSize()
1616{
1617 /* Ignore setting any cursor before the sprites are loaded. */
1618 if (GetMaxSpriteID() == 0) return;
1619
1620 bool first = true;
1621 for (const auto &cs : _cursor.sprites) {
1622 const Sprite *p = GetSprite(GB(cs.image.sprite, 0, SPRITE_WIDTH), SpriteType::Normal);
1623 Point offs, size;
1624 offs.x = UnScaleGUI(p->x_offs) + cs.pos.x;
1625 offs.y = UnScaleGUI(p->y_offs) + cs.pos.y;
1626 size.x = UnScaleGUI(p->width);
1627 size.y = UnScaleGUI(p->height);
1628
1629 if (first) {
1630 /* First sprite sets the total. */
1631 _cursor.total_offs = offs;
1632 _cursor.total_size = size;
1633 first = false;
1634 } else {
1635 /* Additional sprites expand the total. */
1636 int right = std::max(_cursor.total_offs.x + _cursor.total_size.x, offs.x + size.x);
1637 int bottom = std::max(_cursor.total_offs.y + _cursor.total_size.y, offs.y + size.y);
1638 if (offs.x < _cursor.total_offs.x) _cursor.total_offs.x = offs.x;
1639 if (offs.y < _cursor.total_offs.y) _cursor.total_offs.y = offs.y;
1640 _cursor.total_size.x = right - _cursor.total_offs.x;
1641 _cursor.total_size.y = bottom - _cursor.total_offs.y;
1642 }
1643 }
1644
1645 _cursor.dirty = true;
1646}
1647
1653 static void SetCursorSprite(CursorID cursor, PaletteID pal)
1654{
1655 if (_cursor.sprites.size() == 1 && _cursor.sprites[0].image.sprite == cursor && _cursor.sprites[0].image.pal == pal) return;
1656
1657 _cursor.sprites.clear();
1658 _cursor.sprites.emplace_back(cursor, pal, 0, 0);
1659
1660 UpdateCursorSize();
1661}
1662
1663static void SwitchAnimatedCursor()
1664{
1665 if (_cursor.animate_cur == std::end(_cursor.animate_list)) {
1666 _cursor.animate_cur = std::begin(_cursor.animate_list);
1667 }
1668
1669 assert(!_cursor.sprites.empty());
1670 SetCursorSprite(_cursor.animate_cur->sprite, _cursor.sprites[0].image.pal);
1671
1672 _cursor.animate_timeout = _cursor.animate_cur->display_time;
1673 ++_cursor.animate_cur;
1674}
1675
1676void CursorTick()
1677{
1678 if (_cursor.animate_timeout != 0 && --_cursor.animate_timeout == 0) {
1679 SwitchAnimatedCursor();
1680 }
1681}
1682
1687 void SetMouseCursorBusy(bool busy)
1688{
1689 assert(!_cursor.sprites.empty());
1690 if (busy) {
1691 if (_cursor.sprites[0].image.sprite == SPR_CURSOR_MOUSE) SetMouseCursor(SPR_CURSOR_ZZZ, PAL_NONE);
1692 } else {
1693 if (_cursor.sprites[0].image.sprite == SPR_CURSOR_ZZZ) SetMouseCursor(SPR_CURSOR_MOUSE, PAL_NONE);
1694 }
1695}
1696
1703 void SetMouseCursor(CursorID sprite, PaletteID pal)
1704{
1705 /* Turn off animation */
1706 _cursor.animate_timeout = 0;
1707 /* Set cursor */
1708 SetCursorSprite(sprite, pal);
1709}
1710
1716 void SetAnimatedMouseCursor(std::span<const AnimCursor> table)
1717{
1718 assert(!_cursor.sprites.empty());
1719 _cursor.animate_list = table;
1720 _cursor.animate_cur = std::end(table);
1721 _cursor.sprites[0].image.pal = PAL_NONE;
1722 SwitchAnimatedCursor();
1723}
1724
1731 void CursorVars::UpdateCursorPositionRelative(int delta_x, int delta_y)
1732{
1733 assert(this->fix_at);
1734
1735 this->delta.x = delta_x;
1736 this->delta.y = delta_y;
1737}
1738
1745 bool CursorVars::UpdateCursorPosition(int x, int y)
1746{
1747 this->delta.x = x - this->pos.x;
1748 this->delta.y = y - this->pos.y;
1749
1750 if (this->fix_at) {
1751 return this->delta.x != 0 || this->delta.y != 0;
1752 } else if (this->pos.x != x || this->pos.y != y) {
1753 this->dirty = true;
1754 this->pos.x = x;
1755 this->pos.y = y;
1756 }
1757
1758 return false;
1759}
1760
1761bool ChangeResInGame(int width, int height)
1762{
1763 return (_screen.width == width && _screen.height == height) || VideoDriver::GetInstance()->ChangeResolution(width, height);
1764}
1765
1766bool ToggleFullScreen(bool fs)
1767{
1768 bool result = VideoDriver::GetInstance()->ToggleFullscreen(fs);
1769 if (_fullscreen != fs && _resolutions.empty()) {
1770 Debug(driver, 0, "Could not find a suitable fullscreen resolution");
1771 }
1772 return result;
1773}
1774
1775void SortResolutions()
1776{
1777 std::sort(_resolutions.begin(), _resolutions.end());
1778
1779 /* Remove any duplicates from the list. */
1780 auto last = std::unique(_resolutions.begin(), _resolutions.end());
1781 _resolutions.erase(last, _resolutions.end());
1782}
1783
1787 void UpdateGUIZoom()
1788{
1789 /* Determine real GUI zoom to use. */
1790 if (_gui_scale_cfg == -1) {
1791 /* Minimum design size of the game is 640x480. */
1792 float xs = _screen.width / 640.f;
1793 float ys = _screen.height / 480.f;
1794 int scale = std::min(xs, ys) * 100;
1795 /* Round down scaling to 25% increments and clamp to limits. */
1796 _gui_scale = Clamp((scale / 25) * 25, MIN_INTERFACE_SCALE, MAX_INTERFACE_SCALE);
1797 } else {
1798 _gui_scale = Clamp(_gui_scale_cfg, MIN_INTERFACE_SCALE, MAX_INTERFACE_SCALE);
1799 }
1800
1801 ZoomLevel new_zoom = ScaleGUITrad(1) <= 1 ? ZoomLevel::Normal : ScaleGUITrad(1) >= 4 ? ZoomLevel::In4x : ZoomLevel::In2x;
1802 /* Font glyphs should not be clamped to min/max zoom. */
1803 _font_zoom = new_zoom;
1804 /* Ensure the gui_zoom is clamped between min/max. */
1805 new_zoom = Clamp(new_zoom, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
1806 _gui_zoom = new_zoom;
1807}
1808
1815 bool AdjustGUIZoom(bool automatic)
1816{
1817 ZoomLevel old_gui_zoom = _gui_zoom;
1818 ZoomLevel old_font_zoom = _font_zoom;
1819 int old_scale = _gui_scale;
1820 UpdateGUIZoom();
1821 if (old_scale == _gui_scale && old_gui_zoom == _gui_zoom) return false;
1822
1823 /* Update cursors if sprite zoom level has changed. */
1824 if (old_gui_zoom != _gui_zoom) {
1825 VideoDriver::GetInstance()->ClearSystemSprites();
1826 UpdateCursorSize();
1827 }
1828 if (old_font_zoom != _font_zoom) {
1829 GfxClearFontSpriteCache();
1830 }
1831 FontCache::ClearFontCaches(FONTSIZES_ALL);
1832 LoadStringWidthTable();
1833
1834 SetupWidgetDimensions();
1835 UpdateAllVirtCoords();
1836
1837 /* Adjust all window sizes to match the new zoom level, so that they don't appear
1838 to move around when the application is moved to a screen with different DPI. */
1839 auto zoom_shift = old_gui_zoom - _gui_zoom;
1840 for (Window *w : Window::Iterate()) {
1841 if (automatic) {
1842 w->left = (w->left * _gui_scale) / old_scale;
1843 w->top = (w->top * _gui_scale) / old_scale;
1844 }
1845 if (w->viewport != nullptr) {
1846 w->viewport->zoom = Clamp(w->viewport->zoom - zoom_shift, _settings_client.gui.zoom_min, _settings_client.gui.zoom_max);
1847 }
1848 }
1849
1850 return true;
1851}
1852
1853void ChangeGameSpeed(bool enable_fast_forward)
1854{
1855 if (enable_fast_forward) {
1856 _game_speed = _settings_client.gui.fast_forward_speed_limit;
1857 } else {
1858 _game_speed = 100;
1859 }
1860}
UpdateAllVirtCoords
void UpdateAllVirtCoords()
Update the viewport coordinates of all signs.
Definition afterload.cpp:220
backup_type.hpp
Class for backupping variables and making sure they are restored later.
BlitterMode
BlitterMode
The modes of blitting we can do.
Definition base.hpp:17
BlitterMode::Transparent
@ Transparent
Perform transparency darkening remapping.
BlitterMode::CrashRemap
@ CrashRemap
Perform a crash remapping.
BlitterMode::BlackRemap
@ BlackRemap
Perform remapping to a completely blackened sprite.
BlitterMode::Normal
@ Normal
Perform the simple blitting.
BlitterMode::TransparentRemap
@ TransparentRemap
Perform transparency colour remapping.
BlitterMode::ColourRemap
@ ColourRemap
Perform a colour remapping.
GB
static constexpr uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition bitmath_func.hpp:32
HasBit
constexpr bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition bitmath_func.hpp:103
BlitterFactory::GetCurrentBlitter
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:136
Blitter
How all blitters should look like.
Definition base.hpp:29
Blitter::MoveTo
virtual void * MoveTo(void *video, int x, int y)=0
Move the destination pointer the requested amount x and y, keeping in mind any pitch and bpp of the r...
Blitter::GetScreenDepth
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
Blitter::BufferSize
virtual size_t BufferSize(uint width, uint height)=0
Calculate how much memory there is needed for an image of this size in the video-buffer.
Blitter::DrawLine
virtual void DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, PixelColour colour, int width, int dash=0)=0
Draw a line with a given colour.
Blitter::DrawColourMappingRect
virtual void DrawColourMappingRect(void *dst, int width, int height, PaletteID pal)=0
Draw a colourtable to the screen.
Blitter::SetPixel
virtual void SetPixel(void *video, int x, int y, PixelColour colour)=0
Draw a pixel with a given colour on the video-buffer.
Blitter::Draw
virtual void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom)=0
Draw an image to the screen, given an amount of params defined above.
Blitter::CopyToBuffer
virtual void CopyToBuffer(const void *video, void *dst, int width, int height)=0
Copy from the screen to a buffer.
Blitter::DrawRect
virtual void DrawRect(void *video, int width, int height, PixelColour colour)=0
Make a single horizontal line in a single colour on the video-buffer.
Blitter::CopyFromBuffer
virtual void CopyFromBuffer(void *video, const void *src, int width, int height)=0
Copy from a buffer to the screen.
Blitter::ScrollBuffer
virtual void ScrollBuffer(void *video, int &left, int &top, int &width, int &height, int scroll_x, int scroll_y)=0
Scroll the videobuffer some 'x' and 'y' value.
EnumBitSet
Enum-as-bit-set wrapper.
Definition enum_type.hpp:177
FlatSet::insert
std::pair< const_iterator, bool > insert(const Tkey &key)
Insert a key into the set, if it does not already exist.
Definition flatset_type.hpp:31
FontCache
Font cache for basic fonts.
Definition fontcache.h:22
FontCache::GetGlyph
virtual const Sprite * GetGlyph(GlyphID key)=0
Get the glyph (sprite) of the given key.
FontCache::ClearFontCaches
static void ClearFontCaches(FontSizes fontsizes)
Clear cached information for the specified font caches.
Definition fontcache.cpp:257
FontCache::GetSize
FontSize GetSize() const
Get the FontSize of the font.
Definition fontcache.h:53
FontCache::GetDrawGlyphShadow
virtual bool GetDrawGlyphShadow()=0
Do we need to draw a glyph shadow?
Font
Container with information about a font.
Definition gfx_layout.h:97
Font::fc
FontCache * fc
The font we are using.
Definition gfx_layout.h:99
Font::colour
TextColour colour
The colour this font has to be.
Definition gfx_layout.h:100
Layouter
The layouter performs all the layout work.
Definition gfx_layout.h:160
Layouter::GetBounds
Dimension GetBounds()
Get the boundaries of this paragraph.
Definition gfx_layout.cpp:208
ParagraphLayouter::Line
A single line worth of VisualRuns.
Definition gfx_layout.h:141
ParagraphLayouter::VisualRun
Visual run contains data about the bit of text with the same font.
Definition gfx_layout.h:129
ReusableBuffer
A reusable buffer that can be used for places that temporary allocate a bit of memory and do that ver...
Definition alloc_type.hpp:22
ReusableBuffer::GetBuffer
const T * GetBuffer() const
Get the currently allocated buffer.
Definition alloc_type.hpp:58
ReusableBuffer::Allocate
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition alloc_type.hpp:34
VideoDriver::ToggleFullscreen
virtual bool ToggleFullscreen(bool fullscreen)=0
Change the full screen setting.
VideoDriver::ClearSystemSprites
virtual void ClearSystemSprites()
Clear all cached sprites.
Definition video_driver.hpp:108
VideoDriver::MakeDirty
virtual void MakeDirty(int left, int top, int width, int height)=0
Mark a particular area dirty.
VideoDriver::ChangeResolution
virtual bool ChangeResolution(int w, int h)=0
Change the resolution of the window.
VideoDriver::GetInstance
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Definition video_driver.hpp:192
WidgetDimensions::scaled
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
control_codes.h
Control codes that are embedded in the translation strings.
Debug
#define Debug(category, level, format_string,...)
Output a line of debugging information.
Definition debug.h:37
_resolutions
std::vector< Dimension > _resolutions
List of resolutions.
Definition driver.cpp:28
HasFlag
constexpr bool HasFlag(const T x, const T y)
Checks if a value in a bitset enum is set.
Definition enum_type.hpp:142
factory.hpp
Factory to 'query' all available blitters.
GetCharacterHeight
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:87
GetGlyph
const Sprite * GetGlyph(FontSize size, char32_t key)
Get the Sprite for a glyph.
Definition fontcache.h:153
GetGlyphWidth
uint GetGlyphWidth(FontSize size, char32_t key)
Get the width of a glyph.
Definition fontcache.h:160
GlyphID
uint32_t GlyphID
Glyphs are characters from a font.
Definition fontcache.h:18
maxdim
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Definition geometry_func.cpp:22
geometry_func.hpp
Geometry functions.
CentreBounds
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Definition geometry_type.hpp:26
GetStringHeight
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition gfx.cpp:712
SetMouseCursor
void SetMouseCursor(CursorID sprite, PaletteID pal)
Assign a single non-animated sprite to the cursor.
Definition gfx.cpp:1703
GetSpriteSize
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:965
UpdateCursorSize
void UpdateCursorSize()
Update cursor dimension.
Definition gfx.cpp:1615
SetCursorSprite
static void SetCursorSprite(CursorID cursor, PaletteID pal)
Switch cursor to different sprite.
Definition gfx.cpp:1653
GetBroadestDigit
std::pair< uint8_t, uint8_t > GetBroadestDigit(FontSize size)
Determine the broadest digits for guessing the maximum width of a n-digit number.
Definition gfx.cpp:1299
DrawLayoutLine
static int DrawLayoutLine(const ParagraphLayouter::Line &line, int y, int left, int right, StringAlignment align, bool underline, bool truncation, TextColour default_colour)
Drawing routine for drawing a laid out line of text.
Definition gfx.cpp:503
_shift_pressed
bool _shift_pressed
Is Shift pressed?
Definition gfx.cpp:39
GfxBlitter
static void GfxBlitter(const Sprite *const sprite, int x, int y, BlitterMode mode, const SubSprite *const sub, SpriteID sprite_id, ZoomLevel zoom, const DrawPixelInfo *dst=nullptr)
The code for setting up the blitter mode and sprite information before finally drawing the sprite.
Definition gfx.cpp:1063
GetStringLineCount
int GetStringLineCount(std::string_view str, int maxw)
Calculates number of lines of string.
Definition gfx.cpp:736
LoadStringWidthTable
void LoadStringWidthTable(FontSizes fontsizes)
Initialize _stringwidth_table cache for the specified font sizes.
Definition gfx.cpp:1253
_left_button_down
bool _left_button_down
Is left mouse button pressed?
Definition gfx.cpp:41
GetStringBoundingBox
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
MakePolygonSegments
static std::vector< LineSegment > MakePolygonSegments(std::span< const Point > shape, Point offset)
Make line segments from a polygon defined by points, translated by an offset.
Definition gfx.cpp:173
GetStringListBoundingBox
Dimension GetStringListBoundingBox(std::span< const StringID > list, FontSize fontsize)
Get maximum dimension of a list of strings.
Definition gfx.cpp:932
DrawString
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:665
_ctrl_pressed
bool _ctrl_pressed
Is Ctrl pressed?
Definition gfx.cpp:38
SetColourRemap
static void SetColourRemap(TextColour colour)
Set the colour remap to be for the given colour.
Definition gfx.cpp:472
_dirkeys
uint8_t _dirkeys
1 = left, 2 = up, 4 = right, 8 = down
Definition gfx.cpp:34
_screen_disable_anim
bool _screen_disable_anim
Disable palette animation (important for 32bpp-anim blitter during giant screenshot)
Definition gfx.cpp:46
_font_zoom
ZoomLevel _font_zoom
Sprite font Zoom level (not clamped)
Definition gfx.cpp:62
_left_button_clicked
bool _left_button_clicked
Is left mouse button clicked?
Definition gfx.cpp:42
GetStringListWidth
uint GetStringListWidth(std::span< const StringID > list, FontSize fontsize)
Get maximum width of a list of strings.
Definition gfx.cpp:917
_game_speed
uint16_t _game_speed
Current game-speed; 100 is 1x, 0 is infinite.
Definition gfx.cpp:40
GetBlitterMode
static BlitterMode GetBlitterMode(PaletteID pal)
Helper function to get the blitter mode for different types of palettes.
Definition gfx.cpp:985
GfxDoDrawLine
static void GfxDoDrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, PixelColour colour, int width, int dash=0)
Check line clipping by using a linear equation and draw the visible part of the line given by x/y and...
Definition gfx.cpp:317
SetMouseCursorBusy
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition gfx.cpp:1687
_game_session_stats
GameSessionStats _game_session_stats
Statistics about the current session.
Definition gfx.cpp:51
DrawRectOutline
void DrawRectOutline(const Rect &r, PixelColour colour, int width, int dash)
Draw the outline of a Rect.
Definition gfx.cpp:460
UpdateGUIZoom
void UpdateGUIZoom()
Resolve GUI zoom level, if auto-suggestion is requested.
Definition gfx.cpp:1787
DrawSprite
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1031
_right_button_clicked
bool _right_button_clicked
Is right mouse button clicked?
Definition gfx.cpp:44
SetAnimatedMouseCursor
void SetAnimatedMouseCursor(std::span< const AnimCursor > table)
Assign an animation to the cursor.
Definition gfx.cpp:1716
GetDigitWidth
uint8_t GetDigitWidth(FontSize size)
Return the maximum width of single digit.
Definition gfx.cpp:1283
_gui_scale_cfg
int _gui_scale_cfg
GUI scale in config.
Definition gfx.cpp:64
DrawStringMultiLineWithClipping
bool DrawStringMultiLineWithClipping(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw a multiline string, possibly over multiple lines, if the region is within the current display cl...
Definition gfx.cpp:867
GetCharacterWidth
uint8_t GetCharacterWidth(FontSize size, char32_t key)
Return width of character glyph.
Definition gfx.cpp:1270
DrawSpriteViewport
void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub)
Draw a sprite in a viewport.
Definition gfx.cpp:1003
_pause_mode
PauseModes _pause_mode
The current pause mode.
Definition gfx.cpp:50
GfxFillPolygon
void GfxFillPolygon(std::span< const Point > shape, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Fill a polygon with colour.
Definition gfx.cpp:212
GfxPreprocessLine
static bool GfxPreprocessLine(DrawPixelInfo *dpi, int &x, int &y, int &x2, int &y2, int width)
Align parameters of a line to the given DPI and check simple clipping.
Definition gfx.cpp:375
GetStringMultiLineBoundingBox
Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
Calculate string bounding box for multi-line strings.
Definition gfx.cpp:748
DrawStringMultiLine
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
DrawSpriteToRgbaBuffer
std::unique_ptr< uint32_t[]> DrawSpriteToRgbaBuffer(SpriteID spriteId, ZoomLevel zoom)
Draws a sprite to a new RGBA buffer (see Colour union) instead of drawing to the screen.
Definition gfx.cpp:1187
GfxFillRect
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:115
_stringwidth_table
static uint8_t _stringwidth_table[FS_END][224]
Cache containing width of often used characters.
Definition gfx.cpp:53
_switch_mode
SwitchMode _switch_mode
The next mainloop command.
Definition gfx.cpp:49
DrawBox
void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3)
Draws the projection of a parallelepiped.
Definition gfx.cpp:422
_gui_zoom
ZoomLevel _gui_zoom
GUI Zoom level.
Definition gfx.cpp:61
FillDrawPixelInfo
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1565
_right_button_down
bool _right_button_down
Is right mouse button pressed?
Definition gfx.cpp:43
_string_colourremap
static uint8_t _string_colourremap[3]
Recoloursprite for stringdrawing. The grf loader ensures that SpriteType::Font sprites only use colou...
Definition gfx.cpp:75
AdjustGUIZoom
bool AdjustGUIZoom(bool automatic)
Resolve GUI zoom level and adjust GUI to new zoom, if auto-suggestion is requested.
Definition gfx.cpp:1815
DrawCharCentered
void DrawCharCentered(char32_t c, const Rect &r, TextColour colour)
Draw single character horizontally centered around (x,y)
Definition gfx.cpp:948
_gui_scale
int _gui_scale
GUI scale, 100 is 100%.
Definition gfx.cpp:63
gfx_func.h
Functions related to the gfx engine.
DrawOverlappedWindowForAll
void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
Definition window.cpp:945
_cur_palette
Palette _cur_palette
Current palette.
Definition palette.cpp:24
gfx_layout.h
Functions related to laying out the texts.
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition gfx_type.h:17
SpriteType::Recolour
@ Recolour
Recolour sprite.
SpriteType::Normal
@ Normal
The most basic (normal) sprite.
FontSize
FontSize
Available font sizes.
Definition gfx_type.h:248
FS_MONO
@ FS_MONO
Index of the monospaced font in the font tables.
Definition gfx_type.h:252
FS_SMALL
@ FS_SMALL
Index of the small font in the font tables.
Definition gfx_type.h:250
FS_NORMAL
@ FS_NORMAL
Index of the normal font in the font tables.
Definition gfx_type.h:249
FS_LARGE
@ FS_LARGE
Index of the large font in the font tables.
Definition gfx_type.h:251
CursorID
uint32_t CursorID
The number of the cursor (sprite)
Definition gfx_type.h:19
StringAlignment
StringAlignment
How to align the to-be drawn text.
Definition gfx_type.h:387
SA_TOP
@ SA_TOP
Top align the text.
Definition gfx_type.h:393
SA_LEFT
@ SA_LEFT
Left align the text.
Definition gfx_type.h:388
SA_HOR_MASK
@ SA_HOR_MASK
Mask for horizontal alignment.
Definition gfx_type.h:391
SA_RIGHT
@ SA_RIGHT
Right align the text (must be a single bit).
Definition gfx_type.h:390
SA_HOR_CENTER
@ SA_HOR_CENTER
Horizontally center the text.
Definition gfx_type.h:389
SA_VERT_MASK
@ SA_VERT_MASK
Mask for vertical alignment.
Definition gfx_type.h:396
SA_FORCE
@ SA_FORCE
Force the alignment, i.e. don't swap for RTL languages.
Definition gfx_type.h:400
SA_BOTTOM
@ SA_BOTTOM
Bottom align the text.
Definition gfx_type.h:395
SA_VERT_CENTER
@ SA_VERT_CENTER
Vertically center the text.
Definition gfx_type.h:394
FONTSIZES_ALL
constexpr FontSizes FONTSIZES_ALL
Mask of all possible font sizes.
Definition gfx_type.h:262
PaletteID
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
TextColour
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:307
TC_FORCED
@ TC_FORCED
Ignore colour changes from strings.
Definition gfx_type.h:332
TC_NO_SHADE
@ TC_NO_SHADE
Do not add shading to this text colour.
Definition gfx_type.h:331
TC_IS_PALETTE_COLOUR
@ TC_IS_PALETTE_COLOUR
Colour value is already a real palette colour index, not an index of a StringColour.
Definition gfx_type.h:330
FillRectMode
FillRectMode
Define the operation GfxFillRect performs.
Definition gfx_type.h:344
FILLRECT_CHECKER
@ FILLRECT_CHECKER
Draw only every second pixel, used for greying-out.
Definition gfx_type.h:346
FILLRECT_RECOLOUR
@ FILLRECT_RECOLOUR
Apply a recolour sprite to the screen content.
Definition gfx_type.h:347
_invalid_rect
static Rect _invalid_rect
The rect for repaint.
Definition gfx.cpp:73
AddDirtyBlock
void AddDirtyBlock(int left, int top, int right, int bottom)
Extend the internal _invalid_rect rectangle to contain the rectangle defined by the given parameters.
Definition gfx.cpp:1513
DrawDirtyBlocks
void DrawDirtyBlocks()
Repaints the rectangle blocks which are marked as 'dirty'.
Definition gfx.cpp:1449
MarkWholeScreenDirty
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1546
RedrawScreenRect
void RedrawScreenRect(int left, int top, int right, int bottom)
Repaints a specific rectangle of the screen.
Definition gfx.cpp:1423
abs
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
RoundDivSU
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
Definition math_func.hpp:332
CeilDiv
constexpr uint CeilDiv(uint a, uint b)
Computes ceil(a / b) for non-negative a and b.
Definition math_func.hpp:310
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
_networking
bool _networking
are we in networking mode?
Definition network.cpp:66
network.h
Basic functions/variables used all over the place.
NetworkUndrawChatMessage
void NetworkUndrawChatMessage()
Hide the chatbox.
Definition network_chat_gui.cpp:120
network_func.h
Network functions used by other parts of OpenTTD.
newgrf_debug.h
Functions/types related to NewGRF debugging.
_newgrf_debug_sprite_picker
NewGrfDebugSpritePicker _newgrf_debug_sprite_picker
The sprite picker.
Definition newgrf_debug_gui.cpp:53
GameMode
GameMode
Mode which defines the state of the game.
Definition openttd.h:18
SwitchMode
SwitchMode
Mode which defines what mode we're switching to.
Definition openttd.h:26
PC_WHITE
static constexpr PixelColour PC_WHITE
White palette colour.
Definition palette_func.h:99
progress.h
Functions related to modal progress.
safeguards.h
A number of safeguards to prevent using unsafe methods.
_settings_client
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
settings_type.h
Types related to global configuration settings.
GfxClearFontSpriteCache
void GfxClearFontSpriteCache()
Remove all encoded font sprites from the sprite cache without discarding sprite location information.
Definition spritecache.cpp:923
GetMaxSpriteID
SpriteID GetMaxSpriteID()
Get a reasonable (upper bound) estimate of the maximum SpriteID used in OpenTTD; there will be no spr...
Definition spritecache.cpp:202
sprites.h
This file contains all sprite-related enums and defines.
PALETTE_ALL_BLACK
static const PaletteID PALETTE_ALL_BLACK
Exchange any colour by black, needed for painting fictive tiles outside map.
Definition sprites.h:1625
PALETTE_WIDTH
static constexpr uint8_t PALETTE_WIDTH
number of bits of the sprite containing the recolour palette
Definition sprites.h:1548
PALETTE_MODIFIER_TRANSPARENT
static constexpr uint8_t PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition sprites.h:1561
PALETTE_CRASH
static const PaletteID PALETTE_CRASH
Recolour sprite greying of crashed vehicles.
Definition sprites.h:1619
SPR_CURSOR_MOUSE
static const CursorID SPR_CURSOR_MOUSE
Cursor sprite numbers.
Definition sprites.h:1404
PALETTE_TEXT_RECOLOUR
static constexpr uint8_t PALETTE_TEXT_RECOLOUR
Set if palette is actually a magic text recolour.
Definition sprites.h:1546
SPRITE_WIDTH
static constexpr uint8_t SPRITE_WIDTH
number of bits for the sprite number
Definition sprites.h:1549
PALETTE_TO_TRANSPARENT
static const PaletteID PALETTE_TO_TRANSPARENT
This sets the sprite to transparent.
Definition sprites.h:1616
stdafx.h
Definition of base types and functions in a cross-platform compatible way.
string_colours.h
The colour translation of GRF's strings.
_string_colourmap
static constexpr PixelColour _string_colourmap[17]
Colour mapping for TextColour.
Definition string_colours.h:11
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
_current_text_dir
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:56
GetEllipsis
std::string_view GetEllipsis()
Get the ellipsis string for the current language.
Definition strings.cpp:308
strings_func.h
Functions related to OTTD's strings.
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition strings_type.h:19
TD_RTL
@ TD_RTL
Text is written right-to-left by default.
Definition strings_type.h:27
Backup
Class to backup a specific variable and restore it later.
Definition backup_type.hpp:21
Backup::Restore
void Restore()
Restore the variable.
Definition backup_type.hpp:110
Blitter::BlitterParams
Parameters related to blitting.
Definition base.hpp:32
Blitter::BlitterParams::skip_top
int skip_top
How much pixels of the source to skip on the top (based on zoom of dst)
Definition base.hpp:37
Blitter::BlitterParams::sprite_height
int sprite_height
Real height of the sprite.
Definition base.hpp:41
Blitter::BlitterParams::dst
void * dst
Destination buffer.
Definition base.hpp:45
Blitter::BlitterParams::left
int left
The left offset in the 'dst' in pixels to start drawing.
Definition base.hpp:42
Blitter::BlitterParams::pitch
int pitch
The pitch of the destination buffer.
Definition base.hpp:46
Blitter::BlitterParams::sprite_width
int sprite_width
Real width of the sprite.
Definition base.hpp:40
Blitter::BlitterParams::skip_left
int skip_left
How much pixels of the source to skip on the left (based on zoom of dst)
Definition base.hpp:36
Blitter::BlitterParams::height
int height
The height in pixels that needs to be drawn to dst.
Definition base.hpp:39
Blitter::BlitterParams::remap
const uint8_t * remap
XXX – Temporary storage for remap array.
Definition base.hpp:34
Blitter::BlitterParams::width
int width
The width in pixels that needs to be drawn to dst.
Definition base.hpp:38
Blitter::BlitterParams::sprite
const void * sprite
Pointer to the sprite how ever the encoder stored it.
Definition base.hpp:33
Blitter::BlitterParams::top
int top
The top offset in the 'dst' in pixels to start drawing.
Definition base.hpp:43
ClientSettings::gui
GUISettings gui
settings related to the GUI
Definition settings_type.h:650
Coord2D< int >
Coord2D::y
T y
Y coordinate.
Definition geometry_type.hpp:35
Coord2D::x
T x
X coordinate.
Definition geometry_type.hpp:34
CursorVars
Collection of variables for cursor-display and -animation.
Definition gfx_type.h:123
CursorVars::visible
bool visible
cursor is visible
Definition gfx_type.h:145
CursorVars::UpdateCursorPosition
bool UpdateCursorPosition(int x, int y)
Update cursor position on mouse movement.
Definition gfx.cpp:1745
CursorVars::animate_timeout
uint animate_timeout
in case of animated cursor, number of ticks to show the current cursor
Definition gfx_type.h:143
CursorVars::sprites
std::vector< CursorSprite > sprites
Sprites comprising cursor.
Definition gfx_type.h:136
CursorVars::fix_at
bool fix_at
mouse is moving, but cursor is not (used for scrolling)
Definition gfx_type.h:128
CursorVars::pos
Point pos
logical mouse position
Definition gfx_type.h:125
CursorVars::UpdateCursorPositionRelative
void UpdateCursorPositionRelative(int delta_x, int delta_y)
Update cursor position based on a relative change.
Definition gfx.cpp:1731
CursorVars::animate_cur
std::span< constAnimCursor >::iterator animate_cur
in case of animated cursor, current frame
Definition gfx_type.h:142
CursorVars::in_window
bool in_window
mouse inside this window, determines drawing logic
Definition gfx_type.h:147
CursorVars::total_size
Point total_size
union of sprite properties
Definition gfx_type.h:137
CursorVars::dirty
bool dirty
the rect occupied by the mouse is dirty (redraw)
Definition gfx_type.h:146
CursorVars::draw_size
Point draw_size
position and size bounding-box for drawing
Definition gfx_type.h:139
CursorVars::delta
Point delta
relative mouse movement in this tick
Definition gfx_type.h:126
CursorVars::animate_list
std::span< const AnimCursor > animate_list
in case of animated cursor, list of frames
Definition gfx_type.h:141
Dimension
Dimensions (a width and height) of a rectangle in 2D.
Definition geometry_type.hpp:56
DrawPixelInfo
Data about how and where to blit pixels.
Definition gfx_type.h:157
GUISettings::fast_forward_speed_limit
uint16_t fast_forward_speed_limit
Game speed to use when fast-forward is enabled.
Definition settings_type.h:237
GUISettings::zoom_min
ZoomLevel zoom_min
minimum zoom out level
Definition settings_type.h:191
GUISettings::zoom_max
ZoomLevel zoom_max
maximum zoom out level
Definition settings_type.h:192
GameSessionStats
Definition openttd.h:55
NewGrfDebugSpritePicker::mode
NewGrfDebugSpritePickerMode mode
Current state.
Definition newgrf_debug.h:27
NewGrfDebugSpritePicker::clicked_pixel
void * clicked_pixel
Clicked pixel (pointer to blitter buffer)
Definition newgrf_debug.h:28
NewGrfDebugSpritePicker::sprites
FlatSet< SpriteID > sprites
Sprites found.
Definition newgrf_debug.h:29
Palette::palette
Colour palette[256]
Current palette. Entry 0 has to be always fully transparent!
Definition gfx_type.h:374
PixelColour
Colour for pixel/line drawing.
Definition gfx_type.h:405
PixelColour::p
uint8_t p
Palette index.
Definition gfx_type.h:406
Rect
Specification of a rectangle with absolute coordinates of all edges.
Definition geometry_type.hpp:101
Sprite
Data structure describing a sprite.
Definition spritecache_type.h:16
Sprite::width
uint16_t width
Width of the sprite.
Definition spritecache_type.h:18
Sprite::height
uint16_t height
Height of the sprite.
Definition spritecache_type.h:17
Sprite::y_offs
int16_t y_offs
Number of pixels to shift the sprite downwards.
Definition spritecache_type.h:20
Sprite::data
std::byte data[]
Sprite data.
Definition spritecache_type.h:21
Sprite::x_offs
int16_t x_offs
Number of pixels to shift the sprite to the right.
Definition spritecache_type.h:19
SubSprite
Used to only draw a part of the sprite.
Definition gfx_type.h:278
Window
Data structure for an opened window.
Definition window_gui.h:274
Window::Iterate
AllWindows< false > Iterate
Iterate all windows in whatever order is easiest.
Definition window_gui.h:933
video_driver.hpp
Base of all video drivers.
viewport_func.h
Functions related to (drawing on) viewports.
SetupWidgetDimensions
void SetupWidgetDimensions()
Set up pre-scaled versions of Widget Dimensions.
Definition widget.cpp:80
ScaleGUITrad
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
ReInitAllWindows
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3410
window_func.h
Window functions not directly related to making/drawing windows.
window_gui.h
Functions, definitions and such used only by the GUI.
zoom_func.h
Functions related to zooming.
ScaleByZoom
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
UnScaleByZoomLower
int UnScaleByZoomLower(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min)
Definition zoom_func.h:67
UnScaleGUI
int UnScaleGUI(int value)
Short-hand to apply GUI zoom level.
Definition zoom_func.h:77
UnScaleByZoom
int UnScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift right (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:34
ZoomLevel
ZoomLevel
All zoom levels we know.
Definition zoom_type.h:20
ZoomLevel::In2x
@ In2x
Zoomed 2 times in.
ZoomLevel::Min
@ Min
Minimum zoom level.
ZoomLevel::Normal
@ Normal
The normal zoom level.
ZoomLevel::In4x
@ In4x
Zoomed 4 times in.