forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sdltiles.cpp
3945 lines (3522 loc) · 161 KB
/
sdltiles.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if defined(TILES)
#include "cursesdef.h" // IWYU pragma: associated
#include "sdltiles.h" // IWYU pragma: associated
#include <algorithm>
#include <array>
#include <cassert>
#include <climits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <exception>
#include <fstream>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <stack>
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <vector>
#if defined(_MSC_VER) && defined(USE_VCPKG)
# include <SDL2/SDL_image.h>
# include <SDL2/SDL_syswm.h>
#else
#ifdef _WIN32
# include <SDL_syswm.h>
#endif
#endif
#include "avatar.h"
#include "basecamp.h"
#include "cata_tiles.h"
#include "cata_utility.h"
#include "catacharset.h"
#include "color.h"
#include "color_loader.h"
#include "cuboid_rectangle.h"
#include "cursesport.h"
#include "debug.h"
#include "filesystem.h"
#include "font_loader.h"
#include "game.h"
#include "game_ui.h"
#include "get_version.h"
#include "hash_utils.h"
#include "input.h"
#include "runtime_handlers.h"
#include "json.h"
#include "mapbuffer.h"
#include "mission.h"
#include "npc.h"
#include "options.h"
#include "output.h"
#include "overmap_location.h"
#include "overmap_special.h"
#include "overmap_ui.h"
#include "overmapbuffer.h"
#include "path_info.h"
#include "point.h"
#include "rng.h"
#include "sdl_wrappers.h"
#include "sdl_geometry.h"
#include "sdl_font.h"
#include "sdlsound.h"
#include "string_formatter.h"
#include "uistate.h"
#include "ui_manager.h"
#include "wcwidth.h"
#include "worldfactory.h"
#if defined(__linux__)
# include <cstdlib> // getenv()/setenv()
#endif
#if defined(_WIN32)
# if 1 // HACK: Hack to prevent reordering of #include "platform_win.h" by IWYU
# include "platform_win.h"
# endif
# include <shlwapi.h>
#endif
#if defined(__ANDROID__)
#include <jni.h>
#include "action.h"
#include "inventory.h"
#include "map.h"
#include "vehicle.h"
#include "vpart_position.h"
#include "worldfactory.h"
#endif
#define dbg(x) DebugLogFL((x),DC::SDL)
//***********************************
//Globals *
//***********************************
std::unique_ptr<cata_tiles> tilecontext;
static uint32_t lastupdate = 0;
static uint32_t interval = 25;
static bool needupdate = false;
static bool need_invalidate_framebuffers = false;
palette_array windowsPalette;
static Font_Ptr font;
static Font_Ptr map_font;
static Font_Ptr overmap_font;
static SDL_Window_Ptr window;
static SDL_Renderer_Ptr renderer;
static SDL_PixelFormat_Ptr format;
static SDL_Texture_Ptr display_buffer;
static GeometryRenderer_Ptr geometry;
#if defined(__ANDROID__)
static SDL_Texture_Ptr touch_joystick;
#endif
static int WindowWidth; //Width of the actual window, not the curses window
static int WindowHeight; //Height of the actual window, not the curses window
// input from various input sources. Each input source sets the type and
// the actual input value (key pressed, mouse button clicked, ...)
// This value is finally returned by input_manager::get_input_event.
static input_event last_input;
static constexpr int ERR = -1;
static int inputdelay; //How long getch will wait for a character to be typed
static Uint32 delaydpad =
std::numeric_limits<Uint32>::max(); // Used for entering diagonal directions with d-pad.
static Uint32 dpad_delay =
100; // Delay in milliseconds between registering a d-pad event and processing it.
static bool dpad_continuous = false; // Whether we're currently moving continuously with the dpad.
static int lastdpad = ERR; // Keeps track of the last dpad press.
static int queued_dpad = ERR; // Queued dpad press, for individual button presses.
int fontwidth; //the width of the font, background is always this size
int fontheight; //the height of the font, background is always this size
static int TERMINAL_WIDTH;
static int TERMINAL_HEIGHT;
bool fullscreen;
int scaling_factor;
static SDL_Joystick *joystick; // Only one joystick for now.
using cata_cursesport::curseline;
using cata_cursesport::cursecell;
static std::vector<curseline> oversized_framebuffer;
static std::vector<curseline> terminal_framebuffer;
static std::weak_ptr<void> winBuffer; //tracking last drawn window to fix the framebuffer
static int fontScaleBuffer; //tracking zoom levels to fix framebuffer w/tiles
//***********************************
//Non-curses, Window functions *
//***********************************
static bool operator==( const cata_cursesport::WINDOW *const lhs, const catacurses::window &rhs )
{
return lhs == rhs.get();
}
static void ClearScreen()
{
SetRenderDrawColor( renderer, 0, 0, 0, 255 );
RenderClear( renderer );
}
static void InitSDL()
{
int init_flags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER;
int ret;
#if defined(SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING)
SDL_SetHint( SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING, "1" );
#endif
#if defined(__linux__)
// https://bugzilla.libsdl.org/show_bug.cgi?id=3472#c5
if( SDL_COMPILEDVERSION == SDL_VERSIONNUM( 2, 0, 5 ) ) {
const char *xmod = getenv( "XMODIFIERS" );
if( xmod && strstr( xmod, "@im=ibus" ) != nullptr ) {
setenv( "XMODIFIERS", "@im=none", 1 );
}
}
#endif
ret = SDL_Init( init_flags );
throwErrorIf( ret != 0, "SDL_Init failed" );
ret = TTF_Init();
throwErrorIf( ret != 0, "TTF_Init failed" );
// cata_tiles won't be able to load the tiles, but the normal SDL
// code will display fine.
ret = IMG_Init( IMG_INIT_PNG );
printErrorIf( ( ret & IMG_INIT_PNG ) != IMG_INIT_PNG,
"IMG_Init failed to initialize PNG support, tiles won't work" );
ret = SDL_InitSubSystem( SDL_INIT_JOYSTICK );
printErrorIf( ret != 0, "Initializing joystick subsystem failed" );
//SDL2 has no functionality for INPUT_DELAY, we would have to query it manually, which is expensive
//SDL2 instead uses the OS's Input Delay.
atexit( SDL_Quit );
}
static bool SetupRenderTarget()
{
SetRenderDrawBlendMode( renderer, SDL_BLENDMODE_NONE );
display_buffer.reset( SDL_CreateTexture( renderer.get(), SDL_PIXELFORMAT_ARGB8888,
SDL_TEXTUREACCESS_TARGET, WindowWidth / scaling_factor, WindowHeight / scaling_factor ) );
if( printErrorIf( !display_buffer, "Failed to create window buffer" ) ) {
return false;
}
if( printErrorIf( SDL_SetRenderTarget( renderer.get(), display_buffer.get() ) != 0,
"SDL_SetRenderTarget failed" ) ) {
return false;
}
ClearScreen();
return true;
}
//Registers, creates, and shows the Window!!
static void WinCreate()
{
std::string version = string_format( "Cataclysm: Bright Nights - %s", getVersionString() );
// Common flags used for fulscreen and for windowed
int window_flags = 0;
WindowWidth = TERMINAL_WIDTH * fontwidth * scaling_factor;
WindowHeight = TERMINAL_HEIGHT * fontheight * scaling_factor;
window_flags |= SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
// We want our textures clean and sharp when zooming in.
SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "nearest" );
#if !defined(__ANDROID__)
const auto screen_mode = get_option<std::string>( "FULLSCREEN" );
const auto minimize = get_option<bool>( "MINIMIZE_ON_FOCUS_LOSS" );
SDL_SetHint( SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, minimize ? "1" : "0" );
if( screen_mode == "fullscreen" ) {
window_flags |= SDL_WINDOW_FULLSCREEN;
fullscreen = true;
} else if( screen_mode == "windowedbl" ) {
window_flags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
fullscreen = true;
} else if( screen_mode == "maximized" ) {
window_flags |= SDL_WINDOW_MAXIMIZED;
}
#endif
int display = std::stoi( get_option<std::string>( "DISPLAY" ) );
if( display < 0 || display >= SDL_GetNumVideoDisplays() ) {
display = 0;
}
#if defined(__ANDROID__)
// Bugfix for red screen on Samsung S3/Mali
// https://forums.libsdl.org/viewtopic.php?t=11445
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 5 );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 6 );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 5 );
// Fix Back button crash on Android 9
#if defined(SDL_HINT_ANDROID_TRAP_BACK_BUTTON )
const bool trap_back_button = get_option<bool>( "ANDROID_TRAP_BACK_BUTTON" );
SDL_SetHint( SDL_HINT_ANDROID_TRAP_BACK_BUTTON, trap_back_button ? "1" : "0" );
#endif
// Prevent mouse|touch input confusion
#if defined(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH)
SDL_SetHint( SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1" );
#else
SDL_SetHint( SDL_HINT_MOUSE_TOUCH_EVENTS, "0" );
SDL_SetHint( SDL_HINT_TOUCH_MOUSE_EVENTS, "0" );
#endif
#endif
::window.reset( SDL_CreateWindow( version.c_str(),
SDL_WINDOWPOS_CENTERED_DISPLAY( display ),
SDL_WINDOWPOS_CENTERED_DISPLAY( display ),
WindowWidth,
WindowHeight,
window_flags
) );
throwErrorIf( !::window, "SDL_CreateWindow failed" );
#if !defined(__ANDROID__)
// On Android SDL seems janky in windowed mode so we're fullscreen all the time.
// Fullscreen mode is now modified so it obeys terminal width/height, rather than
// overwriting it with this calculation.
if( window_flags & SDL_WINDOW_FULLSCREEN || window_flags & SDL_WINDOW_FULLSCREEN_DESKTOP
|| window_flags & SDL_WINDOW_MAXIMIZED ) {
SDL_GetWindowSize( ::window.get(), &WindowWidth, &WindowHeight );
// Ignore previous values, use the whole window, but nothing more.
TERMINAL_WIDTH = WindowWidth / fontwidth / scaling_factor;
TERMINAL_HEIGHT = WindowHeight / fontheight / scaling_factor;
}
#endif
// Initialize framebuffer caches
terminal_framebuffer.resize( TERMINAL_HEIGHT );
for( int i = 0; i < TERMINAL_HEIGHT; i++ ) {
terminal_framebuffer[i].chars.assign( TERMINAL_WIDTH, cursecell( "" ) );
}
oversized_framebuffer.resize( TERMINAL_HEIGHT );
for( int i = 0; i < TERMINAL_HEIGHT; i++ ) {
oversized_framebuffer[i].chars.assign( TERMINAL_WIDTH, cursecell( "" ) );
}
const Uint32 wformat = SDL_GetWindowPixelFormat( ::window.get() );
format.reset( SDL_AllocFormat( wformat ) );
throwErrorIf( !format, "SDL_AllocFormat failed" );
int renderer_id = -1;
#if !defined(__ANDROID__)
bool software_renderer = get_option<std::string>( "RENDERER" ).empty();
std::string renderer_name;
if( software_renderer ) {
renderer_name = "software";
} else {
renderer_name = get_option<std::string>( "RENDERER" );
}
const int numRenderDrivers = SDL_GetNumRenderDrivers();
for( int i = 0; i < numRenderDrivers; i++ ) {
SDL_RendererInfo ri;
SDL_GetRenderDriverInfo( i, &ri );
if( renderer_name == ri.name ) {
renderer_id = i;
DebugLog( DL::Info, DC::Main ) << "Active renderer: " << renderer_id << "/" << ri.name;
break;
}
}
#else
bool software_renderer = get_option<bool>( "SOFTWARE_RENDERING" );
#endif
#if defined(SDL_HINT_RENDER_BATCHING)
SDL_SetHint( SDL_HINT_RENDER_BATCHING, get_option<bool>( "RENDER_BATCHING" ) ? "1" : "0" );
#endif
if( !software_renderer ) {
dbg( DL::Info ) << "Attempting to initialize accelerated SDL renderer.";
renderer.reset( SDL_CreateRenderer( ::window.get(), renderer_id, SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE ) );
if( printErrorIf( !renderer,
"Failed to initialize accelerated renderer, falling back to software rendering" ) ) {
software_renderer = true;
} else if( !SetupRenderTarget() ) {
dbg( DL::Error ) << "Failed to initialize display buffer under accelerated rendering, "
"falling back to software rendering.";
software_renderer = true;
display_buffer.reset();
renderer.reset();
}
}
if( software_renderer ) {
if( get_option<bool>( "FRAMEBUFFER_ACCEL" ) ) {
SDL_SetHint( SDL_HINT_FRAMEBUFFER_ACCELERATION, "1" );
}
renderer.reset( SDL_CreateRenderer( ::window.get(), -1,
SDL_RENDERER_SOFTWARE | SDL_RENDERER_TARGETTEXTURE ) );
throwErrorIf( !renderer, "Failed to initialize software renderer" );
throwErrorIf( !SetupRenderTarget(),
"Failed to initialize display buffer under software rendering, unable to continue." );
}
SDL_SetWindowMinimumSize( ::window.get(), fontwidth * FULL_SCREEN_WIDTH * scaling_factor,
fontheight * FULL_SCREEN_HEIGHT * scaling_factor );
#if defined(__ANDROID__)
// TODO: Not too sure why this works to make fullscreen on Android behave. :/
if( window_flags & SDL_WINDOW_FULLSCREEN || window_flags & SDL_WINDOW_FULLSCREEN_DESKTOP
|| window_flags & SDL_WINDOW_MAXIMIZED ) {
SDL_GetWindowSize( ::window.get(), &WindowWidth, &WindowHeight );
}
// Load virtual joystick texture
touch_joystick = CreateTextureFromSurface( renderer, load_image( "android/joystick.png" ) );
#endif
ClearScreen();
// Errors here are ignored, worst case: the option does not work as expected,
// but that won't crash
if( get_option<std::string>( "HIDE_CURSOR" ) != "show" && SDL_ShowCursor( -1 ) ) {
SDL_ShowCursor( SDL_DISABLE );
} else {
SDL_ShowCursor( SDL_ENABLE );
}
// Initialize joysticks.
int numjoy = SDL_NumJoysticks();
if( get_option<bool>( "ENABLE_JOYSTICK" ) && numjoy >= 1 ) {
if( numjoy > 1 ) {
dbg( DL::Warn ) << "You have more than one gamepads/joysticks plugged in, "
"only the first will be used.";
}
joystick = SDL_JoystickOpen( 0 );
printErrorIf( joystick == nullptr, "SDL_JoystickOpen failed" );
if( joystick ) {
printErrorIf( SDL_JoystickEventState( SDL_ENABLE ) < 0,
"SDL_JoystickEventState(SDL_ENABLE) failed" );
}
} else {
joystick = nullptr;
}
// Set up audio mixer.
init_sound();
dbg( DL::Info ) << "USE_COLOR_MODULATED_TEXTURES is set to " <<
get_option<bool>( "USE_COLOR_MODULATED_TEXTURES" );
//initialize the alternate rectangle texture for replacing SDL_RenderFillRect
if( get_option<bool>( "USE_COLOR_MODULATED_TEXTURES" ) && !software_renderer ) {
geometry = std::make_unique<ColorModulatedGeometryRenderer>( renderer );
} else {
geometry = std::make_unique<DefaultGeometryRenderer>();
}
}
static void WinDestroy()
{
#if defined(__ANDROID__)
touch_joystick.reset();
#endif
shutdown_sound();
tilecontext.reset();
if( joystick ) {
SDL_JoystickClose( joystick );
joystick = nullptr;
}
geometry.reset();
format.reset();
display_buffer.reset();
renderer.reset();
::window.reset();
}
/// Converts a color from colorscheme to SDL_Color.
inline const SDL_Color &color_as_sdl( const unsigned char color )
{
return windowsPalette[color];
}
#if defined(__ANDROID__)
void draw_terminal_size_preview();
void draw_quick_shortcuts();
void draw_virtual_joystick();
static bool quick_shortcuts_enabled = true;
// For previewing the terminal size with a transparent rectangle overlay when user is adjusting it in the settings
static int preview_terminal_width = -1;
static int preview_terminal_height = -1;
static uint32_t preview_terminal_change_time = 0;
extern "C" {
static bool visible_display_frame_dirty = false;
static bool has_visible_display_frame = false;
static SDL_Rect visible_display_frame;
JNIEXPORT void JNICALL Java_org_libsdl_app_SDLActivity_onNativeVisibleDisplayFrameChanged(
JNIEnv *env, jclass jcls, jint left, jint top, jint right, jint bottom )
{
( void )env; // unused
( void )jcls; // unused
has_visible_display_frame = true;
visible_display_frame_dirty = true;
visible_display_frame.x = left;
visible_display_frame.y = top;
visible_display_frame.w = right - left;
visible_display_frame.h = bottom - top;
}
} // "C"
SDL_Rect get_android_render_rect( float DisplayBufferWidth, float DisplayBufferHeight )
{
// If the display buffer aspect ratio is wider than the display,
// draw it at the top of the screen so it doesn't get covered up
// by the virtual keyboard. Otherwise just center it.
SDL_Rect dstrect;
float DisplayBufferAspect = DisplayBufferWidth / ( float )DisplayBufferHeight;
float WindowHeightLessShortcuts = ( float )WindowHeight;
if( !get_option<bool>( "ANDROID_SHORTCUT_OVERLAP" ) && quick_shortcuts_enabled ) {
WindowHeightLessShortcuts -= get_option<int>( "ANDROID_SHORTCUT_HEIGHT" );
}
float WindowAspect = WindowWidth / ( float )WindowHeightLessShortcuts;
if( WindowAspect < DisplayBufferAspect ) {
dstrect.x = 0;
dstrect.y = 0;
dstrect.w = WindowWidth;
dstrect.h = WindowWidth / DisplayBufferAspect;
} else {
dstrect.x = 0.5f * ( WindowWidth - ( WindowHeightLessShortcuts * DisplayBufferAspect ) );
dstrect.y = 0;
dstrect.w = WindowHeightLessShortcuts * DisplayBufferAspect;
dstrect.h = WindowHeightLessShortcuts;
}
// Make sure the destination rectangle fits within the visible area
if( get_option<bool>( "ANDROID_KEYBOARD_SCREEN_SCALE" ) && has_visible_display_frame ) {
int vdf_right = visible_display_frame.x + visible_display_frame.w;
int vdf_bottom = visible_display_frame.y + visible_display_frame.h;
if( vdf_right < dstrect.x + dstrect.w ) {
dstrect.w = vdf_right - dstrect.x;
}
if( vdf_bottom < dstrect.y + dstrect.h ) {
dstrect.h = vdf_bottom - dstrect.y;
}
}
return dstrect;
}
#endif
void refresh_display()
{
needupdate = false;
lastupdate = SDL_GetTicks();
if( test_mode ) {
return;
}
// Select default target (the window), copy rendered buffer
// there, present it, select the buffer as target again.
SetRenderTarget( renderer, nullptr );
ClearScreen();
#if defined(__ANDROID__)
SDL_Rect dstrect = get_android_render_rect( TERMINAL_WIDTH * fontwidth,
TERMINAL_HEIGHT * fontheight );
RenderCopy( renderer, display_buffer, NULL, &dstrect );
#else
RenderCopy( renderer, display_buffer, nullptr, nullptr );
#endif
#if defined(__ANDROID__)
draw_terminal_size_preview();
draw_quick_shortcuts();
draw_virtual_joystick();
#endif
SDL_RenderPresent( renderer.get() );
SetRenderTarget( renderer, display_buffer );
}
// only update if the set interval has elapsed
static void try_sdl_update()
{
uint32_t now = SDL_GetTicks();
if( now - lastupdate >= interval ) {
refresh_display();
} else {
needupdate = true;
}
}
//for resetting the render target after updating texture caches in cata_tiles.cpp
void set_displaybuffer_rendertarget()
{
SetRenderTarget( renderer, display_buffer );
}
static void invalidate_framebuffer( std::vector<curseline> &framebuffer, point p, int width,
int height )
{
for( int j = 0, fby = p.y; j < height; j++, fby++ ) {
std::fill_n( framebuffer[fby].chars.begin() + p.x, width, cursecell( "" ) );
}
}
static void invalidate_framebuffer( std::vector<curseline> &framebuffer )
{
for( curseline &i : framebuffer ) {
std::fill_n( i.chars.begin(), i.chars.size(), cursecell( "" ) );
}
}
void reinitialize_framebuffer( const bool force_invalidate )
{
static int prev_height = -1;
static int prev_width = -1;
//Re-initialize the framebuffer with new values.
const int new_height = std::max( { TERMY, OVERMAP_WINDOW_HEIGHT, TERRAIN_WINDOW_HEIGHT } );
const int new_width = std::max( { TERMX, OVERMAP_WINDOW_WIDTH, TERRAIN_WINDOW_WIDTH } );
if( new_height != prev_height || new_width != prev_width ) {
prev_height = new_height;
prev_width = new_width;
oversized_framebuffer.resize( new_height );
for( int i = 0; i < new_height; i++ ) {
oversized_framebuffer[i].chars.assign( new_width, cursecell( "" ) );
}
terminal_framebuffer.resize( new_height );
for( int i = 0; i < new_height; i++ ) {
terminal_framebuffer[i].chars.assign( new_width, cursecell( "" ) );
}
} else if( force_invalidate || need_invalidate_framebuffers ) {
need_invalidate_framebuffers = false;
invalidate_framebuffer( oversized_framebuffer );
invalidate_framebuffer( terminal_framebuffer );
}
}
static void invalidate_framebuffer_proportion( cata_cursesport::WINDOW *win )
{
const int oversized_width = std::max( TERMX, std::max( OVERMAP_WINDOW_WIDTH,
TERRAIN_WINDOW_WIDTH ) );
const int oversized_height = std::max( TERMY, std::max( OVERMAP_WINDOW_HEIGHT,
TERRAIN_WINDOW_HEIGHT ) );
// check if the framebuffers/windows have been prepared yet
if( oversized_height == 0 || oversized_width == 0 ) {
return;
}
if( !g || win == nullptr ) {
return;
}
if( win == g->w_overmap || win == g->w_terrain ) {
return;
}
// track the dimensions for conversion
const point termpixel( win->pos.x * font->width, win->pos.y * font->height );
const int termpixel_x2 = termpixel.x + win->width * font->width - 1;
const int termpixel_y2 = termpixel.y + win->height * font->height - 1;
if( map_font != nullptr && map_font->width != 0 && map_font->height != 0 ) {
const int mapfont_x = termpixel.x / map_font->width;
const int mapfont_y = termpixel.y / map_font->height;
const int mapfont_x2 = std::min( termpixel_x2 / map_font->width, oversized_width - 1 );
const int mapfont_y2 = std::min( termpixel_y2 / map_font->height, oversized_height - 1 );
const int mapfont_width = mapfont_x2 - mapfont_x + 1;
const int mapfont_height = mapfont_y2 - mapfont_y + 1;
invalidate_framebuffer( oversized_framebuffer, point( mapfont_x, mapfont_y ), mapfont_width,
mapfont_height );
}
if( overmap_font != nullptr && overmap_font->width != 0 && overmap_font->height != 0 ) {
const int overmapfont_x = termpixel.x / overmap_font->width;
const int overmapfont_y = termpixel.y / overmap_font->height;
const int overmapfont_x2 = std::min( termpixel_x2 / overmap_font->width, oversized_width - 1 );
const int overmapfont_y2 = std::min( termpixel_y2 / overmap_font->height,
oversized_height - 1 );
const int overmapfont_width = overmapfont_x2 - overmapfont_x + 1;
const int overmapfont_height = overmapfont_y2 - overmapfont_y + 1;
invalidate_framebuffer( oversized_framebuffer, point( overmapfont_x, overmapfont_y ),
overmapfont_width,
overmapfont_height );
}
}
// clear the framebuffer when werase is called on certain windows that don't use the main terminal font
void cata_cursesport::handle_additional_window_clear( WINDOW *win )
{
if( !g ) {
return;
}
if( win == g->w_terrain || win == g->w_overmap ) {
invalidate_framebuffer( oversized_framebuffer );
}
}
void clear_window_area( const catacurses::window &win_ )
{
cata_cursesport::WINDOW *const win = win_.get<cata_cursesport::WINDOW>();
geometry->rect( renderer, point( win->pos.x * fontwidth, win->pos.y * fontheight ),
win->width * fontwidth, win->height * fontheight, color_as_sdl( catacurses::black ) );
}
static std::optional<std::pair<tripoint_abs_omt, std::string>> get_mission_arrow(
const inclusive_cuboid<tripoint> &overmap_area, const tripoint_abs_omt ¢er )
{
if( get_avatar().get_active_mission() == nullptr ) {
return std::nullopt;
}
if( !get_avatar().get_active_mission()->has_target() ) {
return std::nullopt;
}
const tripoint_abs_omt mission_target = get_avatar().get_active_mission_target();
std::string mission_arrow_variant;
if( overmap_area.contains( mission_target.raw() ) ) {
mission_arrow_variant = "mission_cursor";
return std::make_pair( mission_target, mission_arrow_variant );
}
inclusive_rectangle<point> area_flat( overmap_area.p_min.xy(), overmap_area.p_max.xy() );
if( area_flat.contains( mission_target.raw().xy() ) ) {
int area_z = center.z();
if( mission_target.z() > area_z ) {
mission_arrow_variant = "mission_arrow_up";
} else {
mission_arrow_variant = "mission_arrow_down";
}
return std::make_pair( tripoint_abs_omt( mission_target.xy(), area_z ), mission_arrow_variant );
}
const std::vector<tripoint> traj = line_to( center.raw(),
tripoint( mission_target.raw().xy(), center.raw().z ) );
if( traj.empty() ) {
debugmsg( "Failed to gen overmap mission trajectory %s %s",
center.to_string(), mission_target.to_string() );
return std::nullopt;
}
tripoint arr_pos = traj[0];
for( auto it = traj.rbegin(); it != traj.rend(); it++ ) {
if( overmap_area.contains( *it ) ) {
arr_pos = *it;
break;
}
}
const int north_border_y = ( overmap_area.p_max.y - overmap_area.p_min.y ) / 3;
const int south_border_y = north_border_y * 2;
const int west_border_x = ( overmap_area.p_max.x - overmap_area.p_min.x ) / 3;
const int east_border_x = west_border_x * 2;
tripoint north_pmax( overmap_area.p_max );
north_pmax.y = overmap_area.p_min.y + north_border_y;
tripoint south_pmin( overmap_area.p_min );
south_pmin.y += south_border_y;
tripoint west_pmax( overmap_area.p_max );
west_pmax.x = overmap_area.p_min.x + west_border_x;
tripoint east_pmin( overmap_area.p_min );
east_pmin.x += east_border_x;
const inclusive_cuboid<tripoint> north_sector( overmap_area.p_min, north_pmax );
const inclusive_cuboid<tripoint> south_sector( south_pmin, overmap_area.p_max );
const inclusive_cuboid<tripoint> west_sector( overmap_area.p_min, west_pmax );
const inclusive_cuboid<tripoint> east_sector( east_pmin, overmap_area.p_max );
mission_arrow_variant = "mission_arrow_";
if( north_sector.contains( arr_pos ) ) {
mission_arrow_variant += 'n';
} else if( south_sector.contains( arr_pos ) ) {
mission_arrow_variant += 's';
}
if( west_sector.contains( arr_pos ) ) {
mission_arrow_variant += 'w';
} else if( east_sector.contains( arr_pos ) ) {
mission_arrow_variant += 'e';
}
return std::make_pair( tripoint_abs_omt( arr_pos ), mission_arrow_variant );
}
std::string cata_tiles::get_omt_id_rotation_and_subtile(
const tripoint_abs_omt &omp, int &rota, int &subtile )
{
auto oter_at = []( const tripoint_abs_omt & p ) {
const oter_id &cur_ter = overmap_buffer.ter( p );
if( !uistate.overmap_show_forest_trails &&
is_ot_match( "forest_trail", cur_ter, ot_match_type::type ) ) {
return oter_id( "forest" );
}
return cur_ter;
};
oter_id ot_id = oter_at( omp );
const oter_t &ot = *ot_id;
oter_type_id ot_type_id = ot.get_type_id();
oter_type_t ot_type = *ot_type_id;
if( ot_type.has_connections() ) {
// This would be for connected terrain
// get terrain neighborhood
const oter_type_id neighborhood[4] = {
oter_at( omp + point_south )->get_type_id(),
oter_at( omp + point_east )->get_type_id(),
oter_at( omp + point_west )->get_type_id(),
oter_at( omp + point_north )->get_type_id()
};
char val = 0;
// populate connection information
for( int i = 0; i < 4; ++i ) {
if( ot_type.connects_to( neighborhood[i] ) ) {
val += 1 << i;
}
}
get_rotation_and_subtile( val, rota, subtile );
} else {
// 'Regular', nonlinear terrain only needs to worry about rotation, not
// subtile
ot.get_rotation_and_subtile( rota, subtile );
}
return ot_type_id.id().str();
}
static point draw_string( Font &font,
const SDL_Renderer_Ptr &renderer,
const GeometryRenderer_Ptr &geometry,
const std::string &str,
point p,
const unsigned char color )
{
const char *cstr = str.c_str();
int len = str.length();
while( len > 0 ) {
const uint32_t ch32 = UTF8_getch( &cstr, &len );
const std::string ch = utf32_to_utf8( ch32 );
font.OutputChar( renderer, geometry, ch, p, color );
p.x += mk_wcwidth( ch32 ) * font.width;
}
return p;
}
void cata_tiles::draw_om( point dest, const tripoint_abs_omt ¢er_abs_omt, bool blink )
{
if( !g ) {
return;
}
#if defined(__ANDROID__)
// Attempted bugfix for Google Play crash - prevent divide-by-zero if no tile
// width/height specified
if( tile_width == 0 || tile_height == 0 ) {
return;
}
#endif
int width = OVERMAP_WINDOW_TERM_WIDTH * font->width;
int height = OVERMAP_WINDOW_TERM_HEIGHT * font->height;
{
//set clipping to prevent drawing over stuff we shouldn't
SDL_Rect clipRect = { dest.x, dest.y, width, height };
printErrorIf( SDL_RenderSetClipRect( renderer.get(), &clipRect ) != 0,
"SDL_RenderSetClipRect failed" );
//fill render area with black to prevent artifacts where no new pixels are drawn
geometry->rect( renderer, clipRect, SDL_Color() );
}
op = point( dest.x * fontwidth, dest.y * fontheight );
// Rounding up to include incomplete tiles at the bottom/right edges
screentile_width = divide_round_up( width, tile_width );
screentile_height = divide_round_up( height, tile_height );
window_dimensions wnd_dim = get_window_dimensions( g->w_overmap );
const int min_col = 0;
const int max_col = screentile_width;
const int min_row = 0;
const int max_row = screentile_height;
int height_3d = 0;
avatar &you = get_avatar();
const tripoint_abs_omt avatar_pos = you.global_omt_location();
const tripoint_abs_omt corner_NW = center_abs_omt - point( wnd_dim.window_size_cell.x / 2,
wnd_dim.window_size_cell.y / 2 );
const tripoint_abs_omt corner_SE = corner_NW + point( max_col - 1, max_row - 1 );
const inclusive_cuboid<tripoint> overmap_area( corner_NW.raw(), corner_SE.raw() );
// Debug vision allows seeing everything
const bool has_debug_vision = you.has_trait( trait_id( "DEBUG_NIGHTVISION" ) );
// sight_points is hoisted for speed reasons.
const int sight_points = !has_debug_vision ?
you.overmap_sight_range( g->light_level( you.posz() ) ) :
100;
const bool showhordes = uistate.overmap_show_hordes;
const bool viewing_weather = ( ( uistate.overmap_debug_weather || uistate.overmap_visible_weather )
&& center_abs_omt.z() >= 0 );
o = corner_NW.raw().xy();
const auto global_omt_to_draw_position = []( const tripoint_abs_omt & omp ) {
// z position is hardcoded to 0 because the things this will be used to draw should not be skipped
return tripoint( omp.raw().xy(), 0 );
};
for( int row = min_row; row < max_row; row++ ) {
for( int col = min_col; col < max_col; col++ ) {
const tripoint_abs_omt omp = corner_NW + point( col, row );
const bool see = has_debug_vision || overmap_buffer.seen( omp );
const bool los = see && you.overmap_los( omp, sight_points );
// the full string from the ter_id including _north etc.
std::string id;
int rotation = 0;
int subtile = -1;
if( viewing_weather ) {
const tripoint_abs_omt omp_sky( omp.xy(), OVERMAP_HEIGHT );
if( uistate.overmap_debug_weather ||
you.overmap_los( omp_sky, sight_points * 2 ) ) {
id = overmap_ui::get_weather_at_point( omp_sky.xy() ).c_str();
}
}
if( id.empty() ) {
if( see ) {
id = get_omt_id_rotation_and_subtile( omp, rotation, subtile );
} else {
id = "unknown_terrain";
}
}
const lit_level ll = overmap_buffer.is_explored( omp ) ? lit_level::LOW : lit_level::LIT;
// light level is now used for choosing between grayscale filter and normal lit tiles.
draw_from_id_string( id, TILE_CATEGORY::C_OVERMAP_TERRAIN, "overmap_terrain", omp.raw(),
subtile, rotation, ll, false, height_3d, 0 );
if( see ) {
if( blink && uistate.overmap_debug_mongroup ) {
const std::vector<mongroup *> mgroups = overmap_buffer.monsters_at( omp );
if( !mgroups.empty() ) {
auto mgroup_iter = mgroups.begin();
std::advance( mgroup_iter, rng( 0, mgroups.size() - 1 ) );
draw_from_id_string( ( *mgroup_iter )->type->defaultMonster.str(),
omp.raw(), 0, 0, lit_level::LIT, false, 0 );
}
}
const int horde_size = overmap_buffer.get_horde_size( omp );
if( showhordes && los && horde_size >= HORDE_VISIBILITY_SIZE ) {
// a little bit of hardcoded fallbacks for hordes
if( find_tile_with_season( id ) ) {
draw_from_id_string( string_format( "overmap_horde_%d", horde_size ),
omp.raw(), 0, 0, lit_level::LIT, false, 0 );
} else {
switch( horde_size ) {
case HORDE_VISIBILITY_SIZE:
draw_from_id_string( "mon_zombie", omp.raw(), 0, 0, lit_level::LIT,
false, 0 );
break;
case HORDE_VISIBILITY_SIZE + 1:
draw_from_id_string( "mon_zombie_tough", omp.raw(), 0, 0,
lit_level::LIT, false, 0 );
break;
case HORDE_VISIBILITY_SIZE + 2:
draw_from_id_string( "mon_zombie_brute", omp.raw(), 0, 0,
lit_level::LIT, false, 0 );
break;
case HORDE_VISIBILITY_SIZE + 3:
draw_from_id_string( "mon_zombie_hulk", omp.raw(), 0, 0,
lit_level::LIT, false, 0 );
break;
case HORDE_VISIBILITY_SIZE + 4:
draw_from_id_string( "mon_zombie_necro", omp.raw(), 0, 0,
lit_level::LIT, false, 0 );
break;
default:
draw_from_id_string( "mon_zombie_master", omp.raw(), 0, 0,
lit_level::LIT, false, 0 );
break;
}
}
}
}
if( uistate.place_terrain || uistate.place_special ) {
// Highlight areas that already have been generated
// TODO: fix point types
if( MAPBUFFER.lookup_submap( project_to<coords::sm>( omp ).raw() ) ) {
draw_from_id_string( "highlight", omp.raw(), 0, 0, lit_level::LIT, false, 0 );
}
}
if( blink && overmap_buffer.has_vehicle( omp ) ) {
if( find_tile_looks_like( "overmap_remembered_vehicle", TILE_CATEGORY::C_OVERMAP_NOTE ) ) {
draw_from_id_string( "overmap_remembered_vehicle", TILE_CATEGORY::C_OVERMAP_NOTE,
"overmap_note", omp.raw(), 0, 0, lit_level::LIT, false, 0 );
} else {
draw_from_id_string( "note_c_cyan", TILE_CATEGORY::C_OVERMAP_NOTE,
"overmap_note", omp.raw(), 0, 0, lit_level::LIT, false, 0 );
}
}
if( blink && uistate.overmap_show_map_notes && overmap_buffer.has_note( omp ) ) {
nc_color ter_color = c_black;
std::string ter_sym = " ";
// Display notes in all situations, even when not seen
std::tie( ter_sym, ter_color, std::ignore ) =
overmap_ui::get_note_display_info( overmap_buffer.note( omp ) );
std::string note_name = "note_" + ter_sym + "_" + string_from_color( ter_color );
draw_from_id_string( note_name, TILE_CATEGORY::C_OVERMAP_NOTE, "overmap_note",
omp.raw(), 0, 0, lit_level::LIT, false, 0 );
}
}
}