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 <http://www.gnu.org/licenses/>.
8 /** @file screenshot.cpp The creation of screenshots! */
11 #include "fileio_func.h"
12 #include "viewport_func.h"
14 #include "screenshot.h"
15 #include "screenshot_gui.h"
16 #include "blitter/factory.hpp"
17 #include "zoom_func.h"
18 #include "core/endian_func.hpp"
19 #include "saveload/saveload.h"
20 #include "company_base.h"
21 #include "company_func.h"
22 #include "strings_func.h"
24 #include "textbuf_gui.h"
25 #include "window_gui.h"
26 #include "window_func.h"
28 #include "landscape.h"
29 #include "video/video_driver.hpp"
30 #include "smallmap_gui.h"
32 #include "table/strings.h"
34 #include "safeguards.h"
36 static const char * const SCREENSHOT_NAME
= "screenshot"; ///< Default filename of a saved screenshot.
37 static const char * const HEIGHTMAP_NAME
= "heightmap"; ///< Default filename of a saved heightmap.
39 std::string _screenshot_format_name
; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
40 uint _num_screenshot_formats
; ///< Number of available screenshot formats.
41 uint _cur_screenshot_format
; ///< Index of the currently selected screenshot format in #_screenshot_formats.
42 static char _screenshot_name
[128]; ///< Filename of the screenshot file.
43 char _full_screenshot_name
[MAX_PATH
]; ///< Pathname of the screenshot file.
44 uint _heightmap_highest_peak
; ///< When saving a heightmap, this contains the highest peak on the map.
47 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
48 * @param userdata Pointer to user data.
49 * @param buf Destination buffer.
50 * @param y Line number of the first line to write.
51 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
52 * @param n Number of lines to write.
54 typedef void ScreenshotCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
);
57 * Function signature for a screenshot generation routine for one of the available formats.
58 * @param name Filename, including extension.
59 * @param callb Callback function for generating lines of pixels.
60 * @param userdata User data, passed on to \a callb.
61 * @param w Width of the image in pixels.
62 * @param h Height of the image in pixels.
63 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
64 * @param palette %Colour palette (for 8bpp images).
65 * @return File was written successfully.
67 typedef bool ScreenshotHandlerProc(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
);
69 /** Screenshot format information. */
70 struct ScreenshotFormat
{
71 const char *extension
; ///< File extension.
72 ScreenshotHandlerProc
*proc
; ///< Function for writing the screenshot.
75 #define MKCOLOUR(x) TO_LE32X(x)
77 /*************************************************
78 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
79 *************************************************/
81 /** BMP File Header (stored in little endian) */
82 PACK(struct BitmapFileHeader
{
88 static_assert(sizeof(BitmapFileHeader
) == 14);
90 /** BMP Info Header (stored in little endian) */
91 struct BitmapInfoHeader
{
94 uint16 planes
, bitcount
;
95 uint32 compression
, sizeimage
, xpels
, ypels
, clrused
, clrimp
;
97 static_assert(sizeof(BitmapInfoHeader
) == 40);
99 /** Format of palette data in BMP header */
101 byte blue
, green
, red
, reserved
;
103 static_assert(sizeof(RgbQuad
) == 4);
106 * Generic .BMP writer
107 * @param name file name including extension
108 * @param callb callback used for gathering rendered image
109 * @param userdata parameters forwarded to \a callb
110 * @param w width in pixels
111 * @param h height in pixels
112 * @param pixelformat bits per pixel
113 * @param palette colour palette (for 8bpp mode)
114 * @return was everything ok?
115 * @see ScreenshotHandlerProc
117 static bool MakeBMPImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
119 uint bpp
; // bytes per pixel
120 switch (pixelformat
) {
121 case 8: bpp
= 1; break;
122 /* 32bpp mode is saved as 24bpp BMP */
123 case 32: bpp
= 3; break;
124 /* Only implemented for 8bit and 32bit images so far */
125 default: return false;
128 FILE *f
= fopen(name
, "wb");
129 if (f
== nullptr) return false;
131 /* Each scanline must be aligned on a 32bit boundary */
132 uint bytewidth
= Align(w
* bpp
, 4); // bytes per line in file
134 /* Size of palette. Only present for 8bpp mode */
135 uint pal_size
= pixelformat
== 8 ? sizeof(RgbQuad
) * 256 : 0;
137 /* Setup the file header */
138 BitmapFileHeader bfh
;
139 bfh
.type
= TO_LE16('MB');
140 bfh
.size
= TO_LE32(sizeof(BitmapFileHeader
) + sizeof(BitmapInfoHeader
) + pal_size
+ bytewidth
* h
);
142 bfh
.off_bits
= TO_LE32(sizeof(BitmapFileHeader
) + sizeof(BitmapInfoHeader
) + pal_size
);
144 /* Setup the info header */
145 BitmapInfoHeader bih
;
146 bih
.size
= TO_LE32(sizeof(BitmapInfoHeader
));
147 bih
.width
= TO_LE32(w
);
148 bih
.height
= TO_LE32(h
);
149 bih
.planes
= TO_LE16(1);
150 bih
.bitcount
= TO_LE16(bpp
* 8);
158 /* Write file header and info header */
159 if (fwrite(&bfh
, sizeof(bfh
), 1, f
) != 1 || fwrite(&bih
, sizeof(bih
), 1, f
) != 1) {
164 if (pixelformat
== 8) {
165 /* Convert the palette to the windows format */
167 for (uint i
= 0; i
< 256; i
++) {
168 rq
[i
].red
= palette
[i
].r
;
169 rq
[i
].green
= palette
[i
].g
;
170 rq
[i
].blue
= palette
[i
].b
;
173 /* Write the palette */
174 if (fwrite(rq
, sizeof(rq
), 1, f
) != 1) {
180 /* Try to use 64k of memory, store between 16 and 128 lines */
181 uint maxlines
= Clamp(65536 / (w
* pixelformat
/ 8), 16, 128); // number of lines per iteration
183 uint8
*buff
= MallocT
<uint8
>(maxlines
* w
* pixelformat
/ 8); // buffer which is rendered to
184 uint8
*line
= AllocaM(uint8
, bytewidth
); // one line, stored to file
185 memset(line
, 0, bytewidth
);
187 /* Start at the bottom, since bitmaps are stored bottom up */
189 uint n
= std::min(h
, maxlines
);
192 /* Render the pixels */
193 callb(userdata
, buff
, h
, w
, n
);
195 /* Write each line */
197 if (pixelformat
== 8) {
198 /* Move to 'line', leave last few pixels in line zeroed */
199 memcpy(line
, buff
+ n
* w
, w
);
201 /* Convert from 'native' 32bpp to BMP-like 24bpp.
202 * Works for both big and little endian machines */
203 Colour
*src
= ((Colour
*)buff
) + n
* w
;
205 for (uint i
= 0; i
< w
; i
++) {
206 dst
[i
* 3 ] = src
[i
].b
;
207 dst
[i
* 3 + 1] = src
[i
].g
;
208 dst
[i
* 3 + 2] = src
[i
].r
;
212 if (fwrite(line
, bytewidth
, 1, f
) != 1) {
226 /*********************************************************
227 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
228 *********************************************************/
229 #if defined(WITH_PNG)
232 #ifdef PNG_TEXT_SUPPORTED
234 #include "newgrf_config.h"
235 #include "ai/ai_info.hpp"
236 #include "company_base.h"
237 #include "base_media_base.h"
238 #endif /* PNG_TEXT_SUPPORTED */
240 static void PNGAPI
png_my_error(png_structp png_ptr
, png_const_charp message
)
242 Debug(misc
, 0, "[libpng] error: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
243 longjmp(png_jmpbuf(png_ptr
), 1);
246 static void PNGAPI
png_my_warning(png_structp png_ptr
, png_const_charp message
)
248 Debug(misc
, 1, "[libpng] warning: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
252 * Generic .PNG file image writer.
253 * @param name Filename, including extension.
254 * @param callb Callback function for generating lines of pixels.
255 * @param userdata User data, passed on to \a callb.
256 * @param w Width of the image in pixels.
257 * @param h Height of the image in pixels.
258 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
259 * @param palette %Colour palette (for 8bpp images).
260 * @return File was written successfully.
261 * @see ScreenshotHandlerProc
263 static bool MakePNGImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
269 uint bpp
= pixelformat
/ 8;
273 /* only implemented for 8bit and 32bit images so far. */
274 if (pixelformat
!= 8 && pixelformat
!= 32) return false;
276 f
= fopen(name
, "wb");
277 if (f
== nullptr) return false;
279 png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
, const_cast<char *>(name
), png_my_error
, png_my_warning
);
281 if (png_ptr
== nullptr) {
286 info_ptr
= png_create_info_struct(png_ptr
);
287 if (info_ptr
== nullptr) {
288 png_destroy_write_struct(&png_ptr
, (png_infopp
)nullptr);
293 if (setjmp(png_jmpbuf(png_ptr
))) {
294 png_destroy_write_struct(&png_ptr
, &info_ptr
);
299 png_init_io(png_ptr
, f
);
301 png_set_filter(png_ptr
, 0, PNG_FILTER_NONE
);
303 png_set_IHDR(png_ptr
, info_ptr
, w
, h
, 8, pixelformat
== 8 ? PNG_COLOR_TYPE_PALETTE
: PNG_COLOR_TYPE_RGB
,
304 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_DEFAULT
, PNG_FILTER_TYPE_DEFAULT
);
306 #ifdef PNG_TEXT_SUPPORTED
307 /* Try to add some game metadata to the PNG screenshot so
308 * it's more useful for debugging and archival purposes. */
309 png_text_struct text
[2];
310 memset(text
, 0, sizeof(text
));
311 text
[0].key
= const_cast<char *>("Software");
312 text
[0].text
= const_cast<char *>(_openttd_revision
);
313 text
[0].text_length
= strlen(_openttd_revision
);
314 text
[0].compression
= PNG_TEXT_COMPRESSION_NONE
;
318 p
+= seprintf(p
, lastof(buf
), "Graphics set: %s (%u)\n", BaseGraphics::GetUsedSet()->name
.c_str(), BaseGraphics::GetUsedSet()->version
);
319 p
= strecpy(p
, "NewGRFs:\n", lastof(buf
));
320 for (const GRFConfig
*c
= _game_mode
== GM_MENU
? nullptr : _grfconfig
; c
!= nullptr; c
= c
->next
) {
321 p
+= seprintf(p
, lastof(buf
), "%08X ", BSWAP32(c
->ident
.grfid
));
322 p
= md5sumToString(p
, lastof(buf
), c
->ident
.md5sum
);
323 p
+= seprintf(p
, lastof(buf
), " %s\n", c
->filename
);
325 p
= strecpy(p
, "\nCompanies:\n", lastof(buf
));
326 for (const Company
*c
: Company::Iterate()) {
327 if (c
->ai_info
== nullptr) {
328 p
+= seprintf(p
, lastof(buf
), "%2i: Human\n", (int)c
->index
);
330 p
+= seprintf(p
, lastof(buf
), "%2i: %s (v%d)\n", (int)c
->index
, c
->ai_info
->GetName(), c
->ai_info
->GetVersion());
333 text
[1].key
= const_cast<char *>("Description");
335 text
[1].text_length
= p
- buf
;
336 text
[1].compression
= PNG_TEXT_COMPRESSION_zTXt
;
337 png_set_text(png_ptr
, info_ptr
, text
, 2);
338 #endif /* PNG_TEXT_SUPPORTED */
340 if (pixelformat
== 8) {
341 /* convert the palette to the .PNG format. */
342 for (i
= 0; i
!= 256; i
++) {
343 rq
[i
].red
= palette
[i
].r
;
344 rq
[i
].green
= palette
[i
].g
;
345 rq
[i
].blue
= palette
[i
].b
;
348 png_set_PLTE(png_ptr
, info_ptr
, rq
, 256);
351 png_write_info(png_ptr
, info_ptr
);
352 png_set_flush(png_ptr
, 512);
354 if (pixelformat
== 32) {
357 /* Save exact colour/alpha resolution */
363 png_set_sBIT(png_ptr
, info_ptr
, &sig_bit
);
365 #if TTD_ENDIAN == TTD_LITTLE_ENDIAN
366 png_set_bgr(png_ptr
);
367 png_set_filler(png_ptr
, 0, PNG_FILLER_AFTER
);
369 png_set_filler(png_ptr
, 0, PNG_FILLER_BEFORE
);
370 #endif /* TTD_ENDIAN == TTD_LITTLE_ENDIAN */
373 /* use by default 64k temp memory */
374 maxlines
= Clamp(65536 / w
, 16, 128);
376 /* now generate the bitmap bits */
377 void *buff
= CallocT
<uint8
>(w
* maxlines
* bpp
); // by default generate 128 lines at a time.
381 /* determine # lines to write */
382 n
= std::min(h
- y
, maxlines
);
384 /* render the pixels into the buffer */
385 callb(userdata
, buff
, y
, w
, n
);
388 /* write them to png */
389 for (i
= 0; i
!= n
; i
++) {
390 png_write_row(png_ptr
, (png_bytep
)buff
+ i
* w
* bpp
);
394 png_write_end(png_ptr
, info_ptr
);
395 png_destroy_write_struct(&png_ptr
, &info_ptr
);
401 #endif /* WITH_PNG */
404 /*************************************************
405 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
406 *************************************************/
408 /** Definition of a PCX file header. */
417 byte pal_small
[16 * 3];
426 static_assert(sizeof(PcxHeader
) == 128);
429 * Generic .PCX file image writer.
430 * @param name Filename, including extension.
431 * @param callb Callback function for generating lines of pixels.
432 * @param userdata User data, passed on to \a callb.
433 * @param w Width of the image in pixels.
434 * @param h Height of the image in pixels.
435 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
436 * @param palette %Colour palette (for 8bpp images).
437 * @return File was written successfully.
438 * @see ScreenshotHandlerProc
440 static bool MakePCXImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
448 if (pixelformat
== 32) {
449 Debug(misc
, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
452 if (pixelformat
!= 8 || w
== 0) return false;
454 f
= fopen(name
, "wb");
455 if (f
== nullptr) return false;
457 memset(&pcx
, 0, sizeof(pcx
));
459 /* setup pcx header */
460 pcx
.manufacturer
= 10;
464 pcx
.xmax
= TO_LE16(w
- 1);
465 pcx
.ymax
= TO_LE16(h
- 1);
466 pcx
.hdpi
= TO_LE16(320);
467 pcx
.vdpi
= TO_LE16(320);
470 pcx
.cpal
= TO_LE16(1);
471 pcx
.width
= pcx
.pitch
= TO_LE16(w
);
472 pcx
.height
= TO_LE16(h
);
474 /* write pcx header */
475 if (fwrite(&pcx
, sizeof(pcx
), 1, f
) != 1) {
480 /* use by default 64k temp memory */
481 maxlines
= Clamp(65536 / w
, 16, 128);
483 /* now generate the bitmap bits */
484 uint8
*buff
= CallocT
<uint8
>(w
* maxlines
); // by default generate 128 lines at a time.
488 /* determine # lines to write */
489 uint n
= std::min(h
- y
, maxlines
);
492 /* render the pixels into the buffer */
493 callb(userdata
, buff
, y
, w
, n
);
496 /* write them to pcx */
497 for (i
= 0; i
!= n
; i
++) {
498 const uint8
*bufp
= buff
+ i
* w
;
499 byte runchar
= bufp
[0];
503 /* for each pixel... */
504 for (j
= 1; j
< w
; j
++) {
507 if (ch
!= runchar
|| runcount
>= 0x3f) {
508 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
509 if (fputc(0xC0 | runcount
, f
) == EOF
) {
515 if (fputc(runchar
, f
) == EOF
) {
526 /* write remaining bytes.. */
527 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
528 if (fputc(0xC0 | runcount
, f
) == EOF
) {
534 if (fputc(runchar
, f
) == EOF
) {
544 /* write 8-bit colour palette */
545 if (fputc(12, f
) == EOF
) {
550 /* Palette is word-aligned, copy it to a temporary byte array */
553 for (uint i
= 0; i
< 256; i
++) {
554 tmp
[i
* 3 + 0] = palette
[i
].r
;
555 tmp
[i
* 3 + 1] = palette
[i
].g
;
556 tmp
[i
* 3 + 2] = palette
[i
].b
;
558 success
= fwrite(tmp
, sizeof(tmp
), 1, f
) == 1;
565 /*************************************************
566 **** GENERIC SCREENSHOT CODE
567 *************************************************/
569 /** Available screenshot formats. */
570 static const ScreenshotFormat _screenshot_formats
[] = {
571 #if defined(WITH_PNG)
572 {"png", &MakePNGImage
},
574 {"bmp", &MakeBMPImage
},
575 {"pcx", &MakePCXImage
},
578 /** Get filename extension of current screenshot file format. */
579 const char *GetCurrentScreenshotExtension()
581 return _screenshot_formats
[_cur_screenshot_format
].extension
;
584 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
585 void InitializeScreenshotFormats()
588 for (uint i
= 0; i
< lengthof(_screenshot_formats
); i
++) {
589 if (_screenshot_format_name
.compare(_screenshot_formats
[i
].extension
) == 0) {
594 _cur_screenshot_format
= j
;
595 _num_screenshot_formats
= lengthof(_screenshot_formats
);
599 * Callback of the screenshot generator that dumps the current video buffer.
600 * @see ScreenshotCallback
602 static void CurrentScreenCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
)
604 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
605 void *src
= blitter
->MoveTo(_screen
.dst_ptr
, 0, y
);
606 blitter
->CopyImageToBuffer(src
, buf
, _screen
.width
, n
, pitch
);
610 * generate a large piece of the world
611 * @param userdata Viewport area to draw
612 * @param buf Videobuffer with same bitdepth as current blitter
613 * @param y First line to render
614 * @param pitch Pitch of the videobuffer
615 * @param n Number of lines to render
617 static void LargeWorldCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
)
619 Viewport
*vp
= (Viewport
*)userdata
;
620 DrawPixelInfo dpi
, *old_dpi
;
623 /* We are no longer rendering to the screen */
624 DrawPixelInfo old_screen
= _screen
;
625 bool old_disable_anim
= _screen_disable_anim
;
627 _screen
.dst_ptr
= buf
;
628 _screen
.width
= pitch
;
630 _screen
.pitch
= pitch
;
631 _screen_disable_anim
= true;
638 dpi
.width
= vp
->width
;
640 dpi
.zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
644 /* Render viewport in blocks of 1600 pixels width */
646 while (vp
->width
- left
!= 0) {
647 wx
= std::min(vp
->width
- left
, 1600);
651 ScaleByZoom(left
- wx
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
652 ScaleByZoom(y
- vp
->top
, vp
->zoom
) + vp
->virtual_top
,
653 ScaleByZoom(left
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
654 ScaleByZoom((y
+ n
) - vp
->top
, vp
->zoom
) + vp
->virtual_top
660 /* Switch back to rendering to the screen */
661 _screen
= old_screen
;
662 _screen_disable_anim
= old_disable_anim
;
666 * Construct a pathname for a screenshot file.
667 * @param default_fn Default filename.
668 * @param ext Extension to use.
669 * @param crashlog Create path for crash.png
670 * @return Pathname for a screenshot file.
672 static const char *MakeScreenshotName(const char *default_fn
, const char *ext
, bool crashlog
= false)
674 bool generate
= StrEmpty(_screenshot_name
);
677 if (_game_mode
== GM_EDITOR
|| _game_mode
== GM_MENU
|| _local_company
== COMPANY_SPECTATOR
) {
678 strecpy(_screenshot_name
, default_fn
, lastof(_screenshot_name
));
680 GenerateDefaultSaveName(_screenshot_name
, lastof(_screenshot_name
));
684 /* Add extension to screenshot file */
685 size_t len
= strlen(_screenshot_name
);
686 seprintf(&_screenshot_name
[len
], lastof(_screenshot_name
), ".%s", ext
);
688 const char *screenshot_dir
= crashlog
? _personal_dir
.c_str() : FiosGetScreenshotDir();
690 for (uint serial
= 1;; serial
++) {
691 if (seprintf(_full_screenshot_name
, lastof(_full_screenshot_name
), "%s%s", screenshot_dir
, _screenshot_name
) >= (int)lengthof(_full_screenshot_name
)) {
692 /* We need more characters than MAX_PATH -> end with error */
693 _full_screenshot_name
[0] = '\0';
696 if (!generate
) break; // allow overwriting of non-automatic filenames
697 if (!FileExists(_full_screenshot_name
)) break;
698 /* If file exists try another one with same name, but just with a higher index */
699 seprintf(&_screenshot_name
[len
], lastof(_screenshot_name
) - len
, "#%u.%s", serial
, ext
);
702 return _full_screenshot_name
;
705 /** Make a screenshot of the current screen. */
706 static bool MakeSmallScreenshot(bool crashlog
)
708 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
709 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
, crashlog
), CurrentScreenCallback
, nullptr, _screen
.width
, _screen
.height
,
710 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
714 * Configure a Viewport for rendering (a part of) the map into a screenshot.
715 * @param t Screenshot type
716 * @param width the width of the screenshot, or 0 for current viewport width (needs to be 0 with SC_VIEWPORT, SC_CRASHLOG, and SC_WORLD).
717 * @param height the height of the screenshot, or 0 for current viewport height (needs to be 0 with SC_VIEWPORT, SC_CRASHLOG, and SC_WORLD).
718 * @param[out] vp Result viewport
720 void SetupScreenshotViewport(ScreenshotType t
, Viewport
*vp
, uint32 width
, uint32 height
)
725 assert(width
== 0 && height
== 0);
727 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
728 vp
->virtual_left
= w
->viewport
->virtual_left
;
729 vp
->virtual_top
= w
->viewport
->virtual_top
;
730 vp
->virtual_width
= w
->viewport
->virtual_width
;
731 vp
->virtual_height
= w
->viewport
->virtual_height
;
733 /* Compute pixel coordinates */
736 vp
->width
= _screen
.width
;
737 vp
->height
= _screen
.height
;
738 vp
->overlay
= w
->viewport
->overlay
;
742 assert(width
== 0 && height
== 0);
744 /* Determine world coordinates of screenshot */
745 vp
->zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
747 TileIndex north_tile
= _settings_game
.construction
.freeform_edges
? TileXY(1, 1) : TileXY(0, 0);
748 TileIndex south_tile
= MapSize() - 1;
750 /* We need to account for a hill or high building at tile 0,0. */
751 int extra_height_top
= TilePixelHeight(north_tile
) + 150;
752 /* If there is a hill at the bottom don't create a large black area. */
753 int reclaim_height_bottom
= TilePixelHeight(south_tile
);
755 vp
->virtual_left
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, 0).x
;
756 vp
->virtual_top
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, extra_height_top
).y
;
757 vp
->virtual_width
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, 0).x
- vp
->virtual_left
+ 1;
758 vp
->virtual_height
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, reclaim_height_bottom
).y
- vp
->virtual_top
+ 1;
760 /* Compute pixel coordinates */
763 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
764 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
765 vp
->overlay
= nullptr;
769 vp
->zoom
= (t
== SC_ZOOMEDIN
) ? _settings_client
.gui
.zoom_min
: ZOOM_LVL_VIEWPORT
;
771 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
772 vp
->virtual_left
= w
->viewport
->virtual_left
;
773 vp
->virtual_top
= w
->viewport
->virtual_top
;
775 if (width
== 0 || height
== 0) {
776 vp
->virtual_width
= w
->viewport
->virtual_width
;
777 vp
->virtual_height
= w
->viewport
->virtual_height
;
779 vp
->virtual_width
= width
<< vp
->zoom
;
780 vp
->virtual_height
= height
<< vp
->zoom
;
783 /* Compute pixel coordinates */
786 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
787 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
788 vp
->overlay
= nullptr;
795 * Make a screenshot of the map.
796 * @param t Screenshot type: World or viewport screenshot
797 * @param width the width of the screenshot of, or 0 for current viewport width.
798 * @param height the height of the screenshot of, or 0 for current viewport height.
799 * @return true on success
801 static bool MakeLargeWorldScreenshot(ScreenshotType t
, uint32 width
= 0, uint32 height
= 0)
804 SetupScreenshotViewport(t
, &vp
, width
, height
);
806 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
807 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
), LargeWorldCallback
, &vp
, vp
.width
, vp
.height
,
808 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
812 * Callback for generating a heightmap. Supports 8bpp grayscale only.
813 * @param userdata Pointer to user data.
814 * @param buffer Destination buffer.
815 * @param y Line number of the first line to write.
816 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
817 * @param n Number of lines to write.
818 * @see ScreenshotCallback
820 static void HeightmapCallback(void *userdata
, void *buffer
, uint y
, uint pitch
, uint n
)
822 byte
*buf
= (byte
*)buffer
;
824 TileIndex ti
= TileXY(MapMaxX(), y
);
825 for (uint x
= MapMaxX(); true; x
--) {
826 *buf
= 256 * TileHeight(ti
) / (1 + _heightmap_highest_peak
);
829 ti
= TILE_ADDXY(ti
, -1, 0);
837 * Make a heightmap of the current map.
838 * @param filename Filename to use for saving.
840 bool MakeHeightmapScreenshot(const char *filename
)
843 for (uint i
= 0; i
< lengthof(palette
); i
++) {
850 _heightmap_highest_peak
= 0;
851 for (TileIndex tile
= 0; tile
< MapSize(); tile
++) {
852 uint h
= TileHeight(tile
);
853 _heightmap_highest_peak
= std::max(h
, _heightmap_highest_peak
);
856 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
857 return sf
->proc(filename
, HeightmapCallback
, nullptr, MapSizeX(), MapSizeY(), 8, palette
);
860 static ScreenshotType _confirmed_screenshot_type
; ///< Screenshot type the current query is about to confirm.
863 * Callback on the confirmation window for huge screenshots.
864 * @param w Window with viewport
865 * @param confirmed true on confirmation
867 static void ScreenshotConfirmationCallback(Window
*w
, bool confirmed
)
869 if (confirmed
) MakeScreenshot(_confirmed_screenshot_type
, {});
874 * Ask for confirmation first if the screenshot will be huge.
875 * @param t Screenshot type: World, defaultzoom, heightmap or viewport screenshot
876 * @see MakeScreenshot
878 void MakeScreenshotWithConfirm(ScreenshotType t
)
881 SetupScreenshotViewport(t
, &vp
);
883 bool heightmap_or_minimap
= t
== SC_HEIGHTMAP
|| t
== SC_MINIMAP
;
884 uint64_t width
= (heightmap_or_minimap
? MapSizeX() : vp
.width
);
885 uint64_t height
= (heightmap_or_minimap
? MapSizeY() : vp
.height
);
887 if (width
* height
> 8192 * 8192) {
888 /* Ask for confirmation */
889 _confirmed_screenshot_type
= t
;
891 SetDParam(1, height
);
892 ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION
, STR_WARNING_SCREENSHOT_SIZE_MESSAGE
, nullptr, ScreenshotConfirmationCallback
);
894 /* Less than 64M pixels, just do it */
895 MakeScreenshot(t
, {});
901 * @param t the type of screenshot to make.
902 * @param name the name to give to the screenshot.
903 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
904 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
905 * @return true iff the screenshot was made successfully
907 static bool RealMakeScreenshot(ScreenshotType t
, std::string name
, uint32 width
, uint32 height
)
909 if (t
== SC_VIEWPORT
) {
910 /* First draw the dirty parts of the screen and only then change the name
911 * of the screenshot. This way the screenshot will always show the name
912 * of the previous screenshot in the 'successful' message instead of the
913 * name of the new screenshot (or an empty name). */
914 SetScreenshotWindowVisibility(true);
917 SetScreenshotWindowVisibility(false);
920 _screenshot_name
[0] = '\0';
921 if (!name
.empty()) strecpy(_screenshot_name
, name
.c_str(), lastof(_screenshot_name
));
926 ret
= MakeSmallScreenshot(false);
930 ret
= MakeSmallScreenshot(true);
935 ret
= MakeLargeWorldScreenshot(t
, width
, height
);
939 ret
= MakeLargeWorldScreenshot(t
);
943 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
944 ret
= MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME
, sf
->extension
));
949 ret
= MakeMinimapWorldScreenshot();
957 if (t
== SC_HEIGHTMAP
) {
958 SetDParamStr(0, _screenshot_name
);
959 SetDParam(1, _heightmap_highest_peak
);
960 ShowErrorMessage(STR_MESSAGE_HEIGHTMAP_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
962 SetDParamStr(0, _screenshot_name
);
963 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
966 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
973 * Schedule making a screenshot.
974 * Unconditionally take a screenshot of the requested type.
975 * @param t the type of screenshot to make.
976 * @param name the name to give to the screenshot.
977 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
978 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
979 * @return true iff the screenshot was successfully made.
980 * @see MakeScreenshotWithConfirm
982 bool MakeScreenshot(ScreenshotType t
, std::string name
, uint32 width
, uint32 height
)
984 if (t
== SC_CRASHLOG
) {
985 /* Video buffer might or might not be locked. */
986 VideoDriver::VideoBufferLocker lock
;
988 return RealMakeScreenshot(t
, name
, width
, height
);
991 VideoDriver::GetInstance()->QueueOnMainThread([=] { // Capture by value to not break scope.
992 RealMakeScreenshot(t
, name
, width
, height
);
999 static void MinimapScreenCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
)
1001 uint32
*ubuf
= (uint32
*)buf
;
1002 uint num
= (pitch
* n
);
1003 for (uint i
= 0; i
< num
; i
++) {
1004 uint row
= y
+ (int)(i
/ pitch
);
1005 uint col
= (MapSizeX() - 1) - (i
% pitch
);
1007 TileIndex tile
= TileXY(col
, row
);
1008 byte val
= GetSmallMapOwnerPixels(tile
, GetTileType(tile
), IncludeHeightmap::Never
) & 0xFF;
1010 uint32 colour_buf
= 0;
1011 colour_buf
= (_cur_palette
.palette
[val
].b
<< 0);
1012 colour_buf
|= (_cur_palette
.palette
[val
].g
<< 8);
1013 colour_buf
|= (_cur_palette
.palette
[val
].r
<< 16);
1016 ubuf
++; // Skip alpha
1021 * Make a minimap screenshot.
1023 bool MakeMinimapWorldScreenshot()
1025 const ScreenshotFormat
*sf
= _screenshot_formats
+ _cur_screenshot_format
;
1026 return sf
->proc(MakeScreenshotName(SCREENSHOT_NAME
, sf
->extension
), MinimapScreenCallback
, nullptr, MapSizeX(), MapSizeY(), 32, _cur_palette
.palette
);