forked from diasurgical/DevilutionX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscrollrt.cpp
More file actions
1772 lines (1561 loc) · 56.9 KB
/
scrollrt.cpp
File metadata and controls
1772 lines (1561 loc) · 56.9 KB
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
/**
* @file scrollrt.cpp
*
* Implementation of functionality for rendering the dungeons, monsters and calling other render routines.
*/
#include "engine/render/scrollrt.h"
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <ankerl/unordered_dense.h>
#include "DiabloUI/ui_flags.hpp"
#include "automap.h"
#include "controls/control_mode.hpp"
#include "controls/plrctrls.h"
#include "cursor.h"
#include "dead.h"
#include "diablo_msg.hpp"
#include "doom.h"
#include "engine/backbuffer_state.hpp"
#include "engine/displacement.hpp"
#include "engine/dx.h"
#include "engine/point.hpp"
#include "engine/render/clx_render.hpp"
#include "engine/render/dun_render.hpp"
#include "engine/render/light_render.hpp"
#include "engine/render/text_render.hpp"
#include "engine/trn.hpp"
#include "engine/world_tile.hpp"
#include "gmenu.h"
#include "headless_mode.hpp"
#include "help.h"
#include "hwcursor.hpp"
#include "init.h"
#include "inv.h"
#include "levels/dun_tile.hpp"
#include "levels/gendung.h"
#include "levels/tile_properties.hpp"
#include "lighting.h"
#include "lua/lua.hpp"
#include "minitext.h"
#include "missiles.h"
#include "nthread.h"
#include "options.h"
#include "panels/charpanel.hpp"
#include "panels/console.hpp"
#include "panels/spell_list.hpp"
#include "plrmsg.h"
#include "qol/chatlog.h"
#include "qol/floatingnumbers.h"
#include "qol/itemlabels.h"
#include "qol/monhealthbar.h"
#include "qol/stash.h"
#include "qol/xpbar.h"
#include "stores.h"
#include "towners.h"
#include "utils/attributes.h"
#include "utils/display.h"
#include "utils/is_of.hpp"
#include "utils/log.hpp"
#include "utils/str_cat.hpp"
#ifndef USE_SDL1
#include "controls/touch/renderers.h"
#endif
#ifdef _DEBUG
#include "debug.h"
#endif
#ifdef DUN_RENDER_STATS
#include "utils/format_int.hpp"
#endif
namespace devilution {
bool AutoMapShowItems;
// DevilutionX extension.
extern void DrawControllerModifierHints(const Surface &out);
bool frameflag;
namespace {
constexpr auto RightFrameDisplacement = Displacement { DunFrameWidth, 0 };
[[nodiscard]] DVL_ALWAYS_INLINE bool IsFloor(Point tilePosition)
{
return !TileHasAny(tilePosition, TileProperties::Solid | TileProperties::BlockMissile);
}
[[nodiscard]] DVL_ALWAYS_INLINE bool IsWall(Point tilePosition)
{
return !IsFloor(tilePosition) || dSpecial[tilePosition.x][tilePosition.y] != 0;
}
/**
* @brief Contains all Missile at rendering position
*/
ankerl::unordered_dense::map<WorldTilePosition, std::vector<Missile *>> MissilesAtRenderingTile;
/**
* @brief Could the missile (at the next game tick) collide? This method is a simplified version of CheckMissileCol (for example without random).
*/
bool CouldMissileCollide(Point tile, bool checkPlayerAndMonster)
{
if (!InDungeonBounds(tile))
return true;
if (checkPlayerAndMonster) {
if (dMonster[tile.x][tile.y] > 0)
return true;
if (dPlayer[tile.x][tile.y] > 0)
return true;
}
return IsMissileBlockedByTile(tile);
}
void UpdateMissilePositionForRendering(Missile &m, int progress)
{
DisplacementOf<int64_t> velocity = m.position.velocity;
velocity *= progress;
velocity /= AnimationInfo::baseValueFraction;
Displacement pixelsTravelled = (m.position.traveled + Displacement { static_cast<int>(velocity.deltaX), static_cast<int>(velocity.deltaY) }) >> 16;
Displacement tileOffset = pixelsTravelled.screenToMissile();
// calculate the future missile position
m.position.tileForRendering = m.position.start + tileOffset;
m.position.offsetForRendering = pixelsTravelled + tileOffset.worldToScreen();
}
void UpdateMissileRendererData(Missile &m)
{
m.position.tileForRendering = m.position.tile;
m.position.offsetForRendering = m.position.offset;
const MissileMovementDistribution missileMovement = GetMissileData(m._mitype).movementDistribution;
// don't calculate missile position if they don't move
if (missileMovement == MissileMovementDistribution::Disabled || m.position.velocity == Displacement {})
return;
int progress = ProgressToNextGameTick;
UpdateMissilePositionForRendering(m, progress);
// In some cases this calculated position is invalid.
// For example a missile shouldn't move inside a wall.
// In this case the game logic don't advance the missile position and removes the missile or shows an explosion animation at the old position.
// For the animation distribution logic this means we are not allowed to move to a tile where the missile could collide, because this could be a invalid position.
// If we are still at the current tile, this tile was already checked and is a valid tile
if (m.position.tileForRendering == m.position.tile)
return;
// If no collision can happen at the new tile we can advance
if (!CouldMissileCollide(m.position.tileForRendering, missileMovement == MissileMovementDistribution::Blockable))
return;
// The new tile could be invalid, so don't advance to it.
// We search the last offset that is in the old (valid) tile.
// Implementation note: If someone knows the correct math to calculate this without the loop, I would really appreciate it.
while (m.position.tile != m.position.tileForRendering) {
progress -= 1;
if (progress <= 0) {
m.position.tileForRendering = m.position.tile;
m.position.offsetForRendering = m.position.offset;
return;
}
UpdateMissilePositionForRendering(m, progress);
}
}
void UpdateMissilesRendererData()
{
MissilesAtRenderingTile.clear();
for (auto &m : Missiles) {
UpdateMissileRendererData(m);
MissilesAtRenderingTile[m.position.tileForRendering].push_back(&m);
}
}
uint32_t lastFpsUpdateInMs;
Rectangle PrevCursorRect;
void BlitCursor(uint8_t *dst, uint32_t dstPitch, uint8_t *src, uint32_t srcPitch, uint32_t srcWidth, uint32_t srcHeight)
{
for (std::uint32_t i = 0; i < srcHeight; ++i, src += srcPitch, dst += dstPitch) {
memcpy(dst, src, srcWidth);
}
}
/**
* @brief Remove the cursor from the buffer
*/
void UndrawCursor(const Surface &out)
{
DrawnCursor &cursor = GetDrawnCursor();
BlitCursor(&out[cursor.rect.position], out.pitch(), cursor.behindBuffer, cursor.rect.size.width, cursor.rect.size.width, cursor.rect.size.height);
PrevCursorRect = cursor.rect;
}
bool ShouldShowCursor()
{
if (ControlMode == ControlTypes::KeyboardAndMouse)
return true;
if (pcurs == CURSOR_TELEPORT)
return true;
if (invflag)
return true;
if (CharFlag && MyPlayer->_pStatPts > 0)
return true;
return false;
}
/**
* @brief Save the content behind the cursor to a temporary buffer, then draw the cursor.
*/
void DrawCursor(const Surface &out)
{
DrawnCursor &cursor = GetDrawnCursor();
if (IsHardwareCursor()) {
SetHardwareCursorVisible(ShouldShowCursor());
cursor.rect.size = { 0, 0 };
return;
}
if (pcurs <= CURSOR_NONE || !ShouldShowCursor()) {
cursor.rect.size = { 0, 0 };
return;
}
Size cursSize = GetInvItemSize(pcurs);
if (cursSize.width == 0 || cursSize.height == 0) {
cursor.rect.size = { 0, 0 };
return;
}
constexpr auto Clip = [](int &pos, int &length, int posEnd) {
if (pos + length <= 0 || pos >= posEnd) {
pos = 0;
length = 0;
} else if (pos < 0) {
length += pos;
pos = 0;
} else if (pos + length > posEnd) {
length = posEnd - pos;
}
};
// Copy the buffer before the item cursor and its 1px outline are drawn to a temporary buffer.
const int outlineWidth = !MyPlayer->HoldItem.isEmpty() ? 1 : 0;
Displacement offset = !MyPlayer->HoldItem.isEmpty() ? Displacement { cursSize / 2 } : Displacement { 0 };
Point cursPosition = MousePosition - offset;
Rectangle &rect = cursor.rect;
rect.position.x = cursPosition.x - outlineWidth;
rect.size.width = cursSize.width + 2 * outlineWidth;
Clip(rect.position.x, rect.size.width, out.w());
rect.position.y = cursPosition.y - outlineWidth;
rect.size.height = cursSize.height + 2 * outlineWidth;
Clip(rect.position.y, rect.size.height, out.h());
if (rect.size.width == 0 || rect.size.height == 0)
return;
BlitCursor(cursor.behindBuffer, rect.size.width, &out[rect.position], out.pitch(), rect.size.width, rect.size.height);
DrawSoftwareCursor(out, cursPosition + Displacement { 0, cursSize.height - 1 }, pcurs);
}
/**
* @brief Render a missile sprite
* @param out Output buffer
* @param missile Pointer to Missile struct
* @param targetBufferPosition Output buffer coordinate
* @param pre Is the sprite in the background
*/
void DrawMissilePrivate(const Surface &out, const Missile &missile, Point targetBufferPosition, bool pre, int lightTableIndex)
{
if (missile._miPreFlag != pre || !missile._miDrawFlag)
return;
const Point missileRenderPosition { targetBufferPosition + missile.position.offsetForRendering - Displacement { missile._miAnimWidth2, 0 } };
const ClxSprite sprite = (*missile._miAnimData)[missile._miAnimFrame - 1];
if (missile._miUniqTrans != 0) {
ClxDrawTRN(out, missileRenderPosition, sprite, Monsters[missile._misource].uniqueMonsterTRN.get());
} else if (missile._miLightFlag) {
ClxDrawLight(out, missileRenderPosition, sprite, lightTableIndex);
} else {
ClxDraw(out, missileRenderPosition, sprite);
}
}
/**
* @brief Render a missile sprites for a given tile
* @param out Output buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
* @param pre Is the sprite in the background
*/
void DrawMissile(const Surface &out, WorldTilePosition tilePosition, Point targetBufferPosition, bool pre, int lightTableIndex)
{
const auto it = MissilesAtRenderingTile.find(tilePosition);
if (it == MissilesAtRenderingTile.end()) return;
for (Missile *missile : it->second) {
DrawMissilePrivate(out, *missile, targetBufferPosition, pre, lightTableIndex);
}
}
/**
* @brief Render a monster sprite
* @param out Output buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
* @param monster Monster reference
*/
void DrawMonster(const Surface &out, Point tilePosition, Point targetBufferPosition, const Monster &monster, int lightTableIndex)
{
if (!monster.animInfo.sprites) {
Log("Draw Monster \"{}\": NULL Cel Buffer", monster.name());
return;
}
const ClxSprite sprite = monster.animInfo.currentSprite();
if (!IsTileLit(tilePosition)) {
ClxDrawTRN(out, targetBufferPosition, sprite, GetInfravisionTRN());
return;
}
uint8_t *trn = nullptr;
if (monster.isUnique())
trn = monster.uniqueMonsterTRN.get();
if (monster.mode == MonsterMode::Petrified)
trn = GetStoneTRN();
if (MyPlayer->_pInfraFlag && lightTableIndex > 8)
trn = GetInfravisionTRN();
if (trn != nullptr)
ClxDrawTRN(out, targetBufferPosition, sprite, trn);
else
ClxDrawLight(out, targetBufferPosition, sprite, lightTableIndex);
}
/**
* @brief Helper for rendering a specific player icon (Mana Shield or Reflect)
*/
void DrawPlayerIconHelper(const Surface &out, MissileGraphicID missileGraphicId, Point position, const Player &player, bool infraVision, int lightTableIndex)
{
const bool lighting = &player != MyPlayer;
if (player.isWalking())
position += GetOffsetForWalking(player.AnimInfo, player._pdir);
position.x -= GetMissileSpriteData(missileGraphicId).animWidth2;
const ClxSprite sprite = (*GetMissileSpriteData(missileGraphicId).sprites).list()[0];
if (!lighting) {
ClxDraw(out, position, sprite);
return;
}
if (infraVision) {
ClxDrawTRN(out, position, sprite, GetInfravisionTRN());
return;
}
ClxDrawLight(out, position, sprite, lightTableIndex);
}
/**
* @brief Helper for rendering player icons (Mana Shield and Reflect)
* @param out Output buffer
* @param player Player reference
* @param position Output buffer coordinates
* @param infraVision Should infravision be applied
*/
void DrawPlayerIcons(const Surface &out, const Player &player, Point position, bool infraVision, int lightTableIndex)
{
if (player.pManaShield)
DrawPlayerIconHelper(out, MissileGraphicID::ManaShield, position, player, infraVision, lightTableIndex);
if (player.wReflections > 0)
DrawPlayerIconHelper(out, MissileGraphicID::Reflect, position + Displacement { 0, 16 }, player, infraVision, lightTableIndex);
}
/**
* @brief Render a player sprite
* @param out Output buffer
* @param player Player reference
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
*/
void DrawPlayer(const Surface &out, const Player &player, Point tilePosition, Point targetBufferPosition, int lightTableIndex)
{
if (!IsTileLit(tilePosition) && !MyPlayer->_pInfraFlag && !MyPlayer->isOnArenaLevel() && leveltype != DTYPE_TOWN) {
return;
}
const ClxSprite sprite = player.currentSprite();
Point spriteBufferPosition = targetBufferPosition + player.getRenderingOffset(sprite);
if (&player == PlayerUnderCursor)
ClxDrawOutlineSkipColorZero(out, 165, spriteBufferPosition, sprite);
if (&player == MyPlayer && IsNoneOf(leveltype, DTYPE_NEST, DTYPE_CRYPT)) {
ClxDraw(out, spriteBufferPosition, sprite);
DrawPlayerIcons(out, player, targetBufferPosition, /*infraVision=*/false, lightTableIndex);
return;
}
if (!IsTileLit(tilePosition) || ((MyPlayer->_pInfraFlag || MyPlayer->isOnArenaLevel()) && lightTableIndex > 8)) {
ClxDrawTRN(out, spriteBufferPosition, sprite, GetInfravisionTRN());
DrawPlayerIcons(out, player, targetBufferPosition, /*infraVision=*/true, lightTableIndex);
return;
}
lightTableIndex = std::max(lightTableIndex - 5, 0);
ClxDrawLight(out, spriteBufferPosition, sprite, lightTableIndex);
DrawPlayerIcons(out, player, targetBufferPosition, /*infraVision=*/false, lightTableIndex);
}
/**
* @brief Render a player sprite
* @param out Output buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
*/
void DrawDeadPlayer(const Surface &out, Point tilePosition, Point targetBufferPosition, int lightTableIndex)
{
dFlags[tilePosition.x][tilePosition.y] &= ~DungeonFlag::DeadPlayer;
for (Player &player : Players) {
if (player.plractive && player._pHitPoints == 0 && player.isOnActiveLevel() && player.position.tile == tilePosition) {
dFlags[tilePosition.x][tilePosition.y] |= DungeonFlag::DeadPlayer;
const Point playerRenderPosition { targetBufferPosition };
DrawPlayer(out, player, tilePosition, playerRenderPosition, lightTableIndex);
}
}
}
/**
* @brief Render an object sprite
* @param out Output buffer
* @param objectToDraw Dungeone object to draw
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
* @param pre Is the sprite in the background
*/
void DrawObject(const Surface &out, const Object &objectToDraw, Point tilePosition, Point targetBufferPosition, int lightTableIndex)
{
const ClxSprite sprite = objectToDraw.currentSprite();
const Point screenPosition = targetBufferPosition + objectToDraw.getRenderingOffset(sprite, tilePosition);
if (&objectToDraw == ObjectUnderCursor) {
ClxDrawOutlineSkipColorZero(out, 194, screenPosition, sprite);
}
if (objectToDraw.applyLighting) {
ClxDrawLight(out, screenPosition, sprite, lightTableIndex);
} else {
ClxDraw(out, screenPosition, sprite);
}
}
static void DrawDungeon(const Surface & /*out*/, const Lightmap & /*lightmap*/, Point /*tilePosition*/, Point /*targetBufferPosition*/);
/**
* @brief Render a cell
* @param out Target buffer
* @param lightmap Per-pixel light buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Target buffer coordinates
*/
void DrawCell(const Surface &out, const Lightmap lightmap, Point tilePosition, Point targetBufferPosition, int lightTableIndex)
{
const uint16_t levelPieceId = dPiece[tilePosition.x][tilePosition.y];
const MICROS *pMap = &DPieceMicros[levelPieceId];
const uint8_t *tbl = LightTables[lightTableIndex].data();
const uint8_t *foliageTbl = tbl;
#ifdef _DEBUG
int walkpathIdx = -1;
Point originalTargetBufferPosition;
if (DebugPath) {
walkpathIdx = MyPlayer->GetPositionPathIndex(tilePosition);
if (walkpathIdx != -1) {
originalTargetBufferPosition = targetBufferPosition;
tbl = GetPauseTRN();
}
}
#endif
bool transparency = TileHasAny(tilePosition, TileProperties::Transparent) && TransList[dTransVal[tilePosition.x][tilePosition.y]];
#ifdef _DEBUG
if ((SDL_GetModState() & KMOD_ALT) != 0)
transparency = false;
#endif
const auto getFirstTileMaskLeft = [=](TileType tile) -> MaskType {
if (transparency) {
switch (tile) {
case TileType::LeftTrapezoid:
case TileType::TransparentSquare:
return TileHasAny(tilePosition, TileProperties::TransparentLeft)
? MaskType::Left
: MaskType::Solid;
case TileType::LeftTriangle:
return MaskType::Solid;
default:
return MaskType::Transparent;
}
}
return MaskType::Solid;
};
const auto getFirstTileMaskRight = [=](TileType tile) -> MaskType {
if (transparency) {
switch (tile) {
case TileType::RightTrapezoid:
case TileType::TransparentSquare:
return TileHasAny(tilePosition, TileProperties::TransparentRight)
? MaskType::Right
: MaskType::Solid;
case TileType::RightTriangle:
return MaskType::Solid;
default:
return MaskType::Transparent;
}
}
return MaskType::Solid;
};
// Create a special lightmap buffer to bleed light up walls
uint8_t lightmapBuffer[TILE_WIDTH * TILE_HEIGHT];
Lightmap bleedLightmap = Lightmap::bleedUp(lightmap, targetBufferPosition, lightmapBuffer);
// If the first micro tile is a floor tile, it may be followed
// by foliage which should be rendered now.
const bool isFloor = IsFloor(tilePosition);
if (const LevelCelBlock levelCelBlock { pMap->mt[0] }; levelCelBlock.hasValue()) {
const TileType tileType = levelCelBlock.type();
if (!isFloor || tileType == TileType::TransparentSquare) {
if (isFloor && tileType == TileType::TransparentSquare) {
RenderTileFoliage(out, bleedLightmap, targetBufferPosition, levelCelBlock, foliageTbl);
} else {
RenderTile(out, bleedLightmap, targetBufferPosition, levelCelBlock, getFirstTileMaskLeft(tileType), tbl);
}
}
}
if (const LevelCelBlock levelCelBlock { pMap->mt[1] }; levelCelBlock.hasValue()) {
const TileType tileType = levelCelBlock.type();
if (!isFloor || tileType == TileType::TransparentSquare) {
if (isFloor && tileType == TileType::TransparentSquare) {
RenderTileFoliage(out, bleedLightmap, targetBufferPosition + RightFrameDisplacement, levelCelBlock, foliageTbl);
} else {
RenderTile(out, bleedLightmap, targetBufferPosition + RightFrameDisplacement,
levelCelBlock, getFirstTileMaskRight(tileType), tbl);
}
}
}
targetBufferPosition.y -= TILE_HEIGHT;
for (uint_fast8_t i = 2, n = MicroTileLen; i < n; i += 2) {
{
const LevelCelBlock levelCelBlock { pMap->mt[i] };
if (levelCelBlock.hasValue()) {
RenderTile(out, bleedLightmap, targetBufferPosition,
levelCelBlock,
transparency ? MaskType::Transparent : MaskType::Solid, foliageTbl);
}
}
{
const LevelCelBlock levelCelBlock { pMap->mt[i + 1] };
if (levelCelBlock.hasValue()) {
RenderTile(out, bleedLightmap, targetBufferPosition + RightFrameDisplacement,
levelCelBlock,
transparency ? MaskType::Transparent : MaskType::Solid, foliageTbl);
}
}
targetBufferPosition.y -= TILE_HEIGHT;
}
#ifdef _DEBUG
if (DebugPath && walkpathIdx != -1) {
DrawString(out, StrCat(walkpathIdx),
Rectangle(originalTargetBufferPosition + Displacement { 0, -TILE_HEIGHT }, Size { TILE_WIDTH, TILE_HEIGHT }),
TextRenderOptions {
.flags = UiFlags::AlignCenter | UiFlags::VerticalCenter
| (IsTileSolid(tilePosition) ? UiFlags::ColorYellow : UiFlags::ColorWhite) });
}
#endif
}
/**
* @brief Render a floor tile.
* @param out Target buffer
* @param lightmap Per-pixel light buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Target buffer coordinate
*/
void DrawFloorTile(const Surface &out, const Lightmap &lightmap, Point tilePosition, Point targetBufferPosition)
{
const int lightTableIndex = dLight[tilePosition.x][tilePosition.y];
const uint8_t *tbl = LightTables[lightTableIndex].data();
#ifdef _DEBUG
if (DebugPath && MyPlayer->GetPositionPathIndex(tilePosition) != -1)
tbl = GetPauseTRN();
#endif
const uint16_t levelPieceId = dPiece[tilePosition.x][tilePosition.y];
{
const LevelCelBlock levelCelBlock { DPieceMicros[levelPieceId].mt[0] };
if (levelCelBlock.hasValue()) {
RenderTileFrame(out, lightmap, targetBufferPosition, TileType::LeftTriangle,
GetDunFrame(levelCelBlock.frame()), DunFrameTriangleHeight, MaskType::Solid, tbl);
}
}
{
const LevelCelBlock levelCelBlock { DPieceMicros[levelPieceId].mt[1] };
if (levelCelBlock.hasValue()) {
RenderTileFrame(out, lightmap, targetBufferPosition + RightFrameDisplacement, TileType::RightTriangle,
GetDunFrame(levelCelBlock.frame()), DunFrameTriangleHeight, MaskType::Solid, tbl);
}
}
}
/**
* @brief Draw item for a given tile
* @param out Output buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
* @param pre Is the sprite in the background
*/
void DrawItem(const Surface &out, int8_t itemIndex, Point targetBufferPosition, int lightTableIndex)
{
const Item &item = Items[itemIndex];
const ClxSprite sprite = item.AnimInfo.currentSprite();
const Point position = targetBufferPosition + item.getRenderingOffset(sprite);
if (ActiveStore == TalkID::None && (itemIndex == pcursitem || AutoMapShowItems)) {
ClxDrawOutlineSkipColorZero(out, GetOutlineColor(item, false), position, sprite);
}
ClxDrawLight(out, position, sprite, lightTableIndex);
if (item.AnimInfo.isLastFrame() || item._iCurs == ICURS_MAGIC_ROCK)
AddItemToLabelQueue(itemIndex, position);
}
/**
* @brief Check if and how a monster should be rendered
* @param out Output buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Output buffer coordinates
*/
void DrawMonsterHelper(const Surface &out, Point tilePosition, Point targetBufferPosition, int lightTableIndex)
{
int mi = dMonster[tilePosition.x][tilePosition.y];
mi = std::abs(mi) - 1;
if (leveltype == DTYPE_TOWN) {
auto &towner = Towners[mi];
const Point position = targetBufferPosition + towner.getRenderingOffset();
const ClxSprite sprite = towner.currentSprite();
if (mi == pcursmonst) {
ClxDrawOutlineSkipColorZero(out, 166, position, sprite);
}
ClxDraw(out, position, sprite);
return;
}
if (!IsTileLit(tilePosition) && !(MyPlayer->_pInfraFlag && IsFloor(tilePosition))) {
return;
}
if (static_cast<size_t>(mi) >= MaxMonsters) {
Log("Draw Monster: tried to draw illegal monster {}", mi);
return;
}
const auto &monster = Monsters[mi];
if ((monster.flags & MFLAG_HIDDEN) != 0) {
return;
}
const ClxSprite sprite = monster.animInfo.currentSprite();
Displacement offset = monster.getRenderingOffset(sprite);
const Point monsterRenderPosition = targetBufferPosition + offset;
if (mi == pcursmonst) {
ClxDrawOutlineSkipColorZero(out, 233, monsterRenderPosition, sprite);
}
DrawMonster(out, tilePosition, monsterRenderPosition, monster, lightTableIndex);
}
/**
* @brief Render object sprites
* @param out Target buffer
* @param lightmap Per-pixel light buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Target buffer coordinates
*/
void DrawDungeon(const Surface &out, const Lightmap &lightmap, Point tilePosition, Point targetBufferPosition)
{
assert(InDungeonBounds(tilePosition));
const int lightTableIndex = dLight[tilePosition.x][tilePosition.y];
DrawCell(out, lightmap, tilePosition, targetBufferPosition, lightTableIndex);
const int8_t bDead = dCorpse[tilePosition.x][tilePosition.y];
const int8_t bMap = dTransVal[tilePosition.x][tilePosition.y];
#ifdef _DEBUG
if (DebugVision && IsTileLit(tilePosition)) {
ClxDraw(out, targetBufferPosition, (*pSquareCel)[0]);
}
#endif
if (MissilePreFlag) {
DrawMissile(out, tilePosition, targetBufferPosition, true, lightTableIndex);
}
if (lightTableIndex < LightsMax && bDead != 0) {
const Corpse &corpse = Corpses[(bDead & 0x1F) - 1];
const Point position { targetBufferPosition.x - CalculateSpriteTileCenterX(corpse.width), targetBufferPosition.y };
const ClxSprite sprite = corpse.spritesForDirection(static_cast<Direction>((bDead >> 5) & 7))[corpse.frame];
if (corpse.translationPaletteIndex != 0) {
const uint8_t *trn = Monsters[corpse.translationPaletteIndex - 1].uniqueMonsterTRN.get();
ClxDrawTRN(out, position, sprite, trn);
} else {
ClxDrawLight(out, position, sprite, lightTableIndex);
}
}
const int8_t bItem = dItem[tilePosition.x][tilePosition.y];
const Object *object = lightTableIndex < LightsMax
? FindObjectAtPosition(tilePosition)
: nullptr;
if (object != nullptr && object->_oPreFlag) {
DrawObject(out, *object, tilePosition, targetBufferPosition, lightTableIndex);
}
if (bItem > 0 && !Items[bItem - 1]._iPostDraw) {
DrawItem(out, static_cast<int8_t>(bItem - 1), targetBufferPosition, lightTableIndex);
}
if (TileContainsDeadPlayer(tilePosition)) {
DrawDeadPlayer(out, tilePosition, targetBufferPosition, lightTableIndex);
}
Player *player = PlayerAtPosition(tilePosition);
if (player != nullptr) {
uint8_t pid = player->getId();
assert(pid < MAX_PLRS);
int playerId = static_cast<int>(pid) + 1;
// If sprite is moving southwards or east, we want to draw it offset from the tile it's moving to, so we need negative ID
// This respests the order that tiles are drawn. By using the negative id, we ensure that the sprite is drawn with priority
if (player->_pmode == PM_WALK_SOUTHWARDS || (player->_pmode == PM_WALK_SIDEWAYS && player->_pdir == Direction::East))
playerId = -playerId;
if (dPlayer[tilePosition.x][tilePosition.y] == playerId) {
auto tempTilePosition = tilePosition;
auto tempTargetBufferPosition = targetBufferPosition;
// Offset the sprite to the tile it's moving from
if (player->_pmode == PM_WALK_SOUTHWARDS) {
switch (player->_pdir) {
case Direction::SouthWest:
tempTargetBufferPosition += { TILE_WIDTH / 2, -TILE_HEIGHT / 2 };
break;
case Direction::South:
tempTargetBufferPosition += { 0, -TILE_HEIGHT };
break;
case Direction::SouthEast:
tempTargetBufferPosition += { -TILE_WIDTH / 2, -TILE_HEIGHT / 2 };
break;
default:
DVL_UNREACHABLE();
}
tempTilePosition += Opposite(player->_pdir);
} else if (player->_pmode == PM_WALK_SIDEWAYS && player->_pdir == Direction::East) {
tempTargetBufferPosition += { -TILE_WIDTH, 0 };
tempTilePosition += Opposite(player->_pdir);
}
DrawPlayer(out, *player, tempTilePosition, tempTargetBufferPosition, lightTableIndex);
}
}
Monster *monster = FindMonsterAtPosition(tilePosition);
if (monster != nullptr) {
auto mid = monster->getId();
assert(mid < MaxMonsters);
int monsterId = static_cast<int>(mid) + 1;
// If sprite is moving southwards or east, we want to draw it offset from the tile it's moving to, so we need negative ID
// This respests the order that tiles are drawn. By using the negative id, we ensure that the sprite is drawn with priority
if (monster->mode == MonsterMode::MoveSouthwards || (monster->mode == MonsterMode::MoveSideways && monster->direction == Direction::East))
monsterId = -monsterId;
if (dMonster[tilePosition.x][tilePosition.y] == monsterId) {
auto tempTilePosition = tilePosition;
auto tempTargetBufferPosition = targetBufferPosition;
// Offset the sprite to the tile it's moving from
if (monster->mode == MonsterMode::MoveSouthwards) {
switch (monster->direction) {
case Direction::SouthWest:
tempTargetBufferPosition += { TILE_WIDTH / 2, -TILE_HEIGHT / 2 };
break;
case Direction::South:
tempTargetBufferPosition += { 0, -TILE_HEIGHT };
break;
case Direction::SouthEast:
tempTargetBufferPosition += { -TILE_WIDTH / 2, -TILE_HEIGHT / 2 };
break;
default:
DVL_UNREACHABLE();
}
tempTilePosition += Opposite(monster->direction);
} else if (monster->mode == MonsterMode::MoveSideways && monster->direction == Direction::East) {
tempTargetBufferPosition += { -TILE_WIDTH, 0 };
tempTilePosition += Opposite(monster->direction);
}
DrawMonsterHelper(out, tempTilePosition, tempTargetBufferPosition, lightTableIndex);
}
}
DrawMissile(out, tilePosition, targetBufferPosition, false, lightTableIndex);
if (object != nullptr && !object->_oPreFlag) {
DrawObject(out, *object, tilePosition, targetBufferPosition, lightTableIndex);
}
if (bItem > 0 && Items[bItem - 1]._iPostDraw) {
DrawItem(out, static_cast<int8_t>(bItem - 1), targetBufferPosition, lightTableIndex);
}
if (leveltype != DTYPE_TOWN) {
bool perPixelLighting = *GetOptions().Graphics.perPixelLighting;
int8_t bArch = dSpecial[tilePosition.x][tilePosition.y] - 1;
if (bArch >= 0) {
bool transparency = TransList[bMap];
#ifdef _DEBUG
// Turn transparency off here for debugging
transparency = transparency && (SDL_GetModState() & KMOD_ALT) == 0;
#endif
if (perPixelLighting) {
// Create a special lightmap buffer to bleed light up walls
uint8_t lightmapBuffer[TILE_WIDTH * TILE_HEIGHT];
Lightmap bleedLightmap = Lightmap::bleedUp(lightmap, targetBufferPosition, lightmapBuffer);
if (transparency)
ClxDrawBlendedWithLightmap(out, targetBufferPosition, (*pSpecialCels)[bArch], bleedLightmap);
else
ClxDrawWithLightmap(out, targetBufferPosition, (*pSpecialCels)[bArch], bleedLightmap);
} else if (transparency) {
ClxDrawLightBlended(out, targetBufferPosition, (*pSpecialCels)[bArch], lightTableIndex);
} else {
ClxDrawLight(out, targetBufferPosition, (*pSpecialCels)[bArch], lightTableIndex);
}
}
} else {
// Tree leaves should always cover player when entering or leaving the tile,
// So delay the rendering until after the next row is being drawn.
// This could probably have been better solved by sprites in screen space.
if (tilePosition.x > 0 && tilePosition.y > 0 && targetBufferPosition.y > TILE_HEIGHT) {
int8_t bArch = dSpecial[tilePosition.x - 1][tilePosition.y - 1] - 1;
if (bArch >= 0)
ClxDraw(out, targetBufferPosition + Displacement { 0, -TILE_HEIGHT }, (*pSpecialCels)[bArch]);
}
}
}
/**
* @brief Render a row of tiles
* @param out Buffer to render to
* @param lightmap Per-pixel light buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Target buffer coordinates
* @param rows Number of rows
* @param columns Tile in a row
*/
void DrawFloor(const Surface &out, const Lightmap &lightmap, Point tilePosition, Point targetBufferPosition, int rows, int columns)
{
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++, tilePosition += Direction::East, targetBufferPosition.x += TILE_WIDTH) {
if (!InDungeonBounds(tilePosition)) {
world_draw_black_tile(out, targetBufferPosition.x, targetBufferPosition.y);
continue;
}
if (IsFloor(tilePosition)) {
DrawFloorTile(out, lightmap, tilePosition, targetBufferPosition);
}
}
// Return to start of row
tilePosition += Displacement(Direction::West) * columns;
targetBufferPosition.x -= columns * TILE_WIDTH;
// Jump to next row
targetBufferPosition.y += TILE_HEIGHT / 2;
if ((i & 1) != 0) {
tilePosition.x++;
columns--;
targetBufferPosition.x += TILE_WIDTH / 2;
} else {
tilePosition.y++;
columns++;
targetBufferPosition.x -= TILE_WIDTH / 2;
}
}
}
/**
* @brief Renders the floor tiles
* @param out Output buffer
* @param lightmap Per-pixel light buffer
* @param tilePosition dPiece coordinates
* @param targetBufferPosition Buffer coordinates
* @param rows Number of rows
* @param columns Tile in a row
*/
void DrawTileContent(const Surface &out, const Lightmap &lightmap, Point tilePosition, Point targetBufferPosition, int rows, int columns)
{
// Keep evaluating until MicroTiles can't affect screen
rows += MicroTileLen;
#ifdef _DEBUG
DebugCoordsMap.reserve(rows * columns);
#endif
for (int i = 0; i < rows; i++) {
bool skip = false;
for (int j = 0; j < columns; j++) {
if (InDungeonBounds(tilePosition)) {
bool skipNext = false;
#ifdef _DEBUG
DebugCoordsMap[tilePosition.x + tilePosition.y * MAXDUNX] = targetBufferPosition;
#endif
if (tilePosition.x + 1 < MAXDUNX && tilePosition.y - 1 >= 0 && targetBufferPosition.x + TILE_WIDTH <= gnScreenWidth) {
// Render objects behind walls first to prevent sprites, that are moving
// between tiles, from poking through the walls as they exceed the tile bounds.
// A proper fix for this would probably be to layout the scene and render by
// sprite screen position rather than tile position.
if (IsWall(tilePosition) && (IsWall(tilePosition + Displacement { 1, 0 }) || (tilePosition.x > 0 && IsWall(tilePosition + Displacement { -1, 0 })))) { // Part of a wall aligned on the x-axis
if (IsTileNotSolid(tilePosition + Displacement { 1, -1 }) && IsTileNotSolid(tilePosition + Displacement { 0, -1 })) { // Has walkable area behind it
DrawDungeon(out, lightmap, tilePosition + Direction::East, { targetBufferPosition.x + TILE_WIDTH, targetBufferPosition.y });
skipNext = true;
}
}
}
if (!skip) {
DrawDungeon(out, lightmap, tilePosition, targetBufferPosition);
}
skip = skipNext;
}
tilePosition += Direction::East;
targetBufferPosition.x += TILE_WIDTH;
}
// Return to start of row
tilePosition += Displacement(Direction::West) * columns;
targetBufferPosition.x -= columns * TILE_WIDTH;
// Jump to next row
targetBufferPosition.y += TILE_HEIGHT / 2;
if ((i & 1) != 0) {
tilePosition.x++;
columns--;
targetBufferPosition.x += TILE_WIDTH / 2;
} else {
tilePosition.y++;
columns++;
targetBufferPosition.x -= TILE_WIDTH / 2;
}
}
}
/**
* @brief Scale up the top left part of the buffer 2x.
*/
void Zoom(const Surface &out)
{
int viewportWidth = out.w();
int viewportOffsetX = 0;
if (CanPanelsCoverView()) {
if (IsLeftPanelOpen()) {
viewportWidth -= SidePanelSize.width;
viewportOffsetX = SidePanelSize.width;
} else if (IsRightPanelOpen()) {
viewportWidth -= SidePanelSize.width;
}
}
// We round to even for the source width and height.
// If the width / height was odd, we copy just one extra pixel / row later on.
const int srcWidth = (viewportWidth + 1) / 2;
const int doubleableWidth = viewportWidth / 2;
const int srcHeight = (out.h() + 1) / 2;
const int doubleableHeight = out.h() / 2;
uint8_t *src = out.at(srcWidth - 1, srcHeight - 1);
uint8_t *dst = out.at(viewportOffsetX + viewportWidth - 1, out.h() - 1);