Debian Codegraph @

CorsixTH/Src/th_gfx_sdl.cpp

raw
1 /*
2 Copyright (c) 2009-2013 Peter "Corsix" Cawley and Edvin "Lego3" Linge
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "th_gfx_sdl.h"
24
25 #include "config.h"
26
27 #include <SDL.h>
28 #include <png.h>
29 // IWYU pragma: no_include <pngconf.h>
30 #ifdef WITH_TRACY
31 #include <tracy/Tracy.hpp>
32 #endif
33
34 #include <algorithm>
35 #include <cmath>
36 #include <cstdio>
37 #include <cstring>
38 #include <iostream>
39 #include <limits>
40 #include <memory>
41 #include <new>
42 #include <stack>
43 #include <stdexcept>
44 #include <vector>
45
46 #include "persist_lua.h"
47 #include "th_gfx.h"
48 #include "th_gfx_common.h"
49 #include "th_gfx_font.h"
50
51 #if SDL_VERSION_ATLEAST(2, 0, 10)
52
53 //! How much to overdraw scaled sprites to ensure no gaps are visible.
54 const float frect_overdraw = 0.01f;
55
56 #define SDL_FRECT_UNIT float
57 #else
58 // On older SDL versions, floating point rendering was not available so we fall
59 // back to integer methods / types.
60 #define SDL_FRECT_UNIT int
61 #define SDL_FRect SDL_Rect
62 #define SDL_RenderCopyF SDL_RenderCopy
63 #define SDL_RenderCopyExF SDL_RenderCopyEx
64 #endif
65
66 full_colour_renderer::full_colour_renderer(int iWidth, int iHeight)
67 : width(iWidth), height(iHeight) {}
68
69 namespace {
70
71 constexpr double pi = 3.14159265358979323846;
72
73 //! The number of game ticks between jelly the jelly effect activating.
74 constexpr int jelly_effect_period = 540;
75
76 //! The number of game ticks the jelly effect is active for when it runs.
77 constexpr int jelly_effect_duration = 90;
78
79 //! Convert a colour to an equivalent grey scale level.
80 /*!
81 @param iOpacity Opacity of the pixel.
82 @param iR Red colour intensity.
83 @param iG Green colour intensity.
84 @param iB Blue colour intensity.
85 @return 32bpp colour pixel in grey scale.
86 */
87 inline uint32_t makeGreyScale(uint8_t iOpacity, uint8_t iR, uint8_t iG,
88 uint8_t iB) {
89 // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
90 // 0.2126*R + 0.7152*G + 0.0722*B
91 // 0.2126 * 65536 = 13932.9536 -> 1393
92 // 0.7152 * 65536 = 46871.3472
93 // 0.0722 * 65536 = 4731.6992 -> 4732
94 // 13933 + 46871 + 4732 = 65536 = 2**16
95 uint8_t iGrey =
96 static_cast<uint8_t>((13933 * iR + 46871 * iG + 4732 * iB) >> 16);
97 return palette::pack_argb(iOpacity, iGrey, iGrey, iGrey);
98 }
99
100 //! Convert a colour by swapping red and blue channel.
101 /*!
102 @param iOpacity Opacity of the pixel.
103 @param iR Red colour intensity.
104 @param iG Green colour intensity.
105 @param iB Blue colour intensity.
106 @return 32bpp colour pixel with red and blue swapped.
107 */
108 inline uint32_t makeSwapRedBlue(uint8_t iOpacity, uint8_t iR, uint8_t iG,
109 uint8_t iB) {
110 // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
111 // The Y factor for red is 0.2126, and for blue 0.0722. This means red is
112 // about 3 times stronger than blue. Simple swapping channels will thus
113 // distort the balance. This code compensates for that by computing red =
114 // blue * 0.0722 / 0.2126 = blue * 1083 / 3189 blue = red * 0.2126 / 0.0722
115 // = red * 1063 / 361 (clipped at max blue, 255)
116 uint8_t iNewRed = static_cast<uint8_t>(iB * 1083 / 3189);
117 int iNewBlue = iR * 1063 / 361;
118 if (iNewBlue > 255) iNewBlue = 255;
119 return palette::pack_argb(iOpacity, iNewRed, iG,
120 static_cast<uint8_t>(iNewBlue));
121 }
122
123 uint8_t convert_6bit_to_8bit_colour_component(uint8_t colour_component) {
124 constexpr uint8_t mask_6bit = 0x3F;
125 return static_cast<uint8_t>(std::lround(
126 (colour_component & mask_6bit) * static_cast<double>(0xFF) / mask_6bit));
127 }
128
129 //! Get the intersection of two SDL_Rects. The output rect can be a
130 // pointer to either of the two input rects.
131 /*!
132 @param a Pointer to first SDL_Rect to be intersected
133 @param b Pointer to second SDL_Rect to be intersected
134 @param[out] out The intersection of SDL_Rect |a| and |b|.
135 */
136 void intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect* out) {
137 // The intersection of the rectangles is the higher of the lower bounds and
138 // the lower of the higher bounds, clamped to a zero size.
139 clip_rect::x_y_type maxX = std::min(a.x + a.w, b.x + b.w);
140 clip_rect::x_y_type maxY = std::min(a.y + a.h, b.y + b.h);
141 out->x = std::max(a.x, b.x);
142 out->y = std::max(a.y, b.y);
143 out->w = maxX - out->x;
144 out->h = maxY - out->y;
145
146 // Make sure that we clamp the values to 0.
147 if (out->w <= 0 || out->h <= 0) {
148 out->w = 0;
149 out->h = 0;
150 }
151 }
152
153 //! Get the enclosing rect of an SDL_Rect scaled by the given scale factor.
154 // Scaling the rect is location dependent, as non-integer scale factors
155 // require that same size rects be +/-1 pixel different in size depending
156 // on location.
157 /*!
158 @param rect Pointer to the SDL_Rect to be scaled.
159 @param scale_factor Scale to be applied to the rectangle.
160 @param[out] dst_rect Enclosing SDL_Rect of rect scaled by scale_factor.
161 */
162 void getEnclosingScaleRect(const SDL_Rect* rect, double scale_factor,
163 SDL_Rect* dst_rect) {
164 // When scaling a rect, we use the scaled position of the bottom-right corner
165 // to determine the size depending on where on the screen the rect is. Compute
166 // width and height first so that we can support when rect == dst_rect.
167 int dst_x = static_cast<int>(scale_factor * rect->x);
168 int dst_y = static_cast<int>(scale_factor * rect->y);
169 dst_rect->w =
170 static_cast<int>(ceil(scale_factor * (rect->x + rect->w))) - dst_x;
171 dst_rect->h =
172 static_cast<int>(ceil(scale_factor * (rect->y + rect->h))) - dst_y;
173 dst_rect->x = dst_x;
174 dst_rect->y = dst_y;
175 }
176
177 //! Get the scaled rect of an SDL_Rect scaled by the given scale factor.
178 // On SDL < 2.0.10 this falls back to using getEnclosingScaleRect.
179 /*!
180 @param rect Pointer to the SDL_Rect to be scaled.
181 @param scale_factor Scale to be applied to the rectangle.
182 @param[out] dst_rect Enclosing SDL_FRect of rect scaled by scale_factor.
183 */
184 void getScaleRect(const SDL_Rect* rect, double scale_factor,
185 SDL_FRect* dst_rect) {
186 #if SDL_VERSION_ATLEAST(2, 0, 10)
187 // If using SDL 2.0.10 or newer, we can use floats to get better precision
188 // on scaled rendering.
189 dst_rect->x = static_cast<float>(rect->x * scale_factor) - frect_overdraw;
190 dst_rect->y = static_cast<float>(rect->y * scale_factor) - frect_overdraw;
191 dst_rect->w = static_cast<float>(rect->w * scale_factor) + 2 * frect_overdraw;
192 dst_rect->h = static_cast<float>(rect->h * scale_factor) + 2 * frect_overdraw;
193 #else
194 // Prior to SDL 2.0.10, fallback to using the enclosing integer SDL_Rect for
195 // scaled rendering.
196 getEnclosingScaleRect(rect, scale_factor, dst_rect);
197 #endif
198 }
199
200 class scoped_color_mod {
201 public:
202 scoped_color_mod(SDL_Texture* pTexture, int r, int g, int b)
203 : texture(pTexture) {
204 int err = SDL_SetTextureColorMod(texture, r, g, b);
205 if (err < 0) {
206 throw std::runtime_error(SDL_GetError());
207 }
208 }
209
210 ~scoped_color_mod() { SDL_SetTextureColorMod(texture, 0xFF, 0xFF, 0xFF); }
211
212 private:
213 SDL_Texture* texture;
214 };
215
216 } // namespace
217
218 palette::palette(const uint8_t* pData, size_t iDataLength, bool is8bit) {
219 int stride;
220 if (iDataLength == 256 * 3) {
221 stride = 3; // RGB
222 } else if (iDataLength == 256 * 4) {
223 stride = 4; // RGBA
224 } else {
225 throw std::runtime_error(
226 "Invalid palette data length. Must be 768 or 1024 bytes.");
227 }
228
229 for (int i = 0; i < color_count; ++i, pData += stride) {
230 uint8_t iR =
231 is8bit ? pData[0] : convert_6bit_to_8bit_colour_component(pData[0]);
232 uint8_t iG =
233 is8bit ? pData[1] : convert_6bit_to_8bit_colour_component(pData[1]);
234 uint8_t iB =
235 is8bit ? pData[2] : convert_6bit_to_8bit_colour_component(pData[2]);
236 uint8_t iA = stride == 4 ? pData[3] : 0xFF;
237 uint32_t iColour = pack_argb(iA, iR, iG, iB);
238 // Remap magenta to transparent
239 if (iColour == pack_argb(0xFF, 0xFF, 0x00, 0xFF))
240 iColour = pack_argb(0x00, 0x00, 0x00, 0x00);
241 colour_index_to_argb_map[i] = iColour;
242 }
243 }
244
245 bool palette::set_entry(int iEntry, uint8_t iR, uint8_t iG, uint8_t iB) {
246 if (iEntry < 0 || iEntry >= color_count) return false;
247 uint32_t iColour = pack_argb(0xFF, iR, iG, iB);
248 // Remap magenta to transparent
249 if (iColour == pack_argb(0xFF, 0xFF, 0x00, 0xFF))
250 iColour = pack_argb(0x00, 0x00, 0x00, 0x00);
251 colour_index_to_argb_map[iEntry] = iColour;
252 return true;
253 }
254
255 const std::array<argb_colour, palette::color_count>& palette::get_argb_data()
256 const {
257 return colour_index_to_argb_map;
258 }
259
260 void full_colour_renderer::decode_image(const uint8_t* pImg,
261 const palette* pPalette,
262 uint32_t iSpriteFlags) {
263 if (width <= 0) {
264 throw std::logic_error("width cannot be <= 0 when decoding an image");
265 }
266 if (height <= 0) {
267 throw std::logic_error("height cannot be <= 0 when decoding an image");
268 }
269
270 iSpriteFlags &= thdf_alt32_mask;
271
272 const auto& pColours = pPalette->get_argb_data();
273 for (;;) {
274 uint8_t iType = *pImg++;
275 size_t iLength = iType & 63;
276 switch (iType >> 6) {
277 case 0: // Fixed fully opaque 32bpp pixels
278 while (iLength > 0) {
279 uint32_t iColour;
280 if (iSpriteFlags == thdf_alt32_blue_red_swap)
281 iColour = makeSwapRedBlue(0xFF, pImg[0], pImg[1], pImg[2]);
282 else if (iSpriteFlags == thdf_alt32_grey_scale)
283 iColour = makeGreyScale(0xFF, pImg[0], pImg[1], pImg[2]);
284 else
285 iColour = palette::pack_argb(0xFF, pImg[0], pImg[1], pImg[2]);
286 push_pixel(iColour);
287 pImg += 3;
288 iLength--;
289 }
290 break;
291
292 case 1: // Fixed partially transparent 32bpp pixels
293 {
294 uint8_t iOpacity = *pImg++;
295 while (iLength > 0) {
296 uint32_t iColour;
297 if (iSpriteFlags == thdf_alt32_blue_red_swap)
298 iColour = makeSwapRedBlue(0xFF, pImg[0], pImg[1], pImg[2]);
299 else if (iSpriteFlags == thdf_alt32_grey_scale)
300 iColour = makeGreyScale(iOpacity, pImg[0], pImg[1], pImg[2]);
301 else
302 iColour = palette::pack_argb(iOpacity, pImg[0], pImg[1], pImg[2]);
303
304 push_pixel(iColour);
305 pImg += 3;
306 iLength--;
307 }
308 break;
309 }
310
311 case 2: // Fixed fully transparent pixels
312 {
313 static const uint32_t iTransparent = palette::pack_argb(0, 0, 0, 0);
314
315 while (iLength > 0) {
316 push_pixel(iTransparent);
317 iLength--;
318 }
319 break;
320 }
321
322 case 3: // Recolour layer
323 {
324 uint8_t iTable = *pImg++;
325 pImg++; // Skip reading the opacity for now.
326 if (iTable == 0xFF) {
327 // Legacy sprite data. Use the palette to recolour the
328 // layer. Note that the iOpacity is ignored here.
329 while (iLength > 0) {
330 push_pixel(pColours[*pImg++]);
331 iLength--;
332 }
333 } else {
334 // TODO: Add proper recolour layers, where RGB comes from
335 // table 'iTable' at index *pImg (iLength times), and
336 // opacity comes from the byte after the iTable byte.
337 //
338 // For now just draw black pixels, so it won't go unnoticed.
339 while (iLength > 0) {
340 uint32_t iColour = palette::pack_argb(0xFF, 0, 0, 0);
341 push_pixel(iColour);
342 iLength--;
343 }
344 }
345 break;
346 }
347 }
348
349 if (y >= height) break;
350 }
351 if (y != height || x != 0) {
352 throw std::logic_error("Image data does not match given dimensions");
353 }
354 }
355
356 full_colour_storing::full_colour_storing(uint32_t* pDest, int iWidth,
357 int iHeight)
358 : full_colour_renderer(iWidth, iHeight) {
359 destination = pDest;
360 }
361
362 void full_colour_storing::store_argb(uint32_t pixel) { *destination++ = pixel; }
363
364 wx_storing::wx_storing(uint8_t* pRGBData, uint8_t* pAData, int iWidth,
365 int iHeight)
366 : full_colour_renderer(iWidth, iHeight) {
367 rgb_data = pRGBData;
368 alpha_data = pAData;
369 }
370
371 void wx_storing::store_argb(uint32_t pixel) {
372 rgb_data[0] = palette::get_red(pixel);
373 rgb_data[1] = palette::get_green(pixel);
374 rgb_data[2] = palette::get_blue(pixel);
375 rgb_data += 3;
376
377 *alpha_data++ = palette::get_alpha(pixel);
378 }
379
380 render_target::scoped_target_texture::scoped_target_texture(
381 render_target* pTarget, int iX, int iY, int iWidth, int iHeight,
382 bool bScale)
383 : target(pTarget),
384 previous_target(target->current_target),
385 rect({iX, iY, iWidth, iHeight}),
386 scale(bScale) {
387 if (!target->supports_target_textures) return;
388
389 texture = SDL_CreateTexture(target->renderer, SDL_PIXELFORMAT_ABGR8888,
390 SDL_TEXTUREACCESS_TARGET, iWidth, iHeight);
391 if (SDL_SetRenderTarget(target->renderer, texture) != 0) {
392 SDL_DestroyTexture(texture);
393 texture = nullptr;
394 return;
395 }
396
397 // Clear the new texture to transparent/black.
398 SDL_RenderSetLogicalSize(target->renderer, rect.w, rect.h);
399 SDL_SetRenderDrawColor(target->renderer, 0, 0, 0, SDL_ALPHA_TRANSPARENT);
400 SDL_RenderClear(target->renderer);
401 target->current_target = this;
402 }
403
404 void render_target::scoped_target_texture::offset(SDL_FRect& targetRect) const {
405 targetRect.x -= static_cast<SDL_FRECT_UNIT>(rect.x);
406 targetRect.y -= static_cast<SDL_FRECT_UNIT>(rect.y);
407 }
408
409 double render_target::scoped_target_texture::scale_factor() const {
410 return scale ? target->global_scale_factor : 1.0;
411 }
412
413 bool render_target::scoped_target_texture::is_target() const { return texture; }
414
415 render_target::scoped_target_texture::~scoped_target_texture() {
416 if (!texture) return;
417
418 // Restore previous context.
419 SDL_SetRenderTarget(target->renderer,
420 previous_target ? previous_target->texture : nullptr);
421 SDL_RenderSetLogicalSize(
422 target->renderer,
423 previous_target ? previous_target->rect.w : target->width,
424 previous_target ? previous_target->rect.h : target->height);
425 SDL_SetTextureBlendMode(texture, SDL_BLENDMODE_BLEND);
426 target->current_target = previous_target;
427 if (scale) {
428 // If the target texture is already scaled, skip the global scale factor
429 // by drawing directly.
430 SDL_RenderCopy(target->renderer, texture, nullptr, &rect);
431 } else {
432 target->draw(texture, nullptr, &rect, 0);
433 }
434 target->intermediate_textures.push_back(texture);
435 }
436
437 render_target::render_target(const render_target_creation_params& params)
438 : width{params.width},
439 height{params.height},
440 direct_zoom{params.direct_zoom} {
441 SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
442 pixel_format = SDL_AllocFormat(SDL_PIXELFORMAT_ABGR8888);
443 window = SDL_CreateWindow("CorsixTH", SDL_WINDOWPOS_UNDEFINED,
444 SDL_WINDOWPOS_UNDEFINED, width, height,
445 SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
446 if (!window) {
447 throw std::runtime_error(SDL_GetError());
448 }
449
450 Uint32 iRendererFlags =
451 (params.present_immediate ? 0 : SDL_RENDERER_PRESENTVSYNC);
452 renderer = SDL_CreateRenderer(window, -1, iRendererFlags);
453
454 SDL_RendererInfo info;
455 SDL_GetRendererInfo(renderer, &info);
456 supports_target_textures = (info.flags & SDL_RENDERER_TARGETTEXTURE) != 0;
457
458 SDL_version sdlVersion;
459 SDL_GetVersion(&sdlVersion);
460 apply_opengl_clip_fix = std::strncmp(info.name, "opengl", 6) == 0 &&
461 sdlVersion.major == 2 && sdlVersion.minor == 0 &&
462 sdlVersion.patch < 4;
463 SDL_SetWindowMinimumSize(window, params.min_width, params.min_height);
464 SDL_RenderSetLogicalSize(renderer, width, height);
465
466 update(params);
467 }
468
469 render_target::~render_target() {
470 zoom_buffer.reset();
471 destroy_intermediate_textures();
472
473 if (pixel_format) {
474 SDL_FreeFormat(pixel_format);
475 pixel_format = nullptr;
476 }
477
478 if (renderer) {
479 SDL_DestroyRenderer(renderer);
480 renderer = nullptr;
481 }
482
483 if (window) {
484 SDL_DestroyWindow(window);
485 window = nullptr;
486 }
487 }
488
489 bool render_target::update(const render_target_creation_params& params) {
490 bool bUpdateSize = (width != params.width) || (height != params.height);
491 width = params.width;
492 height = params.height;
493
494 bool bIsFullscreen =
495 ((SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN_DESKTOP) ==
496 SDL_WINDOW_FULLSCREEN_DESKTOP);
497 if (bIsFullscreen != params.fullscreen) {
498 SDL_SetWindowFullscreen(
499 window, (params.fullscreen ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
500 }
501
502 if (bUpdateSize || bIsFullscreen != params.fullscreen) {
503 SDL_SetWindowSize(window, width, height);
504 }
505
506 if (bUpdateSize) {
507 SDL_RenderSetLogicalSize(renderer, width, height);
508 }
509
510 int old_min_width;
511 int old_min_height;
512 SDL_GetWindowMinimumSize(window, &old_min_width, &old_min_height);
513 if (old_min_width != params.min_width ||
514 old_min_height != params.min_height) {
515 SDL_SetWindowMinimumSize(window, params.min_width, params.min_height);
516 }
517
518 return true;
519 }
520
521 bool render_target::set_scale_factor(double fScale, scaled_items eWhatToScale) {
522 zoom_buffer.reset();
523 scale_bitmaps = false;
524
525 if (fScale <= 0.000) {
526 return false;
527 } else if (eWhatToScale == scaled_items::all && direct_zoom) {
528 global_scale_factor = fScale;
529 if ((SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN_DESKTOP) ==
530 SDL_WINDOW_FULLSCREEN_DESKTOP) {
531 // Drawing to an intermediate screen sized buffer when fullscreen results
532 // in noticeably better text rendering quality.
533 zoom_buffer =
534 std::make_unique<scoped_target_texture>(this, 0, 0, width, height,
535 /* bScale = */ true);
536 }
537 return true;
538 } else if (eWhatToScale == scaled_items::all && supports_target_textures) {
539 // Draw everything from now until the next scale to zoom_texture
540 // with the appropriate virtual size, which will be copied scaled to
541 // fit the window.
542 int virtWidth = static_cast<int>(width / fScale);
543 int virtHeight = static_cast<int>(height / fScale);
544
545 zoom_buffer = std::make_unique<scoped_target_texture>(
546 this, 0, 0, virtWidth, virtHeight, /* bScale = */ false);
547 if (!zoom_buffer->is_target()) {
548 global_scale_factor = 1.0;
549 std::cout << "Warning: Could not render to zoom texture - "
550 << SDL_GetError() << "\n";
551
552 return false;
553 }
554
555 // When zoom_buffer is allocated with bScale = false, this is only used for
556 // the scale to commit the zoom buffer back to the screen at.
557 global_scale_factor = fScale;
558 return true;
559 } else if (0.999 <= fScale && fScale <= 1.001) {
560 return true;
561 } else if (eWhatToScale == scaled_items::bitmaps) {
562 scale_bitmaps = true;
563 bitmap_scale_factor = fScale;
564
565 return true;
566 }
567 return false;
568 }
569
570 void render_target::set_caption(const char* sCaption) {
571 SDL_SetWindowTitle(window, sCaption);
572 }
573
574 const char* render_target::get_renderer_details() const {
575 SDL_RendererInfo info = {};
576 SDL_GetRendererInfo(renderer, &info);
577 return info.name;
578 }
579
580 const char* render_target::get_last_error() { return SDL_GetError(); }
581
582 bool render_target::start_frame() {
583 // Destroy any intermediate textures used last frame.
584 destroy_intermediate_textures();
585
586 fill_black();
587 return true;
588 }
589
590 bool render_target::end_frame() {
591 zoom_buffer.reset();
592
593 // End the frame by adding the cursor and possibly a filter.
594 if (game_cursor) {
595 game_cursor->draw(this, cursor_x, cursor_y);
596 }
597 if (blue_filter_active) {
598 SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
599 SDL_SetRenderDrawColor(renderer, 51, 51, 255,
600 128); // r=0.2, g=0.2, b=1, a=0.5 .
601 SDL_RenderFillRect(renderer, nullptr);
602 }
603
604 SDL_RenderPresent(renderer);
605 FrameMark;
606 return true;
607 }
608
609 bool render_target::fill_black() {
610 SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE);
611 SDL_RenderClear(renderer);
612
613 return true;
614 }
615
616 bool render_target::fill_colour(uint32_t colour) {
617 SDL_SetRenderDrawColor(renderer, palette::get_red(colour),
618 palette::get_green(colour), palette::get_blue(colour),
619 palette::get_alpha(colour));
620 SDL_RenderClear(renderer);
621
622 return true;
623 }
624
625 void render_target::set_blue_filter_active(bool bActivate) {
626 blue_filter_active = bActivate;
627 }
628
629 // Activate or Deactivate SDL function to capture mouse to window
630 void render_target::set_window_grab(bool bActivate) {
631 SDL_SetWindowGrab(window, bActivate ? SDL_TRUE : SDL_FALSE);
632 }
633
634 bool render_target::fill_rect(uint32_t iColour, int iX, int iY, int iW,
635 int iH) {
636 SDL_Rect rcDest = {iX, iY, iW, iH};
637 getEnclosingScaleRect(&rcDest, draw_scale(), &rcDest);
638
639 Uint8 r, g, b, a;
640 SDL_GetRGBA(iColour, pixel_format, &r, &g, &b, &a);
641
642 SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
643 SDL_SetRenderDrawColor(renderer, r, g, b, a);
644 SDL_RenderFillRect(renderer, &rcDest);
645
646 return true;
647 }
648
649 render_target::scoped_clip::scoped_clip(render_target* pTarget,
650 const clip_rect* pRect)
651 : target(pTarget) {
652 target->push_clip_rect(pRect);
653 }
654
655 render_target::scoped_clip::~scoped_clip() { target->pop_clip_rect(); }
656
657 void render_target::push_clip_rect(const clip_rect* pRect) {
658 const SDL_Rect* previous_clip = nullptr;
659 if (!clip_rects.empty()) {
660 previous_clip = &clip_rects.top();
661 }
662 clip_rects.push(SDL_Rect());
663 SDL_Rect& clip = clip_rects.top();
664 getEnclosingScaleRect(pRect, draw_scale(), &clip);
665 if (previous_clip) {
666 // Ensure that this new clip does not escape any previous clips applied.
667 intersectRect(clip, *previous_clip, &clip);
668 }
669
670 // For some reason, SDL treats an empty rect (h or w <= 0) as if you turned
671 // off clipping, so we replace it with a rect that's outside our viewport.
672 const SDL_Rect rcBogus = {-2, -2, 1, 1};
673 if (SDL_RectEmpty(&clip)) {
674 clip = rcBogus;
675 }
676
677 if (apply_opengl_clip_fix) {
678 int renderWidth, renderHeight;
679 SDL_RenderGetLogicalSize(renderer, &renderWidth, &renderHeight);
680 clip.y = renderHeight - clip.y - clip.h;
681 }
682
683 SDL_RenderSetClipRect(renderer, &clip);
684 }
685
686 void render_target::pop_clip_rect() {
687 clip_rects.pop();
688 if (clip_rects.empty()) {
689 SDL_RenderSetClipRect(renderer, nullptr);
690 } else {
691 SDL_RenderSetClipRect(renderer, &clip_rects.top());
692 }
693 }
694
695 int render_target::get_width() const {
696 int w;
697 SDL_RenderGetLogicalSize(renderer, &w, nullptr);
698 return static_cast<int>(std::ceil(w / draw_scale()));
699 }
700
701 int render_target::get_height() const {
702 int h;
703 SDL_RenderGetLogicalSize(renderer, nullptr, &h);
704 return static_cast<int>(std::ceil(h / draw_scale()));
705 }
706
707 void render_target::start_nonoverlapping_draws() {
708 // SDL has no optimisations for drawing lots of non-overlapping sprites
709 }
710
711 void render_target::finish_nonoverlapping_draws() {
712 // SDL has no optimisations for drawing lots of non-overlapping sprites
713 }
714
715 void render_target::set_cursor(cursor* pCursor) { game_cursor = pCursor; }
716
717 void render_target::set_cursor_position(int iX, int iY) {
718 cursor_x = iX;
719 cursor_y = iY;
720 }
721
722 namespace {
723
724 //! Error function called when PNG writing fails.
725 void png_error(png_structp png_data, const char* message) { throw(0); }
726
727 //! Class for managing lifetime of the data structures for saving a PNG file.
728 class png_data_manager {
729 public:
730 png_structp png_write_data{nullptr};
731 png_infop info_write_data{nullptr};
732 png_bytepp row_pointers{nullptr};
733 FILE* fp{nullptr};
734
735 ~png_data_manager() {
736 if (png_write_data != nullptr || info_write_data != nullptr) {
737 png_destroy_write_struct(&png_write_data, &info_write_data);
738 }
739 if (row_pointers != nullptr) {
740 delete[] row_pointers;
741 }
742 if (fp != nullptr) {
743 std::fclose(fp);
744 }
745 }
746 };
747
748 //! Function to write the pixels to the given file as PNG image.
749 bool write_rgb_png(int width, int height, png_bytep pixels, int pitch,
750 const char* file_path) {
751 png_data_manager png_storage;
752
753 // Create PNG writer and info data structures.
754 png_storage.png_write_data = png_create_write_struct(
755 PNG_LIBPNG_VER_STRING, (png_voidp)png_error, nullptr, nullptr);
756 if (png_storage.png_write_data == nullptr) {
757 return false;
758 }
759 png_storage.info_write_data =
760 png_create_info_struct(png_storage.png_write_data);
761 if (png_storage.info_write_data == nullptr) {
762 return false;
763 }
764
765 // Allocate and setup row pointers to the pixels.
766 png_storage.row_pointers = new (std::nothrow) png_bytep[height];
767 if (png_storage.row_pointers == nullptr) {
768 return false;
769 }
770 {
771 png_bytep rp = pixels;
772 for (int h = 0; h < height; h++) {
773 png_storage.row_pointers[h] = rp;
774 rp += pitch;
775 }
776 }
777
778 // Open the file for writing.
779 png_storage.fp = std::fopen(file_path, "wb");
780 if (png_storage.fp == nullptr) {
781 return false;
782 }
783
784 // Configure what to write.
785 png_init_io(png_storage.png_write_data, png_storage.fp);
786 png_set_IHDR(png_storage.png_write_data, png_storage.info_write_data, width,
787 height, 8, PNG_COLOR_TYPE_RGB, PNG_INTERLACE_NONE,
788 PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
789 png_set_rows(png_storage.png_write_data, png_storage.info_write_data,
790 png_storage.row_pointers);
791
792 // Write the image while swapping red and blue channels.
793 png_write_png(png_storage.png_write_data, png_storage.info_write_data,
794 PNG_TRANSFORM_BGR, nullptr);
795 return true;
796 }
797
798 } // namespace
799
800 bool render_target::take_screenshot(const char* file_path) const {
801 int width = 0, height = 0;
802 if (SDL_GetRendererOutputSize(renderer, &width, &height) == -1) return false;
803
804 // Create a window-sized surface, RGB format (0 Rmask means RGB.)
805 SDL_Surface* pRgbSurface =
806 SDL_CreateRGBSurface(0, width, height, 24, 0, 0, 0, 0);
807 if (pRgbSurface == nullptr) return false;
808
809 bool ok = false;
810
811 int readStatus = -1;
812 if (SDL_LockSurface(pRgbSurface) != -1) {
813 // Ask the renderer to (slowly) fill the surface with renderer
814 // output data.
815 readStatus =
816 SDL_RenderReadPixels(renderer, nullptr, pRgbSurface->format->format,
817 pRgbSurface->pixels, pRgbSurface->pitch);
818 SDL_UnlockSurface(pRgbSurface);
819
820 if (readStatus != -1) {
821 try {
822 write_rgb_png(width, height,
823 static_cast<png_bytep>(pRgbSurface->pixels),
824 pRgbSurface->pitch, file_path);
825 ok = true;
826 } catch (int) {
827 ok = false; // Not needed, but clang-tidy wants it.
828 }
829 }
830 }
831
832 SDL_FreeSurface(pRgbSurface);
833
834 return ok;
835 }
836
837 bool render_target::should_scale_bitmaps(double* pFactor) {
838 if (!scale_bitmaps) return false;
839 if (pFactor) *pFactor = bitmap_scale_factor;
840 return true;
841 }
842
843 namespace {
844
845 //! Convert legacy 8bpp sprite data to recoloured 32bpp data, using special
846 //! recolour table 0xFF.
847 /*!
848 @param pPixelData Legacy 8bpp pixels.
849 @param iPixelDataLength Number of pixels in the \a pPixelData.
850 @return Converted 32bpp pixel data, if succeeded else nullptr is returned.
851 Caller should free the returned memory.
852 */
853 uint8_t* convertLegacySprite(const uint8_t* pPixelData,
854 size_t iPixelDataLength) {
855 // Recolour blocks are 63 pixels long.
856 // XXX To reduce the size of the 32bpp data, transparent pixels can be
857 // stored more compactly.
858 size_t iNumFilled = iPixelDataLength / 63;
859 size_t iRemaining = iPixelDataLength - iNumFilled * 63;
860 size_t iNewSize =
861 iNumFilled * (3 + 63) + ((iRemaining > 0) ? 3 + iRemaining : 0);
862 uint8_t* pData = new uint8_t[iNewSize];
863
864 uint8_t* pDest = pData;
865 while (iPixelDataLength > 0) {
866 size_t iLength = (iPixelDataLength >= 63) ? 63 : iPixelDataLength;
867 *pDest++ =
868 static_cast<uint8_t>(iLength + 0xC0); // Recolour layer type of block.
869 *pDest++ = 0xFF; // Use special table 0xFF (which uses the palette as
870 // table).
871 *pDest++ = 0xFF; // Non-transparent.
872 std::memcpy(pDest, pPixelData, iLength);
873 pDest += iLength;
874 pPixelData += iLength;
875 iPixelDataLength -= iLength;
876 }
877 return pData;
878 }
879
880 } // namespace
881
882 SDL_Texture* render_target::create_palettized_texture(
883 int iWidth, int iHeight, const uint8_t* pPixels, const palette* pPalette,
884 uint32_t iSpriteFlags) const {
885 uint32_t* pARGBPixels = new uint32_t[iWidth * iHeight];
886
887 full_colour_storing oRenderer(pARGBPixels, iWidth, iHeight);
888 oRenderer.decode_image(pPixels, pPalette, iSpriteFlags);
889
890 if (iSpriteFlags & thdf_nearest)
891 SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "nearest");
892 SDL_Texture* pTexture = create_texture(iWidth, iHeight, pARGBPixels);
893 if (iSpriteFlags & thdf_nearest)
894 SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
895 delete[] pARGBPixels;
896 return pTexture;
897 }
898
899 SDL_Texture* render_target::create_texture(int iWidth, int iHeight,
900 const uint32_t* pPixels) const {
901 SDL_Texture* pTexture =
902 SDL_CreateTexture(renderer, pixel_format->format,
903 SDL_TEXTUREACCESS_STATIC, iWidth, iHeight);
904
905 if (pTexture == nullptr) {
906 throw std::runtime_error(SDL_GetError());
907 }
908
909 int err = 0;
910 err = SDL_UpdateTexture(pTexture, nullptr, pPixels,
911 static_cast<int>(sizeof(*pPixels) * iWidth));
912 if (err < 0) {
913 throw std::runtime_error(SDL_GetError());
914 }
915
916 err = SDL_SetTextureBlendMode(pTexture, SDL_BLENDMODE_BLEND);
917 if (err < 0) {
918 throw std::runtime_error(SDL_GetError());
919 }
920
921 err = SDL_SetTextureColorMod(pTexture, 0xFF, 0xFF, 0xFF);
922 if (err < 0) {
923 throw std::runtime_error(SDL_GetError());
924 }
925
926 err = SDL_SetTextureAlphaMod(pTexture, 0xFF);
927 if (err < 0) {
928 throw std::runtime_error(SDL_GetError());
929 }
930
931 return pTexture;
932 }
933
934 void render_target::draw(SDL_Texture* pTexture, const SDL_Rect* prcSrcRect,
935 const SDL_Rect* prcDstRect, int iFlags) {
936 SDL_SetTextureAlphaMod(pTexture, 0xFF);
937 if (iFlags & thdf_alpha_50) {
938 SDL_SetTextureAlphaMod(pTexture, 0x80);
939 } else if (iFlags & thdf_alpha_75) {
940 SDL_SetTextureAlphaMod(pTexture, 0x40);
941 }
942
943 int iSDLFlip = SDL_FLIP_NONE;
944 if (iFlags & thdf_flip_horizontal) iSDLFlip |= SDL_FLIP_HORIZONTAL;
945 if (iFlags & thdf_flip_vertical) iSDLFlip |= SDL_FLIP_VERTICAL;
946
947 SDL_FRect scaledDstRect;
948 getScaleRect(prcDstRect, draw_scale(), &scaledDstRect);
949 if (current_target) current_target->offset(scaledDstRect);
950 if (iSDLFlip != 0) {
951 // iSDLFlip may be 3 (HORIZONTAL | VERTICAL) but there is no enum value for
952 // that
953 SDL_RenderCopyExF(renderer, pTexture, prcSrcRect, &scaledDstRect, 0,
954 nullptr,
955 (SDL_RendererFlip)iSDLFlip); // NOLINT
956 } else {
957 SDL_RenderCopyF(renderer, pTexture, prcSrcRect, &scaledDstRect);
958 }
959 }
960
961 void render_target::draw_line(line_sequence* pLine, int iX, int iY) {
962 SDL_SetRenderDrawColor(renderer, pLine->red, pLine->green, pLine->blue,
963 pLine->alpha);
964
965 double scale = draw_scale();
966 double lastX = pLine->line_elements[0].x;
967 double lastY = pLine->line_elements[0].y;
968 for (const line_sequence::line_element& op : pLine->line_elements) {
969 if (op.type == line_sequence::line_command::line) {
970 // Not the true width, but good enough for graphs
971 for (int i = 0; i < pLine->width; ++i) {
972 int adjI = static_cast<int>(i - pLine->width / 2);
973 SDL_RenderDrawLine(renderer, static_cast<int>((lastX + iX) * scale),
974 static_cast<int>((lastY + iY + adjI) * scale),
975 static_cast<int>((op.x + iX) * scale),
976 static_cast<int>((op.y + iY + adjI) * scale));
977 }
978 }
979
980 lastX = op.x;
981 lastY = op.y;
982 }
983 }
984
985 std::unique_ptr<render_target::scoped_buffer>
986 render_target::begin_intermediate_drawing(int iX, int iY, int iWidth,
987 int iHeight) {
988 // We only need an intermediate drawing if there is active scaling.
989 if (draw_scale() == 1.0) return nullptr;
990
991 return std::make_unique<scoped_target_texture>(this, iX, iY, iWidth, iHeight,
992 /* bScale = */ false);
993 }
994
995 double render_target::draw_scale() const {
996 if (current_target) return current_target->scale_factor();
997 return global_scale_factor;
998 }
999
1000 void render_target::destroy_intermediate_textures() {
1001 for (SDL_Texture* texture : intermediate_textures) {
1002 SDL_DestroyTexture(texture);
1003 }
1004 intermediate_textures.clear();
1005 }
1006
1007 raw_bitmap::~raw_bitmap() {
1008 if (texture) {
1009 SDL_DestroyTexture(texture);
1010 }
1011 }
1012
1013 void raw_bitmap::set_palette(const palette* pPalette) {
1014 bitmap_palette = pPalette;
1015 }
1016
1017 void raw_bitmap::load_from_th_file(const uint8_t* pPixelData,
1018 size_t iPixelDataLength, int iWidth,
1019 render_target* pEventualCanvas,
1020 uint32_t spriteFlags) {
1021 if (pEventualCanvas == nullptr) {
1022 throw std::invalid_argument("pEventualCanvas cannot be null");
1023 }
1024
1025 uint8_t* converted_sprite = convertLegacySprite(pPixelData, iPixelDataLength);
1026
1027 int iHeight = static_cast<int>(iPixelDataLength) / iWidth;
1028 texture = pEventualCanvas->create_palettized_texture(
1029 iWidth, iHeight, converted_sprite, bitmap_palette,
1030 thdf_alt32_plain | spriteFlags);
1031 delete[] converted_sprite;
1032
1033 width = iWidth;
1034 height = iHeight;
1035 target = pEventualCanvas;
1036 }
1037
1038 namespace {
1039
1040 /**
1041 * Test whether the loaded full colour sprite loads correctly.
1042 * @param pData Data of the sprite.
1043 * @param iDataLength Length of the sprite data.
1044 * @param iWidth Width of the sprite.
1045 * @param iHeight Height of the sprite.
1046 * @return Whether the sprite loads correctly (at the end of the sprite, all
1047 * data is used).
1048 */
1049 bool testSprite(const uint8_t* pData, size_t iDataLength, int iWidth,
1050 int iHeight) {
1051 if (iWidth <= 0 || iHeight <= 0) return true;
1052
1053 size_t iCount = iWidth * iHeight;
1054 while (iCount > 0) {
1055 if (iDataLength < 1) return false;
1056 iDataLength--;
1057 uint8_t iType = *pData++;
1058
1059 size_t iLength = iType & 63;
1060 switch (iType >> 6) {
1061 case 0: // Fixed fully opaque 32bpp pixels
1062 if (iCount < iLength || iDataLength < iLength * 3) return false;
1063 iCount -= iLength;
1064 iDataLength -= iLength * 3;
1065 pData += iLength * 3;
1066 break;
1067
1068 case 1: // Fixed partially transparent 32bpp pixels
1069 if (iDataLength < 1) return false;
1070 iDataLength--;
1071 pData++; // Opacity byte.
1072
1073 if (iCount < iLength || iDataLength < iLength * 3) return false;
1074 iCount -= iLength;
1075 iDataLength -= iLength * 3;
1076 pData += iLength * 3;
1077 break;
1078
1079 case 2: // Fixed fully transparent pixels
1080 if (iCount < iLength) return false;
1081 iCount -= iLength;
1082 break;
1083
1084 case 3: // Recolour layer
1085 if (iDataLength < 2) return false;
1086 iDataLength -= 2;
1087 pData += 2; // Table number, opacity byte.
1088
1089 if (iCount < iLength || iDataLength < iLength) return false;
1090 iCount -= iLength;
1091 iDataLength -= iLength;
1092 pData += iLength;
1093 break;
1094 }
1095 }
1096 return iDataLength == 0;
1097 }
1098
1099 } // namespace
1100
1101 void raw_bitmap::draw(render_target* pCanvas, int iX, int iY) {
1102 draw(pCanvas, iX, iY, 0, 0, width, height);
1103 }
1104
1105 void raw_bitmap::draw(render_target* pCanvas, int iX, int iY, int iSrcX,
1106 int iSrcY, int iWidth, int iHeight) {
1107 double fScaleFactor;
1108 if (texture == nullptr) return;
1109
1110 if (!pCanvas->should_scale_bitmaps(&fScaleFactor)) {
1111 fScaleFactor = 1;
1112 }
1113
1114 const SDL_Rect rcSrc = {iSrcX, iSrcY, iWidth, iHeight};
1115 const SDL_Rect rcDest = {iX, iY, static_cast<int>(iWidth * fScaleFactor),
1116 static_cast<int>(iHeight * fScaleFactor)};
1117
1118 pCanvas->draw(texture, &rcSrc, &rcDest, 0);
1119 }
1120
1121 sprite_sheet::~sprite_sheet() { _freeSprites(); }
1122
1123 void sprite_sheet::_freeSingleSprite(size_t iNumber) {
1124 if (iNumber >= sprite_count) return;
1125
1126 if (sprites[iNumber].texture != nullptr) {
1127 SDL_DestroyTexture(sprites[iNumber].texture);
1128 sprites[iNumber].texture = nullptr;
1129 }
1130 if (sprites[iNumber].alt_texture != nullptr) {
1131 SDL_DestroyTexture(sprites[iNumber].alt_texture);
1132 sprites[iNumber].alt_texture = nullptr;
1133 }
1134 if (sprites[iNumber].data != nullptr) {
1135 delete[] sprites[iNumber].data;
1136 sprites[iNumber].data = nullptr;
1137 }
1138 }
1139
1140 void sprite_sheet::_freeSprites() {
1141 for (size_t i = 0; i < sprite_count; ++i) _freeSingleSprite(i);
1142
1143 delete[] sprites;
1144 sprites = nullptr;
1145 sprite_count = 0;
1146 }
1147
1148 void sprite_sheet::set_palette(const ::palette* pPalette) {
1149 palette = pPalette;
1150 }
1151
1152 bool sprite_sheet::set_sprite_count(size_t iCount, render_target* pCanvas) {
1153 _freeSprites();
1154
1155 if (pCanvas == nullptr) return false;
1156 target = pCanvas;
1157
1158 sprite_count = iCount;
1159 sprites = new (std::nothrow) sprite[sprite_count];
1160 if (sprites == nullptr) {
1161 sprite_count = 0;
1162 return false;
1163 }
1164
1165 for (size_t i = 0; i < sprite_count; i++) {
1166 sprite& spr = sprites[i];
1167 spr.texture = nullptr;
1168 spr.alt_texture = nullptr;
1169 spr.data = nullptr;
1170 spr.alt_palette_map = nullptr;
1171 spr.sprite_flags = thdf_alt32_plain;
1172 spr.width = 0;
1173 spr.height = 0;
1174 }
1175
1176 return true;
1177 }
1178
1179 //! Sprite structure in the table file.
1180 /*!
1181 https://github.com/CorsixTH/theme-hospital-spec/blob/master/format-specification.md#spritetable
1182 */
1183 struct th_sprite_properties {
1184 static constexpr size_t size = 6;
1185
1186 explicit th_sprite_properties(const uint8_t* pData)
1187 : position{bytes_to_uint32_le(pData)},
1188 width{pData[4]},
1189 height{pData[5]} {}
1190
1191 //! Position of the sprite in the chunk data file.
1192 uint32_t position;
1193
1194 //! Width of the sprite.
1195 uint8_t width;
1196
1197 //! Height of the sprite.
1198 uint8_t height;
1199 };
1200
1201 bool sprite_sheet::load_from_th_file(const uint8_t* pTableData,
1202 size_t iTableDataLength,
1203 const uint8_t* pChunkData,
1204 size_t iChunkDataLength,
1205 bool bComplexChunks,
1206 render_target* pCanvas) {
1207 _freeSprites();
1208 if (pCanvas == nullptr) return false;
1209
1210 size_t iCount = iTableDataLength / th_sprite_properties::size;
1211 if (!set_sprite_count(iCount, pCanvas)) return false;
1212
1213 for (size_t i = 0; i < sprite_count; ++i) {
1214 sprite* pSprite = sprites + i;
1215 const th_sprite_properties thSprite(pTableData +
1216 i * th_sprite_properties::size);
1217
1218 pSprite->texture = nullptr;
1219 pSprite->alt_texture = nullptr;
1220 pSprite->data = nullptr;
1221 pSprite->alt_palette_map = nullptr;
1222 pSprite->width = thSprite.width;
1223 pSprite->height = thSprite.height;
1224
1225 if (pSprite->width == 0 || pSprite->height == 0) continue;
1226
1227 {
1228 std::vector<uint8_t> pData(pSprite->width * pSprite->height);
1229 chunk_renderer oRenderer(pSprite->width, pSprite->height, pData.begin());
1230 int iDataLen = static_cast<int>(iChunkDataLength) -
1231 static_cast<int>(thSprite.position);
1232 if (iDataLen < 0) iDataLen = 0;
1233 oRenderer.decode_chunks(pChunkData + thSprite.position, iDataLen,
1234 bComplexChunks);
1235 pSprite->data =
1236 convertLegacySprite(pData.data(), pSprite->width * pSprite->height);
1237 }
1238 }
1239 return true;
1240 }
1241
1242 bool sprite_sheet::set_sprite_data(size_t iSprite, const uint8_t* pData,
1243 bool bTakeData, size_t iDataLength,
1244 int iWidth, int iHeight) {
1245 if (iSprite >= sprite_count) return false;
1246
1247 if (!testSprite(pData, iDataLength, iWidth, iHeight)) {
1248 std::printf("Sprite number %zu has a bad encoding, skipping", iSprite);
1249 return false;
1250 }
1251
1252 _freeSingleSprite(iSprite);
1253 sprite* pSprite = sprites + iSprite;
1254 if (bTakeData) {
1255 pSprite->data = pData;
1256 } else {
1257 uint8_t* pNewData = new (std::nothrow) uint8_t[iDataLength];
1258 if (pNewData == nullptr) return false;
1259
1260 std::memcpy(pNewData, pData, iDataLength);
1261 pSprite->data = pNewData;
1262 }
1263
1264 pSprite->width = iWidth;
1265 pSprite->height = iHeight;
1266 return true;
1267 }
1268
1269 void sprite_sheet::set_sprite_alt_palette_map(size_t iSprite,
1270 const uint8_t* pMap,
1271 uint32_t iAlt32) {
1272 if (iSprite >= sprite_count) return;
1273
1274 sprite* pSprite = sprites + iSprite;
1275 if (pSprite->alt_palette_map != pMap) {
1276 pSprite->alt_palette_map = pMap;
1277 pSprite->sprite_flags = iAlt32;
1278 if (pSprite->alt_texture) {
1279 SDL_DestroyTexture(pSprite->alt_texture);
1280 pSprite->alt_texture = nullptr;
1281 }
1282 }
1283 }
1284
1285 size_t sprite_sheet::get_sprite_count() const { return sprite_count; }
1286
1287 bool sprite_sheet::get_sprite_size(size_t iSprite, int* pWidth,
1288 int* pHeight) const {
1289 if (iSprite >= sprite_count) return false;
1290 if (pWidth != nullptr) *pWidth = sprites[iSprite].width;
1291 if (pHeight != nullptr) *pHeight = sprites[iSprite].height;
1292 return true;
1293 }
1294
1295 void sprite_sheet::get_sprite_size_unchecked(size_t iSprite, int* pWidth,
1296 int* pHeight) const {
1297 *pWidth = sprites[iSprite].width;
1298 *pHeight = sprites[iSprite].height;
1299 }
1300
1301 bool sprite_sheet::get_sprite_average_colour(size_t iSprite,
1302 argb_colour* pColour) const {
1303 if (iSprite >= sprite_count) return false;
1304 const sprite* pSprite = sprites + iSprite;
1305 int iCountTotal = 0;
1306 int iUsageCounts[256] = {0};
1307 for (long i = 0; i < pSprite->width * pSprite->height; ++i) {
1308 uint8_t cPalIndex = pSprite->data[i];
1309 uint32_t iColour = palette->get_argb_data()[cPalIndex];
1310 if ((iColour >> 24) == 0) continue;
1311
1312 // - Convert from nonlinear RGB to linear RGB.
1313 // gamma = around 2.2 but depends on the screen.
1314 // R, G and B are fractions.
1315 const double gamma = 2.2;
1316 double linR = std::pow(palette::get_red(iColour) / 255.0, gamma);
1317 double linG = std::pow(palette::get_green(iColour) / 255.0, gamma);
1318 double linB = std::pow(palette::get_blue(iColour) / 255.0, gamma);
1319 // - Compute luminance Y in XYZ space.
1320 // Y = .2126 * R^gamma + .7152 * G^gamma + .0722 * B^gamma
1321 double Y = 0.2126 * linR + 0.7152 * linG + 0.0722 * linB;
1322 // - Compute lightness L*.
1323 // L* = 116 * Y ^ 1/3 - 16, range is from 0 to 100.
1324 double L = std::min(100.0, std::max(0.0, 116 * std::cbrt(Y) - 16));
1325 uint8_t cIntensity = static_cast<uint8_t>(L / 100 * 255.0);
1326
1327 // Grant higher score to pixels with high or low intensity (helps avoid
1328 // grey fonts)
1329 int iScore = 1 + std::max(0, 3 - ((255 - cIntensity) / 32)) +
1330 std::max(0, 3 - (cIntensity / 32));
1331 iUsageCounts[cPalIndex] += iScore;
1332 iCountTotal += iScore;
1333 }
1334 if (iCountTotal == 0) return false;
1335 int iHighestCountIndex = 0;
1336 for (int i = 0; i < 256; ++i) {
1337 if (iUsageCounts[i] > iUsageCounts[iHighestCountIndex])
1338 iHighestCountIndex = i;
1339 }
1340 *pColour = palette->get_argb_data()[iHighestCountIndex];
1341 return true;
1342 }
1343
1344 bool sprite_sheet::is_sprite_visible(size_t iSprite) const {
1345 if (iSprite >= sprite_count) return false;
1346
1347 const sprite* pSprite = sprites + iSprite;
1348 for (long i = 0; i < pSprite->width * pSprite->height; ++i) {
1349 uint8_t cPalIndex = pSprite->data[i];
1350 uint32_t iColour = palette->get_argb_data()[cPalIndex];
1351 if ((iColour >> 24) != 0) return true;
1352 }
1353 return false;
1354 }
1355
1356 void sprite_sheet::draw_sprite(render_target* pCanvas, size_t iSprite, int iX,
1357 int iY, uint32_t iFlags, size_t effect_ticks,
1358 animation_effect effect, int scale_factor) {
1359 if (iSprite >= sprite_count || pCanvas == nullptr || pCanvas != target)
1360 return;
1361 sprite& sprite = sprites[iSprite];
1362
1363 // Find or create the texture
1364 SDL_Texture* pTexture = sprite.texture;
1365 if (!pTexture) {
1366 if (sprite.data == nullptr) return;
1367
1368 uint32_t iSprFlags = (sprite.sprite_flags & ~thdf_alt32_mask) |
1369 thdf_alt32_plain | (iFlags & thdf_nearest);
1370 pTexture = target->create_palettized_texture(
1371 sprite.width, sprite.height, sprite.data, palette, iSprFlags);
1372 sprite.texture = pTexture;
1373 }
1374 if (iFlags & thdf_alt_palette) {
1375 pTexture = sprite.alt_texture;
1376 if (!pTexture) {
1377 pTexture = _makeAltBitmap(&sprite);
1378 if (!pTexture) return;
1379 }
1380 }
1381
1382 std::unique_ptr<scoped_color_mod> color_mod;
1383 if (effect == animation_effect::glowing) {
1384 // We want this to vary between 155 -> 205 -> 255.
1385 // Use the target cycle length (15 cycles) to calculate the angle from 0 to
1386 // 2*pi.
1387 int currentVariation = static_cast<int>(
1388 sin(static_cast<double>(effect_ticks % 15) / 15.0 * 2 * pi) * 50);
1389 color_mod = std::make_unique<scoped_color_mod>(pTexture, 0,
1390 205 + currentVariation, 0);
1391 }
1392
1393 if (effect == animation_effect::jelly &&
1394 effect_ticks % jelly_effect_period < jelly_effect_duration) {
1395 int jelly_tick = static_cast<int>(effect_ticks % jelly_effect_period);
1396 // Draw the sprite a few lines at a time following a sine wave x offset.
1397 // To cut down on the number of draw calls, we will draw all of the lines
1398 // that have the same x offset in a single draw call. This results in about
1399 // a third of the draw calls as drawing each line individually.
1400 // TODO: We could move this effect into render_target which is aware of the
1401 // screen scale and could optimize this further when zooming out.
1402 int y1 = 0;
1403 int x_offset = 0;
1404 // Scale the effect up as it ramps in and down as it finishes.
1405 int scale =
1406 std::min(jelly_tick, std::min(jelly_effect_duration - jelly_tick, 2));
1407 for (int y2 = 0; y2 <= sprite.height; y2++) {
1408 // TODO: Ideally this should use the offset of the current line from
1409 // the map location so that multiple layers have the same jelly offset
1410 // at the same vertical line. We can't just use iY because it varies as
1411 // the user scrolls or zooms or the character walks.
1412 int offset = static_cast<int>(
1413 sin((y2 / 16.0 + static_cast<double>(effect_ticks % 50) / 50) * 2 *
1414 pi) *
1415 scale);
1416 if (x_offset != offset || y2 == sprite.height) {
1417 if (y2 > y1) {
1418 // If the current offset rounds to a different value, render the
1419 // previous offset and start a new offset.
1420 SDL_Rect rcSrc = {0, y1, sprite.width, y2 - y1};
1421 SDL_Rect rcDest = {iX + x_offset, iY + y1,
1422 sprite.width * scale_factor,
1423 (y2 - y1) * scale_factor};
1424 pCanvas->draw(pTexture, &rcSrc, &rcDest, iFlags);
1425 }
1426 y1 = y2;
1427 x_offset = offset;
1428 }
1429 }
1430 } else {
1431 SDL_Rect rcSrc = {0, 0, sprite.width, sprite.height};
1432 SDL_Rect rcDest = {iX, iY, sprite.width * scale_factor,
1433 sprite.height * scale_factor};
1434
1435 pCanvas->draw(pTexture, &rcSrc, &rcDest, iFlags);
1436 }
1437 }
1438
1439 void sprite_sheet::wx_draw_sprite(size_t iSprite, uint8_t* pRGBData,
1440 uint8_t* pAData) {
1441 if (iSprite >= sprite_count || pRGBData == nullptr || pAData == nullptr)
1442 return;
1443 sprite* pSprite = sprites + iSprite;
1444
1445 wx_storing oRenderer(pRGBData, pAData, pSprite->width, pSprite->height);
1446 oRenderer.decode_image(pSprite->data, palette, pSprite->sprite_flags);
1447 }
1448
1449 SDL_Texture* sprite_sheet::_makeAltBitmap(sprite* pSprite) {
1450 const auto& argb_data = palette->get_argb_data();
1451
1452 if (!pSprite->alt_palette_map) {
1453 // Use normal palette
1454 uint32_t iSprFlags =
1455 (pSprite->sprite_flags & ~thdf_alt32_mask) | thdf_alt32_plain;
1456 pSprite->alt_texture = target->create_palettized_texture(
1457 pSprite->width, pSprite->height, pSprite->data, palette, iSprFlags);
1458 } else if (!palette) {
1459 // Draw 32bpp image without palette
1460 pSprite->alt_texture = target->create_palettized_texture(
1461 pSprite->width, pSprite->height, pSprite->data, palette,
1462 pSprite->sprite_flags);
1463 } else {
1464 // Create a palette remapping
1465 ::palette oPalette;
1466 for (int iColour = 0; iColour < 255; iColour++) {
1467 oPalette.set_argb(iColour, argb_data[pSprite->alt_palette_map[iColour]]);
1468 }
1469 // Index 255 is typically transparent and not remapped.
1470 oPalette.set_argb(255, argb_data[255]);
1471
1472 pSprite->alt_texture = target->create_palettized_texture(
1473 pSprite->width, pSprite->height, pSprite->data, &oPalette,
1474 pSprite->sprite_flags);
1475 }
1476
1477 return pSprite->alt_texture;
1478 }
1479
1480 namespace {
1481
1482 /**
1483 * Get the colour data of pixel \a iPixelNumber (\a iWidth * y + x)
1484 * @param pImg 32bpp image data.
1485 * @param iWidth Width of the image.
1486 * @param iHeight Height of the image.
1487 * @param pPalette Palette of the image, or \c nullptr.
1488 * @param iPixelNumber Number of the pixel to retrieve.
1489 */
1490 uint32_t get32BppPixel(const uint8_t* pImg, int iWidth, int iHeight,
1491 const ::palette* pPalette, size_t iPixelNumber) {
1492 if (iWidth <= 0 || iHeight <= 0 ||
1493 iPixelNumber >= static_cast<size_t>(iWidth) * iHeight) {
1494 return palette::pack_argb(0, 0, 0, 0);
1495 }
1496
1497 for (;;) {
1498 uint8_t iType = *pImg++;
1499 size_t iLength = iType & 63;
1500 switch (iType >> 6) {
1501 case 0: // Fixed fully opaque 32bpp pixels
1502 if (iPixelNumber >= iLength) {
1503 pImg += 3 * iLength;
1504 iPixelNumber -= iLength;
1505 break;
1506 }
1507
1508 while (iLength > 0) {
1509 if (iPixelNumber == 0)
1510 return palette::pack_argb(0xFF, pImg[0], pImg[1], pImg[2]);
1511
1512 iPixelNumber--;
1513 pImg += 3;
1514 iLength--;
1515 }
1516 break;
1517
1518 case 1: // Fixed partially transparent 32bpp pixels
1519 {
1520 uint8_t iOpacity = *pImg++;
1521 if (iPixelNumber >= iLength) {
1522 pImg += 3 * iLength;
1523 iPixelNumber -= iLength;
1524 break;
1525 }
1526
1527 while (iLength > 0) {
1528 if (iPixelNumber == 0)
1529 return palette::pack_argb(iOpacity, pImg[0], pImg[1], pImg[2]);
1530
1531 iPixelNumber--;
1532 pImg += 3;
1533 iLength--;
1534 }
1535 break;
1536 }
1537
1538 case 2: // Fixed fully transparent pixels
1539 {
1540 if (iPixelNumber >= iLength) {
1541 iPixelNumber -= iLength;
1542 break;
1543 }
1544
1545 return palette::pack_argb(0, 0, 0, 0);
1546 }
1547
1548 case 3: // Recolour layer
1549 {
1550 uint8_t iTable = *pImg++;
1551 pImg++; // Skip reading the opacity for now.
1552 if (iPixelNumber >= iLength) {
1553 pImg += iLength;
1554 iPixelNumber -= iLength;
1555 break;
1556 }
1557
1558 if (iTable == 0xFF && pPalette != nullptr) {
1559 // Legacy sprite data. Use the palette to recolour the
1560 // layer. Note that the iOpacity is ignored here.
1561 return pPalette->get_argb_data()[pImg[iPixelNumber]];
1562 } else {
1563 // TODO: Add proper recolour layers, where RGB comes from
1564 // table 'iTable' at index *pImg (iLength times), and
1565 // opacity comes from the byte after the iTable byte.
1566 //
1567 // For now just draw black pixels, so it won't go unnoticed.
1568 return palette::pack_argb(0xFF, 0, 0, 0);
1569 }
1570 }
1571 }
1572 }
1573 }
1574
1575 } // namespace
1576
1577 bool sprite_sheet::hit_test_sprite(size_t iSprite, int iX, int iY,
1578 uint32_t iFlags) const {
1579 if (iX < 0 || iY < 0 || iSprite >= sprite_count) return false;
1580
1581 sprite& sprite = sprites[iSprite];
1582 int iWidth = sprite.width;
1583 int iHeight = sprite.height;
1584 if (iX >= iWidth || iY >= iHeight) return false;
1585 if (iFlags & thdf_flip_horizontal) iX = iWidth - iX - 1;
1586 if (iFlags & thdf_flip_vertical) iY = iHeight - iY - 1;
1587
1588 uint32_t iCol =
1589 get32BppPixel(sprite.data, iWidth, iHeight, palette, iY * iWidth + iX);
1590 return palette::get_alpha(iCol) != 0;
1591 }
1592
1593 cursor::~cursor() {
1594 SDL_FreeSurface(bitmap);
1595 SDL_FreeCursor(hidden_cursor);
1596 }
1597
1598 bool cursor::create_from_sprite(sprite_sheet* pSheet, size_t iSprite,
1599 int iHotspotX, int iHotspotY) {
1600 #if 0
1601 SDL_FreeSurface(m_pBitmap);
1602 m_pBitmap = nullptr;
1603
1604 if(pSheet == nullptr || iSprite >= pSheet->getSpriteCount())
1605 return false;
1606 SDL_Surface *pSprite = pSheet->_getSpriteBitmap(iSprite, 0);
1607 if(pSprite == nullptr || (m_pBitmap = SDL_DisplayFormat(pSprite)) == nullptr)
1608 return false;
1609 m_iHotspotX = iHotspotX;
1610 m_iHotspotY = iHotspotY;
1611 return true;
1612 #else
1613 return false;
1614 #endif
1615 }
1616
1617 void cursor::use(render_target* pTarget) {
1618 #if 0
1619 //SDL_ShowCursor(0) is buggy in fullscreen until 1.3 (they say)
1620 // use transparent cursor for same effect
1621 uint8_t uData = 0;
1622 m_pCursorHidden = SDL_CreateCursor(&uData, &uData, 8, 1, 0, 0);
1623 SDL_SetCursor(m_pCursorHidden);
1624 pTarget->setCursor(this);
1625 #endif
1626 }
1627
1628 bool cursor::set_position(render_target* pTarget, int iX, int iY) {
1629 #if 0
1630 pTarget->setCursorPosition(iX, iY);
1631 return true;
1632 #else
1633 return false;
1634 #endif
1635 }
1636
1637 void cursor::draw(render_target* pCanvas, int iX, int iY) {
1638 #if 0
1639 SDL_Rect rcDest;
1640 rcDest.x = (Sint16)(iX - m_iHotspotX);
1641 rcDest.y = (Sint16)(iY - m_iHotspotY);
1642 SDL_BlitSurface(m_pBitmap, nullptr, pCanvas->getRawSurface(), &rcDest);
1643 #endif
1644 }
1645
1646 line_sequence::line_sequence() { move_to(0.0, 0.0); }
1647
1648 void line_sequence::move_to(double fX, double fY) {
1649 line_elements.emplace_back(line_command::move, fX, fY);
1650 }
1651
1652 void line_sequence::line_to(double fX, double fY) {
1653 line_elements.emplace_back(line_command::line, fX, fY);
1654 }
1655
1656 void line_sequence::set_width(double pLineWidth) { width = pLineWidth; }
1657
1658 void line_sequence::set_colour(uint8_t iR, uint8_t iG, uint8_t iB, uint8_t iA) {
1659 red = iR;
1660 green = iG;
1661 blue = iB;
1662 alpha = iA;
1663 }
1664
1665 void line_sequence::draw(render_target* pCanvas, int iX, int iY) {
1666 pCanvas->draw_line(this, iX, iY);
1667 }
1668
1669 void line_sequence::persist(lua_persist_writer* pWriter) const {
1670 pWriter->write_uint(static_cast<uint32_t>(red));
1671 pWriter->write_uint(static_cast<uint32_t>(green));
1672 pWriter->write_uint(static_cast<uint32_t>(blue));
1673 pWriter->write_uint(static_cast<uint32_t>(alpha));
1674 pWriter->write_float<double>(width);
1675
1676 uint32_t numOps = static_cast<uint32_t>(line_elements.size());
1677 pWriter->write_uint(numOps);
1678
1679 for (const line_element& op : line_elements) {
1680 pWriter->write_uint(static_cast<uint32_t>(op.type));
1681 pWriter->write_float<double>(op.x);
1682 pWriter->write_float<double>(op.y);
1683 }
1684 }
1685
1686 void line_sequence::depersist(lua_persist_reader* pReader) {
1687 pReader->read_uint(red);
1688 pReader->read_uint(green);
1689 pReader->read_uint(blue);
1690 pReader->read_uint(alpha);
1691 pReader->read_float(width);
1692
1693 uint32_t numOps = 0;
1694 pReader->read_uint(numOps);
1695
1696 for (uint32_t i = 0; i < numOps; i++) {
1697 // Initialize to invalid in case the read fails.
1698 uint32_t type_val = std::numeric_limits<uint32_t>::max();
1699 double fX = std::nan("");
1700 double fY = std::nan("");
1701 pReader->read_uint(type_val);
1702 pReader->read_float(fX);
1703 pReader->read_float(fY);
1704
1705 if (std::isnan(fX) || std::isnan(fY)) {
1706 return;
1707 }
1708
1709 if (type_val == static_cast<uint32_t>(line_command::move)) {
1710 move_to(fX, fY);
1711 } else if (type_val == static_cast<uint32_t>(line_command::line)) {
1712 line_to(fX, fY);
1713 }
1714 }
1715 }
1716
1717 bool freetype_font::is_monochrome() const { return false; }
1718
1719 void freetype_font::free_texture(cached_text* pCacheEntry) const {
1720 if (pCacheEntry->texture != nullptr) {
1721 SDL_DestroyTexture(pCacheEntry->texture);
1722 pCacheEntry->texture = nullptr;
1723 }
1724 }
1725
1726 void freetype_font::make_texture(const render_target* pEventualCanvas,
1727 cached_text* pCacheEntry) const {
1728 std::vector<argb_colour> pPixels(pCacheEntry->width * pCacheEntry->height, 0);
1729 auto outIter = pPixels.begin();
1730
1731 if (shadow_opts.enabled) {
1732 // When drawing a shadow we need to draw the text twice, first the shadow
1733 // then the text itself. The top left corner of the text area is fixed so
1734 // when the shadow is above or to the left of the text we need to offset the
1735 // text itself down or right, otherwise we offset the shadow text.
1736 copy_pixel_data(pCacheEntry, shadow_opts.color,
1737 std::max(shadow_opts.offset_x, 0),
1738 std::max(shadow_opts.offset_y, 0), outIter);
1739 outIter = pPixels.begin();
1740 copy_pixel_data(pCacheEntry, font_color, std::max(-shadow_opts.offset_x, 0),
1741 std::max(-shadow_opts.offset_y, 0), outIter);
1742 } else {
1743 copy_pixel_data(pCacheEntry, font_color, 0, 0, outIter);
1744 }
1745
1746 pCacheEntry->texture = pEventualCanvas->create_texture(
1747 pCacheEntry->width, pCacheEntry->height, pPixels.data());
1748 }
1749
1750 void freetype_font::copy_pixel_data(
1751 const cached_text* cacheEntry, const argb_colour color, const int offsetX,
1752 const int offsetY, std::vector<argb_colour>::iterator outIter) {
1753 const uint32_t colorBase = color & 0xFFFFFF;
1754 const uint32_t alphaBase = (color >> 24) & 0xFF;
1755
1756 const uint8_t* inData = cacheEntry->data;
1757
1758 for (int iY = 0; iY < cacheEntry->height; ++iY) {
1759 for (int iX = 0; iX < cacheEntry->width; ++iX) {
1760 if (const int inIndex =
1761 (iY - offsetY) * cacheEntry->width + (iX - offsetX);
1762 inIndex >= 0 && inIndex < cacheEntry->width * cacheEntry->height &&
1763 inData[inIndex]) {
1764 *outIter = (inData[inIndex] * alphaBase / 255) << 24 | colorBase;
1765 }
1766 ++outIter;
1767 }
1768 }
1769 }
1770
1771 void freetype_font::draw_texture(render_target* pCanvas,
1772 cached_text* pCacheEntry, int iX,
1773 int iY) const {
1774 if (pCacheEntry->texture == nullptr) return;
1775
1776 SDL_Rect rcDest = {iX, iY, pCacheEntry->width, pCacheEntry->height};
1777 pCanvas->draw(pCacheEntry->texture, nullptr, &rcDest, 0);
1778 }