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 "core/backup_type.hpp"
12 #include "fileio_func.h"
13 #include "viewport_func.h"
15 #include "screenshot.h"
16 #include "screenshot_gui.h"
17 #include "blitter/factory.hpp"
18 #include "zoom_func.h"
19 #include "core/endian_func.hpp"
20 #include "saveload/saveload.h"
21 #include "company_base.h"
22 #include "company_func.h"
23 #include "strings_func.h"
25 #include "textbuf_gui.h"
26 #include "window_gui.h"
27 #include "window_func.h"
29 #include "landscape.h"
30 #include "video/video_driver.hpp"
31 #include "smallmap_gui.h"
33 #include "table/strings.h"
35 #include "safeguards.h"
37 static const char * const SCREENSHOT_NAME
= "screenshot"; ///< Default filename of a saved screenshot.
38 static const char * const HEIGHTMAP_NAME
= "heightmap"; ///< Default filename of a saved heightmap.
40 std::string _screenshot_format_name
; ///< Extension of the current screenshot format (corresponds with #_cur_screenshot_format).
41 static std::string _screenshot_name
; ///< Filename of the screenshot file.
42 std::string _full_screenshot_path
; ///< Pathname of the screenshot file.
43 uint _heightmap_highest_peak
; ///< When saving a heightmap, this contains the highest peak on the map.
46 * Callback function signature for generating lines of pixel data to be written to the screenshot file.
47 * @param userdata Pointer to user data.
48 * @param buf Destination buffer.
49 * @param y Line number of the first line to write.
50 * @param pitch Number of pixels to write (1 byte for 8bpp, 4 bytes for 32bpp). @see Colour
51 * @param n Number of lines to write.
53 typedef void ScreenshotCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
);
56 * Function signature for a screenshot generation routine for one of the available formats.
57 * @param name Filename, including extension.
58 * @param callb Callback function for generating lines of pixels.
59 * @param userdata User data, passed on to \a callb.
60 * @param w Width of the image in pixels.
61 * @param h Height of the image in pixels.
62 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
63 * @param palette %Colour palette (for 8bpp images).
64 * @return File was written successfully.
66 typedef bool ScreenshotHandlerProc(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
);
68 /** Screenshot format information. */
69 struct ScreenshotFormat
{
70 const char *extension
; ///< File extension.
71 ScreenshotHandlerProc
*proc
; ///< Function for writing the screenshot.
74 #define MKCOLOUR(x) TO_LE32(x)
76 /*************************************************
77 **** SCREENSHOT CODE FOR WINDOWS BITMAP (.BMP)
78 *************************************************/
80 /** BMP File Header (stored in little endian) */
81 PACK(struct BitmapFileHeader
{
87 static_assert(sizeof(BitmapFileHeader
) == 14);
89 /** BMP Info Header (stored in little endian) */
90 struct BitmapInfoHeader
{
92 int32_t width
, height
;
93 uint16_t planes
, bitcount
;
94 uint32_t compression
, sizeimage
, xpels
, ypels
, clrused
, clrimp
;
96 static_assert(sizeof(BitmapInfoHeader
) == 40);
98 /** Format of palette data in BMP header */
100 uint8_t blue
, green
, red
, reserved
;
102 static_assert(sizeof(RgbQuad
) == 4);
105 * Generic .BMP writer
106 * @param name file name including extension
107 * @param callb callback used for gathering rendered image
108 * @param userdata parameters forwarded to \a callb
109 * @param w width in pixels
110 * @param h height in pixels
111 * @param pixelformat bits per pixel
112 * @param palette colour palette (for 8bpp mode)
113 * @return was everything ok?
114 * @see ScreenshotHandlerProc
116 static bool MakeBMPImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
118 uint bpp
; // bytes per pixel
119 switch (pixelformat
) {
120 case 8: bpp
= 1; break;
121 /* 32bpp mode is saved as 24bpp BMP */
122 case 32: bpp
= 3; break;
123 /* Only implemented for 8bit and 32bit images so far */
124 default: return false;
127 auto of
= FileHandle::Open(name
, "wb");
128 if (!of
.has_value()) 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
+ static_cast<size_t>(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) {
163 if (pixelformat
== 8) {
164 /* Convert the palette to the windows format */
166 for (uint i
= 0; i
< 256; i
++) {
167 rq
[i
].red
= palette
[i
].r
;
168 rq
[i
].green
= palette
[i
].g
;
169 rq
[i
].blue
= palette
[i
].b
;
172 /* Write the palette */
173 if (fwrite(rq
, sizeof(rq
), 1, f
) != 1) {
178 /* Try to use 64k of memory, store between 16 and 128 lines */
179 uint maxlines
= Clamp(65536 / (w
* pixelformat
/ 8), 16, 128); // number of lines per iteration
181 std::vector
<uint8_t> buff(maxlines
* w
* pixelformat
/ 8); // buffer which is rendered to
182 std::vector
<uint8_t> line(bytewidth
); // one line, stored to file
184 /* Start at the bottom, since bitmaps are stored bottom up */
186 uint n
= std::min(h
, maxlines
);
189 /* Render the pixels */
190 callb(userdata
, buff
.data(), h
, w
, n
);
192 /* Write each line */
194 if (pixelformat
== 8) {
195 /* Move to 'line', leave last few pixels in line zeroed */
196 memcpy(line
.data(), buff
.data() + n
* w
, w
);
198 /* Convert from 'native' 32bpp to BMP-like 24bpp.
199 * Works for both big and little endian machines */
200 Colour
*src
= ((Colour
*)buff
.data()) + n
* w
;
201 uint8_t *dst
= line
.data();
202 for (uint i
= 0; i
< w
; i
++) {
203 dst
[i
* 3 ] = src
[i
].b
;
204 dst
[i
* 3 + 1] = src
[i
].g
;
205 dst
[i
* 3 + 2] = src
[i
].r
;
209 if (fwrite(line
.data(), bytewidth
, 1, f
) != 1) {
219 /*********************************************************
220 **** SCREENSHOT CODE FOR PORTABLE NETWORK GRAPHICS (.PNG)
221 *********************************************************/
222 #if defined(WITH_PNG)
225 #ifdef PNG_TEXT_SUPPORTED
227 #include "newgrf_config.h"
228 #include "ai/ai_info.hpp"
229 #include "company_base.h"
230 #include "base_media_base.h"
231 #endif /* PNG_TEXT_SUPPORTED */
233 static void PNGAPI
png_my_error(png_structp png_ptr
, png_const_charp message
)
235 Debug(misc
, 0, "[libpng] error: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
236 longjmp(png_jmpbuf(png_ptr
), 1);
239 static void PNGAPI
png_my_warning(png_structp png_ptr
, png_const_charp message
)
241 Debug(misc
, 1, "[libpng] warning: {} - {}", message
, (const char *)png_get_error_ptr(png_ptr
));
245 * Generic .PNG file image writer.
246 * @param name Filename, including extension.
247 * @param callb Callback function for generating lines of pixels.
248 * @param userdata User data, passed on to \a callb.
249 * @param w Width of the image in pixels.
250 * @param h Height of the image in pixels.
251 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
252 * @param palette %Colour palette (for 8bpp images).
253 * @return File was written successfully.
254 * @see ScreenshotHandlerProc
256 static bool MakePNGImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
261 uint bpp
= pixelformat
/ 8;
265 /* only implemented for 8bit and 32bit images so far. */
266 if (pixelformat
!= 8 && pixelformat
!= 32) return false;
268 auto of
= FileHandle::Open(name
, "wb");
269 if (!of
.has_value()) return false;
272 png_ptr
= png_create_write_struct(PNG_LIBPNG_VER_STRING
, const_cast<char *>(name
), png_my_error
, png_my_warning
);
274 if (png_ptr
== nullptr) {
278 info_ptr
= png_create_info_struct(png_ptr
);
279 if (info_ptr
== nullptr) {
280 png_destroy_write_struct(&png_ptr
, (png_infopp
)nullptr);
284 if (setjmp(png_jmpbuf(png_ptr
))) {
285 png_destroy_write_struct(&png_ptr
, &info_ptr
);
289 png_init_io(png_ptr
, f
);
291 png_set_filter(png_ptr
, 0, PNG_FILTER_NONE
);
293 png_set_IHDR(png_ptr
, info_ptr
, w
, h
, 8, pixelformat
== 8 ? PNG_COLOR_TYPE_PALETTE
: PNG_COLOR_TYPE_RGB
,
294 PNG_INTERLACE_NONE
, PNG_COMPRESSION_TYPE_DEFAULT
, PNG_FILTER_TYPE_DEFAULT
);
296 #ifdef PNG_TEXT_SUPPORTED
297 /* Try to add some game metadata to the PNG screenshot so
298 * it's more useful for debugging and archival purposes. */
299 png_text_struct text
[2];
300 memset(text
, 0, sizeof(text
));
301 text
[0].key
= const_cast<char *>("Software");
302 text
[0].text
= const_cast<char *>(_openttd_revision
);
303 text
[0].text_length
= strlen(_openttd_revision
);
304 text
[0].compression
= PNG_TEXT_COMPRESSION_NONE
;
307 message
.reserve(1024);
308 fmt::format_to(std::back_inserter(message
), "Graphics set: {} ({})\n", BaseGraphics::GetUsedSet()->name
, BaseGraphics::GetUsedSet()->version
);
309 message
+= "NewGRFs:\n";
310 for (const GRFConfig
*c
= _game_mode
== GM_MENU
? nullptr : _grfconfig
; c
!= nullptr; c
= c
->next
) {
311 fmt::format_to(std::back_inserter(message
), "{:08X} {} {}\n", BSWAP32(c
->ident
.grfid
), FormatArrayAsHex(c
->ident
.md5sum
), c
->filename
);
313 message
+= "\nCompanies:\n";
314 for (const Company
*c
: Company::Iterate()) {
315 if (c
->ai_info
== nullptr) {
316 fmt::format_to(std::back_inserter(message
), "{:2d}: Human\n", (int)c
->index
);
318 fmt::format_to(std::back_inserter(message
), "{:2d}: {} (v{})\n", (int)c
->index
, c
->ai_info
->GetName(), c
->ai_info
->GetVersion());
321 text
[1].key
= const_cast<char *>("Description");
322 text
[1].text
= const_cast<char *>(message
.c_str());
323 text
[1].text_length
= message
.size();
324 text
[1].compression
= PNG_TEXT_COMPRESSION_zTXt
;
325 png_set_text(png_ptr
, info_ptr
, text
, 2);
326 #endif /* PNG_TEXT_SUPPORTED */
328 if (pixelformat
== 8) {
329 /* convert the palette to the .PNG format. */
330 for (i
= 0; i
!= 256; i
++) {
331 rq
[i
].red
= palette
[i
].r
;
332 rq
[i
].green
= palette
[i
].g
;
333 rq
[i
].blue
= palette
[i
].b
;
336 png_set_PLTE(png_ptr
, info_ptr
, rq
, 256);
339 png_write_info(png_ptr
, info_ptr
);
340 png_set_flush(png_ptr
, 512);
342 if (pixelformat
== 32) {
345 /* Save exact colour/alpha resolution */
351 png_set_sBIT(png_ptr
, info_ptr
, &sig_bit
);
353 if constexpr (std::endian::native
== std::endian::little
) {
354 png_set_bgr(png_ptr
);
355 png_set_filler(png_ptr
, 0, PNG_FILLER_AFTER
);
357 png_set_filler(png_ptr
, 0, PNG_FILLER_BEFORE
);
361 /* use by default 64k temp memory */
362 maxlines
= Clamp(65536 / w
, 16, 128);
364 /* now generate the bitmap bits */
365 std::vector
<uint8_t> buff(static_cast<size_t>(w
) * maxlines
* bpp
); // by default generate 128 lines at a time.
369 /* determine # lines to write */
370 n
= std::min(h
- y
, maxlines
);
372 /* render the pixels into the buffer */
373 callb(userdata
, buff
.data(), y
, w
, n
);
376 /* write them to png */
377 for (i
= 0; i
!= n
; i
++) {
378 png_write_row(png_ptr
, (png_bytep
)buff
.data() + i
* w
* bpp
);
382 png_write_end(png_ptr
, info_ptr
);
383 png_destroy_write_struct(&png_ptr
, &info_ptr
);
387 #endif /* WITH_PNG */
390 /*************************************************
391 **** SCREENSHOT CODE FOR ZSOFT PAINTBRUSH (.PCX)
392 *************************************************/
394 /** Definition of a PCX file header. */
396 uint8_t manufacturer
;
403 uint8_t pal_small
[16 * 3];
412 static_assert(sizeof(PcxHeader
) == 128);
415 * Generic .PCX file image writer.
416 * @param name Filename, including extension.
417 * @param callb Callback function for generating lines of pixels.
418 * @param userdata User data, passed on to \a callb.
419 * @param w Width of the image in pixels.
420 * @param h Height of the image in pixels.
421 * @param pixelformat Bits per pixel (bpp), either 8 or 32.
422 * @param palette %Colour palette (for 8bpp images).
423 * @return File was written successfully.
424 * @see ScreenshotHandlerProc
426 static bool MakePCXImage(const char *name
, ScreenshotCallback
*callb
, void *userdata
, uint w
, uint h
, int pixelformat
, const Colour
*palette
)
433 if (pixelformat
== 32) {
434 Debug(misc
, 0, "Can't convert a 32bpp screenshot to PCX format. Please pick another format.");
437 if (pixelformat
!= 8 || w
== 0) return false;
439 auto of
= FileHandle::Open(name
, "wb");
440 if (!of
.has_value()) return false;
443 memset(&pcx
, 0, sizeof(pcx
));
445 /* setup pcx header */
446 pcx
.manufacturer
= 10;
450 pcx
.xmax
= TO_LE16(w
- 1);
451 pcx
.ymax
= TO_LE16(h
- 1);
452 pcx
.hdpi
= TO_LE16(320);
453 pcx
.vdpi
= TO_LE16(320);
456 pcx
.cpal
= TO_LE16(1);
457 pcx
.width
= pcx
.pitch
= TO_LE16(w
);
458 pcx
.height
= TO_LE16(h
);
460 /* write pcx header */
461 if (fwrite(&pcx
, sizeof(pcx
), 1, f
) != 1) {
465 /* use by default 64k temp memory */
466 maxlines
= Clamp(65536 / w
, 16, 128);
468 /* now generate the bitmap bits */
469 std::vector
<uint8_t> buff(static_cast<size_t>(w
) * maxlines
); // by default generate 128 lines at a time.
473 /* determine # lines to write */
474 uint n
= std::min(h
- y
, maxlines
);
477 /* render the pixels into the buffer */
478 callb(userdata
, buff
.data(), y
, w
, n
);
481 /* write them to pcx */
482 for (i
= 0; i
!= n
; i
++) {
483 const uint8_t *bufp
= buff
.data() + i
* w
;
484 uint8_t runchar
= bufp
[0];
488 /* for each pixel... */
489 for (j
= 1; j
< w
; j
++) {
490 uint8_t ch
= bufp
[j
];
492 if (ch
!= runchar
|| runcount
>= 0x3f) {
493 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
494 if (fputc(0xC0 | runcount
, f
) == EOF
) {
498 if (fputc(runchar
, f
) == EOF
) {
507 /* write remaining bytes.. */
508 if (runcount
> 1 || (runchar
& 0xC0) == 0xC0) {
509 if (fputc(0xC0 | runcount
, f
) == EOF
) {
513 if (fputc(runchar
, f
) == EOF
) {
519 /* write 8-bit colour palette */
520 if (fputc(12, f
) == EOF
) {
524 /* Palette is word-aligned, copy it to a temporary byte array */
525 uint8_t tmp
[256 * 3];
527 for (uint i
= 0; i
< 256; i
++) {
528 tmp
[i
* 3 + 0] = palette
[i
].r
;
529 tmp
[i
* 3 + 1] = palette
[i
].g
;
530 tmp
[i
* 3 + 2] = palette
[i
].b
;
532 success
= fwrite(tmp
, sizeof(tmp
), 1, f
) == 1;
537 /*************************************************
538 **** GENERIC SCREENSHOT CODE
539 *************************************************/
541 /** Available screenshot formats. */
542 static const ScreenshotFormat _screenshot_formats
[] = {
543 #if defined(WITH_PNG)
544 {"png", &MakePNGImage
},
546 {"bmp", &MakeBMPImage
},
547 {"pcx", &MakePCXImage
},
550 /* The currently loaded screenshot format. Set to a valid value as it might be used in early crash logs, when InitializeScreenshotFormats has not been called yet. */
551 static const ScreenshotFormat
*_cur_screenshot_format
= std::begin(_screenshot_formats
);
553 /** Get filename extension of current screenshot file format. */
554 const char *GetCurrentScreenshotExtension()
556 return _cur_screenshot_format
->extension
;
559 /** Initialize screenshot format information on startup, with #_screenshot_format_name filled from the loadsave code. */
560 void InitializeScreenshotFormats()
562 for (auto &format
: _screenshot_formats
) {
563 if (_screenshot_format_name
== format
.extension
) {
564 _cur_screenshot_format
= &format
;
569 _cur_screenshot_format
= std::begin(_screenshot_formats
);
573 * Callback of the screenshot generator that dumps the current video buffer.
574 * @see ScreenshotCallback
576 static void CurrentScreenCallback(void *, void *buf
, uint y
, uint pitch
, uint n
)
578 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
579 void *src
= blitter
->MoveTo(_screen
.dst_ptr
, 0, y
);
580 blitter
->CopyImageToBuffer(src
, buf
, _screen
.width
, n
, pitch
);
584 * generate a large piece of the world
585 * @param userdata Viewport area to draw
586 * @param buf Videobuffer with same bitdepth as current blitter
587 * @param y First line to render
588 * @param pitch Pitch of the videobuffer
589 * @param n Number of lines to render
591 static void LargeWorldCallback(void *userdata
, void *buf
, uint y
, uint pitch
, uint n
)
593 Viewport
*vp
= (Viewport
*)userdata
;
597 /* We are no longer rendering to the screen */
598 DrawPixelInfo old_screen
= _screen
;
599 bool old_disable_anim
= _screen_disable_anim
;
601 _screen
.dst_ptr
= buf
;
602 _screen
.width
= pitch
;
604 _screen
.pitch
= pitch
;
605 _screen_disable_anim
= true;
607 AutoRestoreBackup
dpi_backup(_cur_dpi
, &dpi
);
611 dpi
.width
= vp
->width
;
613 dpi
.zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
617 /* Render viewport in blocks of 1600 pixels width */
619 while (vp
->width
- left
!= 0) {
620 wx
= std::min(vp
->width
- left
, 1600);
624 ScaleByZoom(left
- wx
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
625 ScaleByZoom(y
- vp
->top
, vp
->zoom
) + vp
->virtual_top
,
626 ScaleByZoom(left
- vp
->left
, vp
->zoom
) + vp
->virtual_left
,
627 ScaleByZoom((y
+ n
) - vp
->top
, vp
->zoom
) + vp
->virtual_top
631 /* Switch back to rendering to the screen */
632 _screen
= old_screen
;
633 _screen_disable_anim
= old_disable_anim
;
637 * Construct a pathname for a screenshot file.
638 * @param default_fn Default filename.
639 * @param ext Extension to use.
640 * @param crashlog Create path for crash.png
641 * @return Pathname for a screenshot file.
643 static const char *MakeScreenshotName(const char *default_fn
, const char *ext
, bool crashlog
= false)
645 bool generate
= _screenshot_name
.empty();
648 if (_game_mode
== GM_EDITOR
|| _game_mode
== GM_MENU
|| _local_company
== COMPANY_SPECTATOR
) {
649 _screenshot_name
= default_fn
;
651 _screenshot_name
= GenerateDefaultSaveName();
655 /* Handle user-specified filenames ending in # with automatic numbering */
656 if (_screenshot_name
.ends_with("#")) {
658 _screenshot_name
.pop_back();
661 size_t len
= _screenshot_name
.size();
662 /* Add extension to screenshot file */
663 _screenshot_name
+= fmt::format(".{}", ext
);
665 const char *screenshot_dir
= crashlog
? _personal_dir
.c_str() : FiosGetScreenshotDir();
667 for (uint serial
= 1;; serial
++) {
668 _full_screenshot_path
= fmt::format("{}{}", screenshot_dir
, _screenshot_name
);
670 if (!generate
) break; // allow overwriting of non-automatic filenames
671 if (!FileExists(_full_screenshot_path
)) break;
672 /* If file exists try another one with same name, but just with a higher index */
673 _screenshot_name
.erase(len
);
674 _screenshot_name
+= fmt::format("#{}.{}", serial
, ext
);
677 return _full_screenshot_path
.c_str();
680 /** Make a screenshot of the current screen. */
681 static bool MakeSmallScreenshot(bool crashlog
)
683 return _cur_screenshot_format
->proc(MakeScreenshotName(SCREENSHOT_NAME
, _cur_screenshot_format
->extension
, crashlog
), CurrentScreenCallback
, nullptr, _screen
.width
, _screen
.height
,
684 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
688 * Configure a Viewport for rendering (a part of) the map into a screenshot.
689 * @param t Screenshot type
690 * @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).
691 * @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).
692 * @param[out] vp Result viewport
694 void SetupScreenshotViewport(ScreenshotType t
, Viewport
*vp
, uint32_t width
, uint32_t height
)
699 assert(width
== 0 && height
== 0);
701 Window
*w
= GetMainWindow();
702 vp
->virtual_left
= w
->viewport
->virtual_left
;
703 vp
->virtual_top
= w
->viewport
->virtual_top
;
704 vp
->virtual_width
= w
->viewport
->virtual_width
;
705 vp
->virtual_height
= w
->viewport
->virtual_height
;
707 /* Compute pixel coordinates */
710 vp
->width
= _screen
.width
;
711 vp
->height
= _screen
.height
;
712 vp
->overlay
= w
->viewport
->overlay
;
716 assert(width
== 0 && height
== 0);
718 /* Determine world coordinates of screenshot */
719 vp
->zoom
= ZOOM_LVL_WORLD_SCREENSHOT
;
721 TileIndex north_tile
= _settings_game
.construction
.freeform_edges
? TileXY(1, 1) : TileXY(0, 0);
722 TileIndex south_tile
= Map::Size() - 1;
724 /* We need to account for a hill or high building at tile 0,0. */
725 int extra_height_top
= TilePixelHeight(north_tile
) + 150;
726 /* If there is a hill at the bottom don't create a large black area. */
727 int reclaim_height_bottom
= TilePixelHeight(south_tile
);
729 vp
->virtual_left
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, 0).x
;
730 vp
->virtual_top
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(north_tile
) * TILE_SIZE
, extra_height_top
).y
;
731 vp
->virtual_width
= RemapCoords(TileX(north_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, 0).x
- vp
->virtual_left
+ 1;
732 vp
->virtual_height
= RemapCoords(TileX(south_tile
) * TILE_SIZE
, TileY(south_tile
) * TILE_SIZE
, reclaim_height_bottom
).y
- vp
->virtual_top
+ 1;
734 /* Compute pixel coordinates */
737 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
738 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
739 vp
->overlay
= nullptr;
743 vp
->zoom
= (t
== SC_ZOOMEDIN
) ? _settings_client
.gui
.zoom_min
: ZOOM_LVL_VIEWPORT
;
745 Window
*w
= GetMainWindow();
746 vp
->virtual_left
= w
->viewport
->virtual_left
;
747 vp
->virtual_top
= w
->viewport
->virtual_top
;
749 if (width
== 0 || height
== 0) {
750 vp
->virtual_width
= w
->viewport
->virtual_width
;
751 vp
->virtual_height
= w
->viewport
->virtual_height
;
753 vp
->virtual_width
= width
<< vp
->zoom
;
754 vp
->virtual_height
= height
<< vp
->zoom
;
757 /* Compute pixel coordinates */
760 vp
->width
= UnScaleByZoom(vp
->virtual_width
, vp
->zoom
);
761 vp
->height
= UnScaleByZoom(vp
->virtual_height
, vp
->zoom
);
762 vp
->overlay
= nullptr;
769 * Make a screenshot of the map.
770 * @param t Screenshot type: World or viewport screenshot
771 * @param width the width of the screenshot of, or 0 for current viewport width.
772 * @param height the height of the screenshot of, or 0 for current viewport height.
773 * @return true on success
775 static bool MakeLargeWorldScreenshot(ScreenshotType t
, uint32_t width
= 0, uint32_t height
= 0)
778 SetupScreenshotViewport(t
, &vp
, width
, height
);
780 return _cur_screenshot_format
->proc(MakeScreenshotName(SCREENSHOT_NAME
, _cur_screenshot_format
->extension
), LargeWorldCallback
, &vp
, vp
.width
, vp
.height
,
781 BlitterFactory::GetCurrentBlitter()->GetScreenDepth(), _cur_palette
.palette
);
785 * Callback for generating a heightmap. Supports 8bpp grayscale only.
786 * @param buffer Destination buffer.
787 * @param y Line number of the first line to write.
788 * @param n Number of lines to write.
789 * @see ScreenshotCallback
791 static void HeightmapCallback(void *, void *buffer
, uint y
, uint
, uint n
)
793 uint8_t *buf
= (uint8_t *)buffer
;
795 TileIndex ti
= TileXY(Map::MaxX(), y
);
796 for (uint x
= Map::MaxX(); true; x
--) {
797 *buf
= 256 * TileHeight(ti
) / (1 + _heightmap_highest_peak
);
800 ti
= TileAddXY(ti
, -1, 0);
808 * Make a heightmap of the current map.
809 * @param filename Filename to use for saving.
811 bool MakeHeightmapScreenshot(const char *filename
)
814 for (uint i
= 0; i
< lengthof(palette
); i
++) {
821 _heightmap_highest_peak
= 0;
822 for (TileIndex tile
= 0; tile
< Map::Size(); tile
++) {
823 uint h
= TileHeight(tile
);
824 _heightmap_highest_peak
= std::max(h
, _heightmap_highest_peak
);
827 return _cur_screenshot_format
->proc(filename
, HeightmapCallback
, nullptr, Map::SizeX(), Map::SizeY(), 8, palette
);
830 static ScreenshotType _confirmed_screenshot_type
; ///< Screenshot type the current query is about to confirm.
833 * Callback on the confirmation window for huge screenshots.
834 * @param confirmed true on confirmation
836 static void ScreenshotConfirmationCallback(Window
*, bool confirmed
)
838 if (confirmed
) MakeScreenshot(_confirmed_screenshot_type
, {});
843 * Ask for confirmation first if the screenshot will be huge.
844 * @param t Screenshot type: World, defaultzoom, heightmap or viewport screenshot
845 * @see MakeScreenshot
847 void MakeScreenshotWithConfirm(ScreenshotType t
)
850 SetupScreenshotViewport(t
, &vp
);
852 bool heightmap_or_minimap
= t
== SC_HEIGHTMAP
|| t
== SC_MINIMAP
;
853 uint64_t width
= (heightmap_or_minimap
? Map::SizeX() : vp
.width
);
854 uint64_t height
= (heightmap_or_minimap
? Map::SizeY() : vp
.height
);
856 if (width
* height
> 8192 * 8192) {
857 /* Ask for confirmation */
858 _confirmed_screenshot_type
= t
;
860 SetDParam(1, height
);
861 ShowQuery(STR_WARNING_SCREENSHOT_SIZE_CAPTION
, STR_WARNING_SCREENSHOT_SIZE_MESSAGE
, nullptr, ScreenshotConfirmationCallback
);
863 /* Less than 64M pixels, just do it */
864 MakeScreenshot(t
, {});
870 * @param t the type of screenshot to make.
871 * @param name the name to give to the screenshot.
872 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
873 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
874 * @return true iff the screenshot was made successfully
876 static bool RealMakeScreenshot(ScreenshotType t
, std::string name
, uint32_t width
, uint32_t height
)
878 if (t
== SC_VIEWPORT
) {
879 /* First draw the dirty parts of the screen and only then change the name
880 * of the screenshot. This way the screenshot will always show the name
881 * of the previous screenshot in the 'successful' message instead of the
882 * name of the new screenshot (or an empty name). */
883 SetScreenshotWindowVisibility(true);
886 SetScreenshotWindowVisibility(false);
889 _screenshot_name
= name
;
894 ret
= MakeSmallScreenshot(false);
898 ret
= MakeSmallScreenshot(true);
903 ret
= MakeLargeWorldScreenshot(t
, width
, height
);
907 ret
= MakeLargeWorldScreenshot(t
);
911 ret
= MakeHeightmapScreenshot(MakeScreenshotName(HEIGHTMAP_NAME
, _cur_screenshot_format
->extension
));
916 ret
= MakeMinimapWorldScreenshot();
924 if (t
== SC_HEIGHTMAP
) {
925 SetDParamStr(0, _screenshot_name
);
926 SetDParam(1, _heightmap_highest_peak
);
927 ShowErrorMessage(STR_MESSAGE_HEIGHTMAP_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
929 SetDParamStr(0, _screenshot_name
);
930 ShowErrorMessage(STR_MESSAGE_SCREENSHOT_SUCCESSFULLY
, INVALID_STRING_ID
, WL_WARNING
);
933 ShowErrorMessage(STR_ERROR_SCREENSHOT_FAILED
, INVALID_STRING_ID
, WL_ERROR
);
940 * Schedule making a screenshot.
941 * Unconditionally take a screenshot of the requested type.
942 * @param t the type of screenshot to make.
943 * @param name the name to give to the screenshot.
944 * @param width the width of the screenshot of, or 0 for current viewport width (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
945 * @param height the height of the screenshot of, or 0 for current viewport height (only works for SC_ZOOMEDIN and SC_DEFAULTZOOM).
946 * @return true iff the screenshot was successfully made.
947 * @see MakeScreenshotWithConfirm
949 bool MakeScreenshot(ScreenshotType t
, std::string name
, uint32_t width
, uint32_t height
)
951 if (t
== SC_CRASHLOG
) {
952 /* Video buffer might or might not be locked. */
953 VideoDriver::VideoBufferLocker lock
;
955 return RealMakeScreenshot(t
, name
, width
, height
);
958 VideoDriver::GetInstance()->QueueOnMainThread([=] { // Capture by value to not break scope.
959 RealMakeScreenshot(t
, name
, width
, height
);
966 static void MinimapScreenCallback(void *, void *buf
, uint y
, uint pitch
, uint n
)
968 uint32_t *ubuf
= (uint32_t *)buf
;
969 uint num
= (pitch
* n
);
970 for (uint i
= 0; i
< num
; i
++) {
971 uint row
= y
+ (int)(i
/ pitch
);
972 uint col
= (Map::SizeX() - 1) - (i
% pitch
);
974 TileIndex tile
= TileXY(col
, row
);
975 uint8_t val
= GetSmallMapOwnerPixels(tile
, GetTileType(tile
), IncludeHeightmap::Never
) & 0xFF;
977 uint32_t colour_buf
= 0;
978 colour_buf
= (_cur_palette
.palette
[val
].b
<< 0);
979 colour_buf
|= (_cur_palette
.palette
[val
].g
<< 8);
980 colour_buf
|= (_cur_palette
.palette
[val
].r
<< 16);
983 ubuf
++; // Skip alpha
988 * Make a minimap screenshot.
990 bool MakeMinimapWorldScreenshot()
992 return _cur_screenshot_format
->proc(MakeScreenshotName(SCREENSHOT_NAME
, _cur_screenshot_format
->extension
), MinimapScreenCallback
, nullptr, Map::SizeX(), Map::SizeY(), 32, _cur_palette
.palette
);