-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathdraw.cpp
2908 lines (2560 loc) · 102 KB
/
draw.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
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include "aastr.h"
#include "core/platform.h"
#include "ac/common.h"
#include "util/compress.h"
#include "ac/view.h"
#include "ac/characterextras.h"
#include "ac/characterinfo.h"
#include "ac/display.h"
#include "ac/draw.h"
#include "ac/draw_software.h"
#include "ac/gamesetup.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/global_game.h"
#include "ac/global_gui.h"
#include "ac/global_region.h"
#include "ac/gui.h"
#include "ac/mouse.h"
#include "ac/movelist.h"
#include "ac/overlay.h"
#include "ac/sys_events.h"
#include "ac/roomobject.h"
#include "ac/roomstatus.h"
#include "ac/runtime_defines.h"
#include "ac/screenoverlay.h"
#include "ac/sprite.h"
#include "ac/string.h"
#include "ac/system.h"
#include "ac/viewframe.h"
#include "ac/walkablearea.h"
#include "ac/walkbehind.h"
#include "ac/dynobj/scriptsystem.h"
#include "debug/debugger.h"
#include "debug/debug_log.h"
#include "font/fonts.h"
#include "gui/guimain.h"
#include "gui/guiobject.h"
#include "platform/base/agsplatformdriver.h"
#include "plugin/agsplugin.h"
#include "plugin/plugin_engine.h"
#include "ac/spritecache.h"
#include "gfx/gfx_util.h"
#include "gfx/graphicsdriver.h"
#include "gfx/ali3dexception.h"
#include "gfx/blender.h"
#include "media/audio/audio_system.h"
#include "ac/game.h"
#include "util/wgt2allg.h"
using namespace AGS::Common;
using namespace AGS::Engine;
extern GameSetupStruct game;
extern GameState play;
extern ScriptSystem scsystem;
extern AGSPlatformDriver *platform;
extern RoomStruct thisroom;
extern unsigned int loopcounter;
extern SpriteCache spriteset;
extern RoomStatus*croom;
extern int our_eip;
extern int in_new_room;
extern RoomObject*objs;
extern std::vector<ViewStruct> views;
extern int displayed_room;
extern CharacterInfo*playerchar;
extern int eip_guinum;
extern int cur_mode,cur_cursor;
extern int mouse_frame,mouse_delay;
extern int lastmx,lastmy;
extern IDriverDependantBitmap *mouseCursor;
extern int hotx,hoty;
extern int bg_just_changed;
RGB palette[256];
COLOR_MAP maincoltable;
IGraphicsDriver *gfxDriver = nullptr;
IDriverDependantBitmap *blankImage = nullptr;
IDriverDependantBitmap *blankSidebarImage = nullptr;
IDriverDependantBitmap *debugConsole = nullptr;
// ObjTexture is a helper struct that pairs a raw bitmap with
// a renderer's texture and an optional position
struct ObjTexture
{
// Sprite ID
uint32_t SpriteID = UINT32_MAX;
// Raw bitmap; used for software render mode,
// or when particular object types require generated image.
std::unique_ptr<Bitmap> Bmp;
// Corresponding texture, created by renderer
IDriverDependantBitmap *Ddb = nullptr;
// Sprite's position
Point Pos;
// Texture's offset, *relative* to the logical sprite's position;
// may be used in case the texture's size is different for any reason
Point Off;
ObjTexture() = default;
ObjTexture(uint32_t sprite_id, Bitmap *bmp, IDriverDependantBitmap *ddb, int x, int y, int xoff = 0, int yoff = 0)
: SpriteID(sprite_id), Bmp(bmp), Ddb(ddb), Pos(x, y), Off(xoff, yoff) {}
ObjTexture(const ObjTexture&) = default;
ObjTexture(ObjTexture &&o) { *this = std::move(o); }
~ObjTexture()
{
Bmp.reset();
if (Ddb)
{
assert(gfxDriver);
gfxDriver->DestroyDDB(Ddb);
}
}
ObjTexture &operator =(ObjTexture &&o)
{
SpriteID = o.SpriteID;
if (Ddb)
{
assert(gfxDriver);
gfxDriver->DestroyDDB(Ddb);
}
Bmp = std::move(o.Bmp);
Ddb = o.Ddb;
o.Ddb = nullptr;
Pos = o.Pos;
Off = o.Off;
return *this;
}
};
// ObjectCache stores cached object data, used to determine
// if active sprite / texture should be reconstructed
struct ObjectCache
{
std::unique_ptr<Bitmap> image;
bool in_use = false;
int sppic = 0;
short tintr = 0, tintg = 0, tintb = 0, tintamnt = 0, tintlight = 0;
short lightlev = 0, zoom = 0;
bool mirrored = 0;
int x = 0, y = 0;
};
// actsps is used for temporary storage of the bitmap and texture
// of the latest version of the sprite (room objects and characters);
// objects sprites begin with index 0, characters are after MAX_ROOM_OBJECTS
std::vector<ObjTexture> actsps;
// Walk-behind textures (3D renderers only)
std::vector<ObjTexture> walkbehindobj;
// GUI surfaces
std::vector<ObjTexture> guibg;
// GUI render texture, for rendering all controls on same texture buffer
std::vector<IDriverDependantBitmap*> gui_render_tex;
// GUI control surfaces
std::vector<ObjTexture> guiobjbg;
// first control texture index of each GUI
std::vector<int> guiobjddbref;
// Overlay's cached transformed bitmap, for software mode
std::vector<std::unique_ptr<Bitmap>> overlaybmp;
// For debugging room masks
RoomAreaMask debugRoomMask = kRoomAreaNone;
ObjTexture debugRoomMaskObj;
int debugMoveListChar = -1;
ObjTexture debugMoveListObj;
// Cached character and object states, used to determine
// whether these require texture update
std::vector<ObjectCache> charcache;
ObjectCache objcache[MAX_ROOM_OBJECTS];
std::vector<Point> screenovercache;
bool current_background_is_dirty = false;
// Room background sprite
IDriverDependantBitmap* roomBackgroundBmp = nullptr;
// Buffer and info flags for viewport/camera pairs rendering in software mode
struct RoomCameraDrawData
{
// Intermediate bitmap for the software drawing method.
// We use this bitmap in case room camera has scaling enabled, we draw dirty room rects on it,
// and then pass to software renderer which draws sprite on top and then either blits or stretch-blits
// to the virtual screen.
// For more details see comment in ALSoftwareGraphicsDriver::RenderToBackBuffer().
PBitmap Buffer; // this is the actual bitmap
PBitmap Frame; // this is either same bitmap reference or sub-bitmap of virtual screen
bool IsOffscreen; // whether room viewport was offscreen (cannot use sub-bitmap)
bool IsOverlap; // whether room viewport overlaps any others (marking dirty rects is complicated)
};
std::vector<RoomCameraDrawData> CameraDrawData;
// Describes a texture or node description, for sorting and passing into renderer
struct SpriteListEntry
{
int id = -1; // user identifier, for any custom purpose
IDriverDependantBitmap *ddb = nullptr;
int x = 0, y = 0;
int zorder = 0;
// Tells if this item should take priority during sort if z1 == z2
// TODO: this is some compatibility feature - find out if may be omited and done without extra struct?
bool takesPriorityIfEqual = false;
// Mark for the render stage callback (if >= 0 other fields are ignored)
int renderStage = -1;
};
// Two lists of sprites to push into renderer during next render pass
// thingsToDrawList - is the main list, unsorted, drawn in the index order
std::vector<SpriteListEntry> thingsToDrawList;
// sprlist - will be sorted using baseline and appended to main list
std::vector<SpriteListEntry> sprlist;
Bitmap *debugConsoleBuffer = nullptr;
// whether there are currently remnants of a DisplaySpeech
bool screen_is_dirty = false;
Bitmap *raw_saved_screen = nullptr;
Bitmap *dynamicallyCreatedSurfaces[MAX_DYNAMIC_SURFACES];
void setpal() {
set_palette_range(palette, 0, 255, 0);
}
int _places_r = 3, _places_g = 2, _places_b = 3;
// PSP: convert 32 bit RGB to BGR.
Bitmap *convert_32_to_32bgr(Bitmap *tempbl) {
int i = 0;
int j = 0;
unsigned char* current;
while (i < tempbl->GetHeight())
{
current = tempbl->GetScanLineForWriting(i);
while (j < tempbl->GetWidth())
{
current[0] ^= current[2];
current[2] ^= current[0];
current[0] ^= current[2];
current += 4;
j++;
}
i++;
j = 0;
}
return tempbl;
}
// NOTE: Some of these conversions are required even when using
// D3D and OpenGL rendering, for two reasons:
// 1) certain raw drawing operations are still performed by software
// Allegro methods, hence bitmaps should be kept compatible to any native
// software operations, such as blitting two bitmaps of different formats.
// 2) mobile ports feature an OpenGL renderer built in Allegro library,
// that assumes native bitmaps are in OpenGL-compatible format, so that it
// could copy them to texture without additional changes.
// AGS own OpenGL renderer tries to sync its behavior with the former one.
//
// TODO: make gfxDriver->GetCompatibleBitmapFormat describe all necessary
// conversions, so that we did not have to guess.
//
Bitmap *AdjustBitmapForUseWithDisplayMode(Bitmap* bitmap, bool has_alpha)
{
const int bmp_col_depth = bitmap->GetColorDepth();
const int game_col_depth = game.GetColorDepth();
const int compat_col_depth = gfxDriver->GetCompatibleBitmapFormat(game_col_depth);
const bool must_switch_palette = bitmap->GetColorDepth() == 8 && game_col_depth > 8;
if (must_switch_palette)
select_palette(palette);
Bitmap *new_bitmap = bitmap;
//
// The only special case when bitmap needs to be prepared for graphics driver
//
// In 32-bit display mode, 32-bit bitmaps may require component conversion
// to match graphics driver expectation about pixel format.
// TODO: make GetCompatibleBitmapFormat tell this somehow
#if defined (AGS_INVERTED_COLOR_ORDER)
const int sys_col_depth = System_GetColorDepth();
if (sys_col_depth > 16 && bmp_col_depth == 32)
{
// Convert RGB to BGR.
new_bitmap = convert_32_to_32bgr(bitmap);
}
#endif
//
// The rest is about bringing bitmaps to the native game's format
// (has no dependency on display mode).
//
// In 32-bit game 32-bit bitmaps should have transparent pixels marked
// (this adjustment is probably needed for DrawingSurface ops)
if (game_col_depth == 32 && bmp_col_depth == 32)
{
if (has_alpha)
set_rgb_mask_using_alpha_channel(new_bitmap);
}
// In 32-bit game hicolor bitmaps must be converted to the true color
else if (game_col_depth == 32 && (bmp_col_depth > 8 && bmp_col_depth <= 16))
{
new_bitmap = BitmapHelper::CreateBitmapCopy(bitmap, compat_col_depth);
}
// In non-32-bit game truecolor bitmaps must be downgraded
else if (game_col_depth <= 16 && bmp_col_depth > 16)
{
if (has_alpha) // if has valid alpha channel, convert it to regular transparency mask
new_bitmap = remove_alpha_channel(bitmap);
else // else simply convert bitmap
new_bitmap = BitmapHelper::CreateBitmapCopy(bitmap, compat_col_depth);
}
// Finally, if we did not create a new copy already, - convert to driver compatible format
if (new_bitmap == bitmap)
new_bitmap = GfxUtil::ConvertBitmap(bitmap, gfxDriver->GetCompatibleBitmapFormat(bitmap->GetColorDepth()));
if (must_switch_palette)
unselect_palette();
return new_bitmap;
}
Bitmap *CreateCompatBitmap(int width, int height, int col_depth)
{
return new Bitmap(width, height,
gfxDriver->GetCompatibleBitmapFormat(col_depth == 0 ? game.GetColorDepth() : col_depth));
}
Bitmap *ReplaceBitmapWithSupportedFormat(Bitmap *bitmap)
{
return GfxUtil::ConvertBitmap(bitmap, gfxDriver->GetCompatibleBitmapFormat(bitmap->GetColorDepth()));
}
Bitmap *PrepareSpriteForUse(Bitmap* bitmap, bool has_alpha)
{
Bitmap *new_bitmap = AdjustBitmapForUseWithDisplayMode(bitmap, has_alpha);
if (new_bitmap != bitmap)
delete bitmap;
return new_bitmap;
}
PBitmap PrepareSpriteForUse(PBitmap bitmap, bool has_alpha)
{
Bitmap *new_bitmap = AdjustBitmapForUseWithDisplayMode(bitmap.get(), has_alpha);
return new_bitmap == bitmap.get() ? bitmap : PBitmap(new_bitmap); // if bitmap is same, don't create new smart ptr!
}
Bitmap *CopyScreenIntoBitmap(int width, int height, bool at_native_res)
{
Bitmap *dst = new Bitmap(width, height, game.GetColorDepth());
GraphicResolution want_fmt;
// If the size and color depth are supported we may copy right into our bitmap
if (gfxDriver->GetCopyOfScreenIntoBitmap(dst, at_native_res, &want_fmt))
return dst;
// Otherwise we might need to copy between few bitmaps...
Bitmap *buf_screenfmt = new Bitmap(want_fmt.Width, want_fmt.Height, want_fmt.ColorDepth);
gfxDriver->GetCopyOfScreenIntoBitmap(buf_screenfmt, at_native_res);
// If at least size matches then we may blit
if (dst->GetSize() == buf_screenfmt->GetSize())
{
dst->Blit(buf_screenfmt);
}
// Otherwise we need to go through another bitmap of the matching format
else
{
Bitmap *buf_dstfmt = new Bitmap(buf_screenfmt->GetWidth(), buf_screenfmt->GetHeight(), dst->GetColorDepth());
buf_dstfmt->Blit(buf_screenfmt);
dst->StretchBlt(buf_dstfmt, RectWH(dst->GetSize()));
delete buf_dstfmt;
}
delete buf_screenfmt;
return dst;
}
// Begin resolution system functions
// Multiplies up the number of pixels depending on the current
// resolution, to give a relatively fixed size at any game res
AGS_INLINE int get_fixed_pixel_size(int pixels)
{
return pixels * game.GetRelativeUIMult();
}
AGS_INLINE int data_to_game_coord(int coord)
{
return coord * game.GetDataUpscaleMult();
}
AGS_INLINE void data_to_game_coords(int *x, int *y)
{
const int mul = game.GetDataUpscaleMult();
x[0] *= mul;
y[0] *= mul;
}
AGS_INLINE void data_to_game_round_up(int *x, int *y)
{
const int mul = game.GetDataUpscaleMult();
x[0] = x[0] * mul + (mul - 1);
y[0] = y[0] * mul + (mul - 1);
}
AGS_INLINE int game_to_data_coord(int coord)
{
return coord / game.GetDataUpscaleMult();
}
AGS_INLINE void game_to_data_coords(int &x, int &y)
{
const int mul = game.GetDataUpscaleMult();
x /= mul;
y /= mul;
}
AGS_INLINE int game_to_data_round_up(int coord)
{
const int mul = game.GetDataUpscaleMult();
return (coord / mul) + (mul - 1);
}
AGS_INLINE void ctx_data_to_game_coord(int &x, int &y, bool hires_ctx)
{
if (hires_ctx && !game.IsLegacyHiRes())
{
x /= HIRES_COORD_MULTIPLIER;
y /= HIRES_COORD_MULTIPLIER;
}
else if (!hires_ctx && game.IsLegacyHiRes())
{
x *= HIRES_COORD_MULTIPLIER;
y *= HIRES_COORD_MULTIPLIER;
}
}
AGS_INLINE void ctx_data_to_game_size(int &w, int &h, bool hires_ctx)
{
if (hires_ctx && !game.IsLegacyHiRes())
{
w = std::max(1, (w / HIRES_COORD_MULTIPLIER));
h = std::max(1, (h / HIRES_COORD_MULTIPLIER));
}
else if (!hires_ctx && game.IsLegacyHiRes())
{
w *= HIRES_COORD_MULTIPLIER;
h *= HIRES_COORD_MULTIPLIER;
}
}
AGS_INLINE int ctx_data_to_game_size(int size, bool hires_ctx)
{
if (hires_ctx && !game.IsLegacyHiRes())
return std::max(1, (size / HIRES_COORD_MULTIPLIER));
if (!hires_ctx && game.IsLegacyHiRes())
return size * HIRES_COORD_MULTIPLIER;
return size;
}
AGS_INLINE int game_to_ctx_data_size(int size, bool hires_ctx)
{
if (hires_ctx && !game.IsLegacyHiRes())
return size * HIRES_COORD_MULTIPLIER;
else if (!hires_ctx && game.IsLegacyHiRes())
return std::max(1, (size / HIRES_COORD_MULTIPLIER));
return size;
}
AGS_INLINE void defgame_to_finalgame_coords(int &x, int &y)
{ // Note we support only upscale now
x *= game.GetScreenUpscaleMult();
y *= game.GetScreenUpscaleMult();
}
// End resolution system functions
// Create blank (black) images used to repaint borders around game frame
void create_blank_image(int coldepth)
{
// this is the first time that we try to use the graphics driver,
// so it's the most likey place for a crash
try
{
Bitmap *blank = CreateCompatBitmap(16, 16, coldepth);
blank->Clear();
blankImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
blankSidebarImage = gfxDriver->CreateDDBFromBitmap(blank, false, true);
delete blank;
}
catch (Ali3DException gfxException)
{
quit(gfxException.Message.GetCStr());
}
}
void destroy_blank_image()
{
if (blankImage)
gfxDriver->DestroyDDB(blankImage);
if (blankSidebarImage)
gfxDriver->DestroyDDB(blankSidebarImage);
blankImage = nullptr;
blankSidebarImage = nullptr;
}
int MakeColor(int color_index)
{
color_t real_color = 0;
__my_setcolor(&real_color, color_index, game.GetColorDepth());
return real_color;
}
void init_draw_method()
{
if (gfxDriver->HasAcceleratedTransform())
{
walkBehindMethod = DrawAsSeparateSprite;
create_blank_image(game.GetColorDepth());
}
else
{
walkBehindMethod = DrawOverCharSprite;
}
on_mainviewport_changed();
init_room_drawdata();
if (gfxDriver->UsesMemoryBackBuffer())
gfxDriver->GetMemoryBackBuffer()->Clear();
}
void dispose_draw_method()
{
dispose_room_drawdata();
dispose_invalid_regions(false);
destroy_blank_image();
}
void init_game_drawdata()
{
// character and object caches
charcache.resize(game.numcharacters);
for (int i = 0; i < MAX_ROOM_OBJECTS; ++i)
objcache[i] = ObjectCache();
size_t actsps_num = game.numcharacters + MAX_ROOM_OBJECTS;
actsps.resize(actsps_num);
guibg.resize(game.numgui);
gui_render_tex.resize(game.numgui);
size_t guio_num = 0;
// Prepare GUI cache lists and build the quick reference for controls cache
guiobjddbref.resize(game.numgui);
for (const auto &gui : guis)
{
guiobjddbref[gui.ID] = guio_num;
guio_num += gui.GetControlCount();
}
guiobjbg.resize(guio_num);
}
void dispose_game_drawdata()
{
clear_drawobj_cache();
charcache.clear();
actsps.clear();
walkbehindobj.clear();
guibg.clear();
gui_render_tex.clear();
guiobjbg.clear();
guiobjddbref.clear();
}
static void dispose_debug_room_drawdata()
{
debugRoomMaskObj = ObjTexture();
debugMoveListObj = ObjTexture();
}
void dispose_room_drawdata()
{
CameraDrawData.clear();
dispose_invalid_regions(true);
}
void clear_drawobj_cache()
{
// clear the character cache
for (auto &cc : charcache)
{
cc = ObjectCache();
}
// clear the object cache
for (int i = 0; i < MAX_ROOM_OBJECTS; ++i)
{
objcache[i] = ObjectCache();
}
// room overlays cache
screenovercache.clear();
// cleanup Character + Room object textures
for (auto &o : actsps) o = ObjTexture();
for (auto &o : walkbehindobj) o = ObjTexture();
// cleanup GUI and controls textures
for (auto &o : guibg) o = ObjTexture();
for (auto &tex : gui_render_tex)
{
if (tex)
gfxDriver->DestroyDDB(tex);
tex = nullptr;
}
for (auto &o : guiobjbg) o = ObjTexture();
// cleanup Overlay intermediate bitmaps
overlaybmp.clear();
dispose_debug_room_drawdata();
}
void release_drawobj_rendertargets()
{
if ((gui_render_tex.size() == 0) ||
!gfxDriver->ShouldReleaseRenderTargets())
return;
for (auto &tex : gui_render_tex)
{
if (tex)
gfxDriver->DestroyDDB(tex);
tex = nullptr;
}
}
void on_mainviewport_changed()
{
if (!gfxDriver->RequiresFullRedrawEachFrame())
{
const auto &view = play.GetMainViewport();
set_invalidrects_globaloffs(view.Left, view.Top);
// the black background region covers whole game screen
init_invalid_regions(-1, game.GetGameRes(), RectWH(game.GetGameRes()));
if (game.GetGameRes().ExceedsByAny(view.GetSize()))
clear_letterbox_borders();
}
}
// Allocates a bitmap for rendering camera/viewport pair (software render mode)
void prepare_roomview_frame(Viewport *view)
{
if (!view->GetCamera()) return; // no camera link
const int view_index = view->GetID();
const Size view_sz = view->GetRect().GetSize();
const Size cam_sz = view->GetCamera()->GetRect().GetSize();
RoomCameraDrawData &draw_dat = CameraDrawData[view_index];
// We use intermediate bitmap to render camera/viewport pair in software mode under these conditions:
// * camera size and viewport size are different (this may be suboptimal to paint dirty rects stretched,
// and also Allegro backend cannot stretch background of different colour depth).
// * viewport is located outside of the virtual screen (even if partially): subbitmaps cannot contain
// regions outside of master bitmap, and we must not clamp surface size to virtual screen because
// plugins may want to also use viewport bitmap, therefore it should retain full size.
if (cam_sz == view_sz && !draw_dat.IsOffscreen)
{ // note we keep the buffer allocated in case it will become useful later
draw_dat.Frame.reset();
}
else
{
PBitmap &camera_frame = draw_dat.Frame;
PBitmap &camera_buffer = draw_dat.Buffer;
if (!camera_buffer || camera_buffer->GetWidth() < cam_sz.Width || camera_buffer->GetHeight() < cam_sz.Height)
{
// Allocate new buffer bitmap with an extra size in case they will want to zoom out
int room_width = data_to_game_coord(thisroom.Width);
int room_height = data_to_game_coord(thisroom.Height);
Size alloc_sz = Size::Clamp(cam_sz * 2, Size(1, 1), Size(room_width, room_height));
camera_buffer.reset(new Bitmap(alloc_sz.Width, alloc_sz.Height, gfxDriver->GetMemoryBackBuffer()->GetColorDepth()));
}
if (!camera_frame || camera_frame->GetSize() != cam_sz)
{
camera_frame.reset(BitmapHelper::CreateSubBitmap(camera_buffer.get(), RectWH(cam_sz)));
}
}
}
// Syncs room viewport and camera in case either size has changed
void sync_roomview(Viewport *view)
{
if (view->GetCamera() == nullptr)
return;
// Note the dirty regions' viewport is found using absolute offset on game screen
init_invalid_regions(view->GetID(),
view->GetCamera()->GetRect().GetSize(),
play.GetRoomViewportAbs(view->GetID()));
prepare_roomview_frame(view);
}
void init_room_drawdata()
{
// Update debug overlays, if any were on
debug_draw_room_mask(debugRoomMask);
debug_draw_movelist(debugMoveListChar);
// Following data is only updated for software renderer
if (gfxDriver->RequiresFullRedrawEachFrame())
return;
// Make sure all frame buffers are created for software drawing
int view_count = play.GetRoomViewportCount();
CameraDrawData.resize(view_count);
for (int i = 0; i < play.GetRoomViewportCount(); ++i)
sync_roomview(play.GetRoomViewport(i).get());
}
void on_roomviewport_created(int index)
{
if (!gfxDriver || gfxDriver->RequiresFullRedrawEachFrame())
return;
if ((size_t)index < CameraDrawData.size())
return;
CameraDrawData.resize(index + 1);
}
void on_roomviewport_deleted(int index)
{
if (gfxDriver->RequiresFullRedrawEachFrame())
return;
CameraDrawData.erase(CameraDrawData.begin() + index);
delete_invalid_regions(index);
}
void on_roomviewport_changed(Viewport *view)
{
if (gfxDriver->RequiresFullRedrawEachFrame())
return;
if (!view->IsVisible() || view->GetCamera() == nullptr)
return;
const bool off = !IsRectInsideRect(RectWH(gfxDriver->GetMemoryBackBuffer()->GetSize()), view->GetRect());
const bool off_changed = off != CameraDrawData[view->GetID()].IsOffscreen;
CameraDrawData[view->GetID()].IsOffscreen = off;
if (view->HasChangedSize())
sync_roomview(view);
else if (off_changed)
prepare_roomview_frame(view);
// TODO: don't have to do this all the time, perhaps do "dirty rect" method
// and only clear previous viewport location?
invalidate_screen();
gfxDriver->GetMemoryBackBuffer()->Clear();
}
void detect_roomviewport_overlaps(size_t z_index)
{
if (gfxDriver->RequiresFullRedrawEachFrame())
return;
// Find out if we overlap or are overlapped by anything;
const auto &viewports = play.GetRoomViewportsZOrdered();
for (; z_index < viewports.size(); ++z_index)
{
auto this_view = viewports[z_index];
const int this_id = this_view->GetID();
bool is_overlap = false;
if (!this_view->IsVisible()) continue;
for (size_t z_index2 = 0; z_index2 < z_index; ++z_index2)
{
if (!viewports[z_index2]->IsVisible()) continue;
if (AreRectsIntersecting(this_view->GetRect(), viewports[z_index2]->GetRect()))
{
is_overlap = true;
break;
}
}
if (CameraDrawData[this_id].IsOverlap != is_overlap)
{
CameraDrawData[this_id].IsOverlap = is_overlap;
prepare_roomview_frame(this_view.get());
}
}
}
void on_roomcamera_changed(Camera *cam)
{
if (gfxDriver->RequiresFullRedrawEachFrame())
return;
if (cam->HasChangedSize())
{
auto viewrefs = cam->GetLinkedViewports();
for (auto vr : viewrefs)
{
PViewport vp = vr.lock();
if (vp)
sync_roomview(vp.get());
}
}
// TODO: only invalidate what this particular camera sees
invalidate_screen();
}
void mark_object_changed(int objid)
{
objcache[objid].y = -9999;
}
void reset_objcache_for_sprite(int sprnum, bool deleted)
{
// Check if this sprite is assigned to any game object, and mark these for update;
// if the sprite was deleted, also dispose shared textures
// room objects cache
if (croom != nullptr)
{
for (size_t i = 0; i < (size_t)croom->numobj; ++i)
{
if (objcache[i].sppic == sprnum)
objcache[i].sppic = -1;
if (deleted && (actsps[i].SpriteID == sprnum))
actsps[i] = ObjTexture();
}
}
// character cache
for (size_t i = 0; i < (size_t)game.numcharacters; ++i)
{
if (charcache[i].sppic == sprnum)
charcache[i].sppic = -1;
if (deleted && (actsps[ACTSP_OBJSOFF + i].SpriteID == sprnum))
actsps[i] = ObjTexture();
}
}
void mark_screen_dirty()
{
screen_is_dirty = true;
}
bool is_screen_dirty()
{
return screen_is_dirty;
}
void invalidate_screen()
{
invalidate_all_rects();
}
void invalidate_camera_frame(int index)
{
invalidate_all_camera_rects(index);
}
void invalidate_rect(int x1, int y1, int x2, int y2, bool in_room)
{
invalidate_rect_ds(x1, y1, x2, y2, in_room);
}
void invalidate_sprite(int x1, int y1, IDriverDependantBitmap *pic, bool in_room)
{
invalidate_rect_ds(x1, y1, x1 + pic->GetWidth(), y1 + pic->GetHeight(), in_room);
}
void invalidate_sprite_glob(int x1, int y1, IDriverDependantBitmap *pic)
{
invalidate_rect_global(x1, y1, x1 + pic->GetWidth(), y1 + pic->GetHeight());
}
void mark_current_background_dirty()
{
current_background_is_dirty = true;
}
void draw_and_invalidate_text(Bitmap *ds, int x1, int y1, int font, color_t text_color, const char *text)
{
wouttext_outline(ds, x1, y1, font, text_color, (char*)text);
invalidate_rect(x1, y1, x1 + get_text_width_outlined(text, font),
y1 + get_font_height_outlined(font) + get_fixed_pixel_size(1), false);
}
// Renders black borders for the legacy boxed game mode,
// where whole game screen changes size between large and small rooms
static void render_black_borders()
{
const Rect &viewport = play.GetMainViewport();
if (viewport.Top > 0)
{
// letterbox borders
blankImage->SetStretch(game.GetGameRes().Width, viewport.Top, false);
gfxDriver->DrawSprite(0, 0, blankImage);
gfxDriver->DrawSprite(0, viewport.Bottom + 1, blankImage);
}
if (viewport.Left > 0)
{
// sidebar borders for widescreen
blankSidebarImage->SetStretch(viewport.Left, viewport.GetHeight(), false);
gfxDriver->DrawSprite(0, 0, blankSidebarImage);
gfxDriver->DrawSprite(viewport.Right + 1, 0, blankSidebarImage);
}
}
extern volatile bool game_update_suspend;
extern volatile bool want_exit, abort_engine;
void render_to_screen()
{
const bool full_frame_rend = gfxDriver->RequiresFullRedrawEachFrame();
// Stage: final plugin callback (still drawn on game screen
if (pl_any_want_hook(AGSE_FINALSCREENDRAW))
{
gfxDriver->BeginSpriteBatch(play.GetMainViewport(),
play.GetGlobalTransform(full_frame_rend), (GraphicFlip)play.screen_flipped);
gfxDriver->DrawSprite(AGSE_FINALSCREENDRAW, 0, nullptr);
gfxDriver->EndSpriteBatch();
}
// Stage: engine overlay
construct_engine_overlay();
// only vsync in full screen mode, it makes things worse in a window
gfxDriver->SetVsync((scsystem.vsync > 0) && (!scsystem.windowed));
bool succeeded = false;
while (!succeeded && !want_exit && !abort_engine)
{
try
{
if (full_frame_rend)
{
gfxDriver->Render();
}
else
{
// NOTE: the shake yoff and global flip here will only be used by a software renderer;
// as hw renderers have these as transform parameters for the parent scene nodes.
// This may be a matter for the future code improvement.
//
// For software renderer, need to blacken upper part of the game frame when shaking screen moves image down
if (play.shake_screen_yoff > 0)
{
const Rect &viewport = play.GetMainViewport();
gfxDriver->ClearRectangle(viewport.Left, viewport.Top, viewport.GetWidth() - 1, play.shake_screen_yoff, nullptr);
}
gfxDriver->Render(0, play.shake_screen_yoff, (GraphicFlip)play.screen_flipped);
}
succeeded = true;
}
catch (Ali3DFullscreenLostException e)
{
Debug::Printf("Renderer exception: %s", e.Message.GetCStr());
do
{
sys_evt_process_pending();
platform->Delay(300);
} while (game_update_suspend && (!want_exit) && (!abort_engine));
}
}
}
// Blanks out borders around main viewport in case it became smaller (e.g. after loading another room)
void clear_letterbox_borders()
{
const Rect &viewport = play.GetMainViewport();
gfxDriver->ClearRectangle(0, 0, game.GetGameRes().Width - 1, viewport.Top - 1, nullptr);
gfxDriver->ClearRectangle(0, viewport.Bottom + 1, game.GetGameRes().Width - 1, game.GetGameRes().Height - 1, nullptr);
}
void draw_game_screen_callback()
{
construct_game_scene(true);
construct_game_screen_overlay(false);
}
void putpixel_compensate (Bitmap *ds, int xx,int yy, int col) {
if ((ds->GetColorDepth() == 32) && (col != 0)) {
// ensure the alpha channel is preserved if it has one
int alphaval = geta32(ds->GetPixel(xx, yy));
col = makeacol32(getr32(col), getg32(col), getb32(col), alphaval);
}
ds->FillRect(Rect(xx, yy, xx + get_fixed_pixel_size(1) - 1, yy + get_fixed_pixel_size(1) - 1), col);
}
void draw_sprite_support_alpha(Bitmap *ds, bool ds_has_alpha, int xpos, int ypos, Bitmap *image, bool src_has_alpha,
BlendMode blend_mode, int alpha)
{
if (alpha <= 0)