-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDungGine.h
1598 lines (1411 loc) · 58 KB
/
DungGine.h
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
//
// DungGine.h
// DungGine
//
// Created by Rasmus Anthin on 2024-06-13.
//
#pragma once
#include "BSPTree.h"
#include "Environment.h"
#include "ScreenHelper.h"
#include "DungGineStyles.h"
#include "RoomStyle.h"
#include "Items.h"
#include "PC.h"
#include "NPC.h"
#include "SolarMotionPatterns.h"
#include "Globals.h"
#include "DungGineListener.h"
#include "Inventory.h"
#include "Keyboard.h"
#include <Termin8or/Keyboard.h>
#include <Termin8or/MessageHandler.h>
#include <Core/FolderHelper.h>
#include <Core/events/EventBroadcaster.h>
#include <Core/Utils.h>
using namespace utils::literals;
namespace dung
{
using namespace std::string_literals;
class DungGine final : public EventBroadcaster<DungGineListener>
{
std::unique_ptr<Environment> m_environment;
bool m_use_per_room_lat_long_for_sun_dir = true;
SolarDirection m_sun_dir = SolarDirection::E;
Latitude m_latitude = Latitude::NorthernHemisphere;
Longitude m_longitude = Longitude::F;
Season m_season = Season::Spring;
SolarMotionPatterns m_solar_motion;
float m_sun_minutes_per_day = 20.f;
float m_sun_day_t_offs = 0.f;
float m_sun_minutes_per_year = 120.f;
float m_sun_year_t_offs = 0.f;
float m_t_solar_period = 0.f;
bool debug = false;
PC m_player;
std::vector<NPC> all_npcs;
std::unique_ptr<ScreenHelper> m_screen_helper;
std::unique_ptr<Inventory> m_inventory;
std::unique_ptr<Keyboard> m_keyboard;
std::vector<Key> all_keys;
// Lamps illuminate items and NPCs. If you've already discovered an item or
// NPC using a lamp (and after FOW been cleared),
// then they will still be visible when the room is not lit.
// Lamps will not work in surface level rooms.
std::vector<Lamp> all_lamps;
std::vector<std::unique_ptr<Weapon>> all_weapons;
std::vector<Potion> all_potions;
std::vector<std::unique_ptr<Armour>> all_armour;
std::unique_ptr<MessageHandler> message_handler;
bool use_fog_of_war = false;
const std::vector<std::string> c_fight_strings { "(", "#", ")", "%", "*" };
const std::vector<Color> c_fight_colors { Color::Red, Color::Yellow, Color::Blue, Color::Magenta, Color::White, Color::Black, Color::LightGray, Color::DarkGray };
enum class FightDir { NW, W, SW, S, SE, E, NE, N, NUM_ITEMS };
std::vector<int> fight_r_offs = { 1, 0, -1, -1, -1, 0, 1, 1 };
std::vector<int> fight_c_offs = { 1, 1, 1, 0, -1, -1, -1, 0 };
ui::TextBox tb_health, tb_strength;
ui::TextBoxDebug tbd;
bool stall_game = false;
// /////////////////////
void update_sun(float real_time_s)
{
m_t_solar_period = std::fmod(m_sun_day_t_offs + (real_time_s / 60.f) / m_sun_minutes_per_day, 1.f);
m_sun_dir = m_solar_motion.get_solar_direction(m_latitude, m_longitude, m_season, m_t_solar_period);
float t_season_period = std::fmod(m_sun_year_t_offs + (real_time_s / 60.f) / m_sun_minutes_per_year, 1.f);
m_season = static_cast<Season>(math::roundI(7*t_season_period));
}
void update_inventory()
{
auto num_inv_keys = stlutils::sizeI(m_player.key_idcs);
auto num_inv_lamps = stlutils::sizeI(m_player.lamp_idcs);
auto num_inv_wpns = stlutils::sizeI(m_player.weapon_idcs);
auto num_inv_potions = stlutils::sizeI(m_player.potion_idcs);
auto num_inv_armour = stlutils::sizeI(m_player.armour_idcs);
m_player.curr_tot_inv_weight = 0.f;
auto f_format_item_str = [](std::string& item_str, float weight, float price, int hp)
{
std::ostringstream oss;
oss << std::setprecision(1) << std::fixed << weight;
std::string weight_str = oss.str() + " kg";
item_str += str::rep_char(' ', 25 - stlutils::sizeI(item_str) - stlutils::sizeI(weight_str)) + weight_str;
oss.str("");
oss.clear();
oss << std::setprecision(2) << std::fixed << price;
std::string price_str = oss.str() + " FK"; // Fantasy-Kronor.
item_str += str::rep_char(' ', 42 - stlutils::sizeI(item_str) - stlutils::sizeI(price_str)) + price_str;
if (hp > 0)
{
oss.str("");
oss.clear();
oss << std::setprecision(0) << std::fixed << hp;
std::string hp_str = oss.str() + " hp";
item_str += str::rep_char(' ', 52 - stlutils::sizeI(item_str) - stlutils::sizeI(hp_str)) + hp_str;
}
};
auto* keys_group = m_inventory->fetch_group("Keys:");
auto* keys_subgroup = keys_group->fetch_subgroup(0);
for (int inv_key_idx = 0; inv_key_idx < num_inv_keys; ++inv_key_idx)
{
auto key_idx = m_player.key_idcs[inv_key_idx];
auto& key = all_keys[key_idx];
std::string item_str = " Key:" + std::to_string(key.key_id);
f_format_item_str(item_str, key.weight, key.price, 0);
if (keys_subgroup->find_item(&key) == nullptr)
keys_subgroup->add_item(item_str, &key);
m_player.curr_tot_inv_weight += key.weight;
}
auto* lamps_group = m_inventory->fetch_group("Lamps:");
auto* lamps_subgroup = lamps_group->fetch_subgroup(0);
for (int inv_lamp_idx = 0; inv_lamp_idx < num_inv_lamps; ++inv_lamp_idx)
{
auto lamp_idx = m_player.lamp_idcs[inv_lamp_idx];
auto& lamp = all_lamps[lamp_idx];
auto lamp_type = lamp.get_type_str();
str::to_upper(lamp_type[0]);
std::string item_str = " "s + lamp_type + ":" + std::to_string(lamp_idx);
f_format_item_str(item_str, lamp.weight, lamp.price, 0);
if (lamps_subgroup->find_item(&lamp) == nullptr)
lamps_subgroup->add_item(item_str, &lamp);
m_player.curr_tot_inv_weight += lamp.weight;
}
auto* weapons_group = m_inventory->fetch_group("Weapons:");
auto* weapons_subgroup_melee = weapons_group->fetch_subgroup(0);
weapons_subgroup_melee->set_title("Melee:");
for (int inv_wpn_idx = 0; inv_wpn_idx < num_inv_wpns; ++inv_wpn_idx)
{
auto wpn_idx = m_player.weapon_idcs[inv_wpn_idx];
auto& weapon = all_weapons[wpn_idx];
std::string item_str = " ";
if (dynamic_cast<Sword*>(weapon.get()) != nullptr)
item_str += "Sword";
else if (dynamic_cast<Dagger*>(weapon.get()) != nullptr)
item_str += "Dagger";
else if (dynamic_cast<Flail*>(weapon.get()) != nullptr)
item_str += "Flail";
else
item_str += "<Weapon>";
item_str += ":";
item_str += std::to_string(wpn_idx);
f_format_item_str(item_str, weapon->weight, weapon->price, weapon->damage);
if (weapons_subgroup_melee->find_item(weapon.get()) == nullptr)
weapons_subgroup_melee->add_item(item_str, weapon.get());
m_player.curr_tot_inv_weight += weapon->weight;
}
auto* potions_group = m_inventory->fetch_group("Potions:");
auto* potions_subgroup = potions_group->fetch_subgroup(0);
for (int inv_pot_idx = 0; inv_pot_idx < num_inv_potions; ++inv_pot_idx)
{
auto pot_idx = m_player.potion_idcs[inv_pot_idx];
auto& potion = all_potions[pot_idx];
std::string item_str = " Potion:" + std::to_string(pot_idx);
f_format_item_str(item_str, potion.weight, potion.price, 0);
if (potions_subgroup->find_item(&potion) == nullptr)
potions_subgroup->add_item(item_str, &potion);
m_player.curr_tot_inv_weight += potion.weight;
}
auto* armour_group = m_inventory->fetch_group("Armour:");
auto* armour_subgroup_shields = armour_group->fetch_subgroup(ARMOUR_Shield);
armour_subgroup_shields->set_title("Shields:");
auto* armour_subgroup_gambesons = armour_group->fetch_subgroup(ARMOUR_Gambeson);
armour_subgroup_gambesons->set_title("Gambesons:");
auto* armour_subgroup_chainmaillehauberks = armour_group->fetch_subgroup(ARMOUR_ChainMailleHauberk);
armour_subgroup_chainmaillehauberks->set_title("Chain-Maille Hauberks:");
auto* armour_subgroup_platedbodyarmour = armour_group->fetch_subgroup(ARMOUR_PlatedBodyArmour);
armour_subgroup_platedbodyarmour->set_title("Plated Body Armour:");
auto* armour_subgroup_paddedcoifs = armour_group->fetch_subgroup(ARMOUR_PaddedCoif);
armour_subgroup_paddedcoifs->set_title("Padded Coifs:");
auto* armour_subgroup_chainmaillecoifs = armour_group->fetch_subgroup(ARMOUR_ChainMailleCoif);
armour_subgroup_chainmaillecoifs->set_title("Chain-Maille Coifs:");
auto* armour_subgroup_helmets = armour_group->fetch_subgroup(ARMOUR_Helmet);
armour_subgroup_helmets->set_title("Helmets:");
for (int inv_a_idx = 0; inv_a_idx < num_inv_armour; ++inv_a_idx)
{
auto a_idx = m_player.armour_idcs[inv_a_idx];
const auto& armour = all_armour[a_idx];
std::string item_str = " ";
InvSubGroup* armour_subgroup = nullptr;
if (dynamic_cast<Shield*>(armour.get()) != nullptr)
{
item_str += "Shield";
armour_subgroup = armour_subgroup_shields;
}
else if (dynamic_cast<Gambeson*>(armour.get()) != nullptr)
{
item_str += "Gambeson";
armour_subgroup = armour_subgroup_gambesons;
}
else if (dynamic_cast<ChainMailleHauberk*>(armour.get()) != nullptr)
{
item_str += "C.M.H.";
armour_subgroup = armour_subgroup_chainmaillehauberks;
}
else if (dynamic_cast<PlatedBodyArmour*>(armour.get()) != nullptr)
{
item_str += "P.B.A.";
armour_subgroup = armour_subgroup_platedbodyarmour;
}
else if (dynamic_cast<PaddedCoif*>(armour.get()) != nullptr)
{
item_str += "P. Coif";
armour_subgroup = armour_subgroup_paddedcoifs;
}
else if (dynamic_cast<ChainMailleCoif*>(armour.get()) != nullptr)
{
item_str += "C.M. Coif";
armour_subgroup = armour_subgroup_chainmaillecoifs;
}
else if (dynamic_cast<Helmet*>(armour.get()) != nullptr)
{
item_str += "Helmet";
armour_subgroup = armour_subgroup_helmets;
}
else
item_str += "<Armour>";
item_str += ":";
item_str += std::to_string(a_idx);
f_format_item_str(item_str, armour->weight, armour->price, armour->protection);
if (armour_subgroup != nullptr)
if (armour_subgroup->find_item(armour.get()) == nullptr)
armour_subgroup->add_item(item_str, armour.get());
m_player.curr_tot_inv_weight += armour->weight;
}
}
template<typename Lambda>
void clear_field(Lambda get_field_ptr, bool clear_val)
{
for (auto& key : all_keys)
*get_field_ptr(&key) = clear_val;
for (auto& lamp : all_lamps)
*get_field_ptr(&lamp) = clear_val;
for (auto& weapon : all_weapons)
*get_field_ptr(weapon.get()) = clear_val;
for (auto& potion : all_potions)
*get_field_ptr(&potion) = clear_val;
for (auto& armour : all_armour)
*get_field_ptr(armour.get()) = clear_val;
for (auto& bs : m_player.blood_splats)
*get_field_ptr(&bs) = clear_val;
for (auto& npc : all_npcs)
for (auto& bs : npc.blood_splats)
*get_field_ptr(&bs) = clear_val;
// #NOTE: fog_of_war and light vars set by NPC class itself.
//for (auto& npc : all_npcs)
// *get_field_ptr(&npc) = clear_val;
ttl::Rectangle bb;
bool_vector* field = nullptr;
if (m_player.curr_corridor != nullptr)
{
bb = m_player.curr_corridor->bb;
field = get_field_ptr(m_player.curr_corridor);
auto* door_0 = m_player.curr_corridor->doors[0];
auto* door_1 = m_player.curr_corridor->doors[1];
stlutils::memset(*field, clear_val);
*get_field_ptr(door_0) = clear_val;
*get_field_ptr(door_1) = clear_val;
}
if (m_player.curr_room != nullptr)
{
bb = m_player.curr_room->bb_leaf_room;
field = get_field_ptr(m_player.curr_room);
stlutils::memset(*field, clear_val);
for (auto* door : m_player.curr_room->doors)
*get_field_ptr(door) = clear_val;
}
}
template<typename Lambda>
void update_field(const RC& curr_pos, Lambda get_field_ptr, bool set_val, float radius, float angle_deg,
Lamp::LightType src_type)
{
const auto c_fow_dist = radius; //2.3f;
auto f_normalize_angle = [](float& ang)
{
while (ang < 0.f)
ang += math::c_2pi;
while (ang >= math::c_2pi)
ang -= math::c_2pi;
};
auto f_set_item_field = [&](auto& obj)
{
if (m_player.curr_room == obj.curr_room || m_player.curr_corridor == obj.curr_corridor)
if (distance(obj.pos, curr_pos) <= radius)
{
if (src_type == Lamp::LightType::Directional)
{
// #FIXME: Move parts into math functions for better reuse.
// Rotating dir vector CW and CCW using a rotation matrix.
auto a = math::deg2rad(angle_deg*0.5f);
auto dir_r = m_player.los_r;
auto dir_c = m_player.los_c;
auto Clo = std::cos(-a);
auto Slo = std::sin(-a);
auto Chi = std::cos(+a);
auto Shi = std::sin(+a);
math::normalize(dir_r, dir_c);
float dir_lo_r = (dir_r*Clo - dir_c*Slo);
float dir_lo_c = dir_r*Slo + dir_c*Clo;
float dir_hi_r = (dir_r*Chi - dir_c*Shi);
float dir_hi_c = dir_r*Shi + dir_c*Chi;
float lo_angle_rad = std::atan2(-dir_lo_r, dir_lo_c);
float hi_angle_rad = std::atan2(-dir_hi_r, dir_hi_c);
f_normalize_angle(lo_angle_rad);
f_normalize_angle(hi_angle_rad);
if (lo_angle_rad > hi_angle_rad)
hi_angle_rad += math::c_2pi;
float curr_angle_rad = static_cast<float>(std::atan2(-(obj.pos.r - curr_pos.r), obj.pos.c - curr_pos.c));
f_normalize_angle(curr_angle_rad);
if (curr_angle_rad < lo_angle_rad)
curr_angle_rad += math::c_2pi;
if (math::in_range<float>(curr_angle_rad, lo_angle_rad, hi_angle_rad, Range::Closed))
*get_field_ptr(&obj) = set_val;
}
else
*get_field_ptr(&obj) = set_val;
}
};
for (auto& key : all_keys)
f_set_item_field(key);
for (auto& lamp : all_lamps)
f_set_item_field(lamp);
for (auto& weapon : all_weapons)
f_set_item_field(*weapon);
for (auto& potion : all_potions)
f_set_item_field(potion);
for (auto& armour : all_armour)
f_set_item_field(*armour);
for (auto& bs : m_player.blood_splats)
f_set_item_field(bs);
for (auto& npc : all_npcs)
for (auto& bs : npc.blood_splats)
f_set_item_field(bs);
// #NOTE: fog_of_war and light vars set by NPC class itself.
//for (auto& npc : all_npcs)
// if (distance(npc.pos, curr_pos) <= c_fow_dist)
// *get_field_ptr(&npc) = set_val;
ttl::Rectangle bb;
RC local_pos;
RC size;
bool_vector* field = nullptr;
auto set_field = [&](const RC& p)
{
if (field == nullptr)
return;
if (p.r < 0 || p.c < 0 || p.r >= bb.r_len || p.c >= bb.c_len)
return;
// ex:
// +---+ 01234
// | | 56789
// +---+ ABCDE
// r_len = 3, c_len = 5
// FOW size = 3*5
// idx = 0 .. 14
// r = 2, c = 4 => idx = r * c_len + c = 2*5 + 4 = 14.
int idx = p.r * size.c + p.c;
if (0 <= idx && idx < static_cast<int>(field->size()))
(*field)[idx] = set_val;
};
auto update_rect_field = [&]() // #FIXME: FHXFTW
{
local_pos = curr_pos - bb.pos();
size = bb.size();
std::vector<RC> positions;
switch (src_type)
{
case Lamp::LightType::Isotropic:
positions = drawing::filled_circle_positions(local_pos, radius, globals::px_aspect);
break;
case Lamp::LightType::Directional:
positions = drawing::filled_arc_positions(local_pos, radius, math::deg2rad(angle_deg), m_player.los_r, m_player.los_c, globals::px_aspect);
break;
case Lamp::LightType::NUM_ITEMS:
break;
}
for (const auto& pos : positions)
set_field(pos);
int r_room = -1;
int c_room = -1;
if (curr_pos.r - bb.top() <= 1)
r_room = 0;
else if (bb.bottom() - curr_pos.r <= 1)
r_room = bb.r_len - 1;
if (curr_pos.c - bb.left() <= 1)
c_room = 0;
else if (bb.right() - curr_pos.c <= 1)
c_room = bb.c_len - 1;
if (r_room >= 0 && c_room >= 0)
set_field({ r_room, c_room });
};
if (m_player.curr_corridor != nullptr && m_player.curr_corridor->is_inside_corridor(curr_pos))
{
bb = m_player.curr_corridor->bb;
field = get_field_ptr(m_player.curr_corridor);
auto* door_0 = m_player.curr_corridor->doors[0];
auto* door_1 = m_player.curr_corridor->doors[1];
update_rect_field();
if (distance(door_0->pos, curr_pos) <= c_fow_dist)
*get_field_ptr(door_0) = set_val;
if (distance(door_1->pos, curr_pos) <= c_fow_dist)
*get_field_ptr(door_1) = set_val;
}
if (m_player.curr_room != nullptr && m_player.curr_room->is_inside_room(curr_pos))
{
bb = m_player.curr_room->bb_leaf_room;
field = get_field_ptr(m_player.curr_room);
update_rect_field();
for (auto* door : m_player.curr_room->doors)
if (distance(door->pos, curr_pos) <= c_fow_dist)
*get_field_ptr(door) = set_val;
}
}
void set_visibilities(float fow_radius, const RC& pc_pos)
{
const auto c_fow_radius_sq = math::sq(fow_radius);
auto f_calc_night = [&](const auto& obj) -> bool
{
bool is_night = false;
if (m_use_per_room_lat_long_for_sun_dir)
{
auto f_set_night = [&](const RoomStyle& rs)
{
if (m_solar_motion.get_solar_direction(rs.latitude, rs.longitude, m_season, m_t_solar_period) == SolarDirection::Nadir)
is_night = true;
};
auto room_style = m_environment->find_room_style(obj.curr_room);
if (room_style.has_value())
f_set_night(room_style.value());
else
{
auto corr_style = m_environment->find_corridor_style(obj.curr_corridor);
if (corr_style.has_value())
f_set_night(corr_style.value());
}
}
else
is_night = m_sun_dir == SolarDirection::Nadir;
return is_night;
};
auto f_fow_near = [&pc_pos, c_fow_radius_sq](const auto& obj) -> bool
{
return distance_squared(obj.pos, pc_pos) <= c_fow_radius_sq;
};
for (auto& key : all_keys)
key.set_visibility(use_fog_of_war, f_fow_near(key), f_calc_night(key));
for (auto& lamp : all_lamps)
lamp.set_visibility(use_fog_of_war, f_fow_near(lamp), f_calc_night(lamp));
for (auto& weapon : all_weapons)
weapon->set_visibility(use_fog_of_war, f_fow_near(*weapon), f_calc_night(*weapon));
for (auto& potion : all_potions)
potion.set_visibility(use_fog_of_war, f_fow_near(potion), f_calc_night(potion));
for (auto& armour : all_armour)
armour->set_visibility(use_fog_of_war, f_fow_near(*armour), f_calc_night(*armour));
for (auto& npc : all_npcs)
npc.set_visibility(use_fog_of_war, f_fow_near(npc), f_calc_night(npc));
for (auto& bs : m_player.blood_splats)
bs.set_visibility(use_fog_of_war, f_calc_night(bs));
for (auto& npc : all_npcs)
for (auto& bs : npc.blood_splats)
bs.set_visibility(use_fog_of_war, f_calc_night(bs));
}
template<int NR, int NC>
void draw_health_bars(ScreenHandler<NR, NC>& sh, bool framed_mode)
{
std::vector<std::string> health_bars;
std::vector<Style> styles;
std::string pc_hb = str::rep_char(' ', 10);
float pc_ratio = globals::max_health / 10;
for (int i = 0; i < 10; ++i)
pc_hb[i] = m_player.health > static_cast<int>(i*pc_ratio) ? '#' : ' ';
health_bars.emplace_back(pc_hb);
styles.emplace_back(Style { Color::Magenta, Color::Transparent2 });
for (const auto& npc : all_npcs)
{
if (npc.health > 0 && npc.state == State::Fight)
{
std::string npc_hb = str::rep_char(' ', 10);
float npc_ratio = globals::max_health / 10;
for (int i = 0; i < 10; ++i)
npc_hb[i] = npc.health > static_cast<int>(i*npc_ratio) ? 'O' : ' ';
health_bars.emplace_back(npc_hb);
styles.emplace_back(Style { Color::Red, Color::Transparent2 });
}
}
ui::TextBoxDrawingArgsAlign tb_args;
tb_args.v_align = ui::VerticalAlignment::TOP;
tb_args.h_align = ui::HorizontalAlignment::LEFT;
tb_args.base.box_style = { Color::White, Color::DarkBlue };
tb_args.framed_mode = framed_mode;
tb_health.set_text(health_bars, styles);
tb_health.calc_pre_draw(str::Adjustment::Left);
tb_health.draw(sh, tb_args);
}
template<int NR, int NC>
void draw_strength_bar(ScreenHandler<NR, NC>& sh, bool framed_mode)
{
ui::TextBoxDrawingArgsPos tb_args;
int offs = framed_mode ? 1 : 0;
tb_args.pos = { 1 + offs, 12 + offs };
tb_args.base.box_style = { Color::White, Color::DarkBlue };
std::string strength_bar = str::rep_char(' ', 10);
float pc_ratio = m_player.strength / 10.f;
for (int i = 0; i < 10; ++i)
strength_bar[i] = (m_player.strength - m_player.weakness) > static_cast<int>(i*pc_ratio)
? '=' : ' ';
Style style { Color::Green, Color::Transparent2 };
tb_strength.set_text(strength_bar, style);
tb_strength.calc_pre_draw(str::Adjustment::Left);
tb_strength.draw(sh, tb_args);
}
void update_fighting(float real_time_s)
{
if (m_player.health > 0)
{
for (auto& npc : all_npcs)
{
if (npc.health > 0 && npc.state == State::Fight)
{
auto f_calc_damage = [](const Weapon* weapon, int bonus)
{
if (weapon == nullptr)
return 1 + bonus; // Fists with strength bonus
return weapon->damage + bonus;
};
int blind_attack_penalty = (npc.visible ? 0 : 12) + rnd::rand_int(0, 8);
// NPC attack roll.
int npc_attack_roll = rnd::dice(20) + npc.thac0 + npc.get_melee_attack_bonus() - blind_attack_penalty;
// Calculate the player's total armor class.
int player_ac = m_player.calc_armour_class(m_inventory.get());
// Determine if NPC hits the player.
// e.g. d12 + 1 + (2 + 10/2) >= (10 + 10/2).
// d12 + 8 >= 15.
if (npc_attack_roll >= player_ac)
{
// NPC hits the player
int damage = 1; // Default damage for fists
if (npc.weapon_idx != -1)
damage = f_calc_damage(all_weapons[npc.weapon_idx].get(), npc.get_melee_damage_bonus());
// Apply damage to the player
bool was_alive = m_player.health > 0;
m_player.health -= damage;
if (was_alive && m_player.health <= 0)
{
message_handler->add_message(real_time_s,
"You were killed!",
MessageHandler::Level::Fatal);
broadcast([](auto* listener) { listener->on_pc_death(); });
}
}
// Roll a d20 for the player's attack roll (if the NPC is visible).
// If invisible, then roll a d32 instead.
const auto* weapon = m_player.get_selected_melee_weapon(m_inventory.get());
int player_attack_roll = rnd::dice(20) + m_player.thac0 + m_player.get_melee_attack_bonus() - blind_attack_penalty;
int npc_ac = npc.calc_armour_class();
// Determine if player hits the NPC.
if (player_attack_roll >= npc_ac)
{
// PC hits the NPC.
int damage = f_calc_damage(weapon, m_player.get_melee_damage_bonus());
// Apply damage to the NPC.
bool was_alive = npc.health > 0;
npc.health -= damage;
if (was_alive && npc.health <= 0)
{
message_handler->add_message(real_time_s,
"You killed the " + race2str(npc.npc_race) + "!",
MessageHandler::Level::Guide);
broadcast([](auto* listener) { listener->on_npc_death(); });
}
}
}
}
}
}
template<int NR, int NC>
void draw_fighting(ScreenHandler<NR, NC>& sh, const RC& pc_scr_pos, bool do_update_fight, float real_time_s, float sim_time_s)
{
if (m_player.health > 0)
{
for (auto& npc : all_npcs)
{
if (npc.health <= 0)
continue;
if (npc.state == State::Fight)
{
if (npc.trg_info_hostile_npc.once())
{
std::string message = "You are being attacked";
std::string race = race2str(npc.npc_race);
if (npc.visible && !race.empty())
message += " by " + str::indef_art(race);
message += "!";
message_handler->add_message(real_time_s,
message, MessageHandler::Level::Warning);
}
}
else
npc.trg_info_hostile_npc.reset();
if (npc.state == State::Fight)
{
auto npc_scr_pos = m_screen_helper->get_screen_pos(npc.pos);
// [side_case, base_case, side_case]
// Case NW (dp = [1, 1]):
//O#
//#*
// r + [1, 1, 0]
// c + [0, 1, 1]
//
// Case W (dp = [0, 1]):
// #
//O*
// #
// r + [1, 0, -1]
// c + [1, 1, 1]
//
// Case SW (dp = [-1, 1]):
//#*
//O#
// r + [0, -1, -1]
// c + [1, 1, 0]
//
// Case S (dp = [-1, 0]):
//#*#
// O
// r + [-1, -1, -1]
// c + [ 1, 0, -1]
//
// Case SE (dp = [-1, -1]):
//*#
//#O
// r + [-1, -1, 0]
// c + [ 0, -1, -1]
//
// Case E (dp = [0, -1]):
//#
//*O
//#
// r + [-1, 0, 1]
// c + [-1, -1, -1]
//
// Case NE (dp = [1, -1]):
//#O
//*#
// r + [ 0, 1, 1]
// c + [-1, -1, 0]
//
// Case N (dp = [1, 0]):
// O
//#*#
// r + [ 1, 1, 1]
// c + [-1, 0, 1]
auto dp = m_player.pos - npc.pos;
dp.r = math::sgn(dp.r);
dp.c = math::sgn(dp.c);
auto f_dp_to_dir = [](const RC& dp)
{
if (dp == RC { 1, 1 }) return FightDir::NW;
if (dp == RC { 0, 1 }) return FightDir::W;
if (dp == RC { -1, 1 }) return FightDir::SW;
if (dp == RC { -1, 0 }) return FightDir::S;
if (dp == RC { -1, -1 }) return FightDir::SE;
if (dp == RC { 0, -1 }) return FightDir::E;
if (dp == RC { 1, -1 }) return FightDir::NE;
if (dp == RC { 1, 0 }) return FightDir::N;
return FightDir::NUM_ITEMS;
};
const auto num_dir = static_cast<int>(FightDir::NUM_ITEMS);
auto f_calc_fight_offs = [&](const RC& dp)
{
auto dir = static_cast<int>(f_dp_to_dir(dp));
if (dir >= static_cast<int>(FightDir::NUM_ITEMS))
return RC { 0, 0 };
auto r_offs = rnd::randn_select(0.f, 1.f, std::vector {
fight_r_offs[(num_dir + dir - 1)%num_dir],
fight_r_offs[dir],
fight_r_offs[(dir + 1)%num_dir] });
auto c_offs = rnd::randn_select(0.f, 1.f, std::vector {
fight_c_offs[(num_dir + dir - 1)%num_dir],
fight_c_offs[dir],
fight_c_offs[(dir + 1)%num_dir] });
return RC { r_offs, c_offs };
};
auto f_render_fight = [&](PlayerBase* pb, const RC& scr_pos, const RC& offs)
{
// #FIXME:
if (do_update_fight)
{
pb->cached_fight_style = styles::Style
{
color::get_random_color(c_fight_colors),
Color::Transparent2
};
pb->cached_fight_str = rnd::rand_select(c_fight_strings);
}
auto fight_style = pb->cached_fight_style;
auto fight_str = pb->cached_fight_str;
sh.write_buffer(fight_str,
scr_pos.r + offs.r,
scr_pos.c + offs.c,
fight_style);
};
if (do_update_fight)
m_player.cached_fight_offs = f_calc_fight_offs(dp);
auto offs = m_player.cached_fight_offs;
if (m_environment->is_inside_any_room(m_player.pos + offs))
{
f_render_fight(&m_player, npc_scr_pos, offs);
if (do_update_fight && rnd::one_in(npc.visible ? 20 : 28))
{
auto& bs = m_player.blood_splats.emplace_back(m_environment.get(), m_player.pos + offs, rnd::dice(4), sim_time_s, offs);
bs.curr_room = m_player.curr_room;
bs.curr_corridor = m_player.curr_corridor;
if (m_player.is_inside_curr_room())
bs.is_underground = m_environment->is_underground(m_player.curr_room);
else if (m_player.is_inside_curr_corridor())
bs.is_underground = m_environment->is_underground(m_player.curr_corridor);
}
}
if (npc.visible)
{
if (do_update_fight)
npc.cached_fight_offs = f_calc_fight_offs(-dp);
auto offs = npc.cached_fight_offs;
if (m_environment->is_inside_any_room(npc.pos + offs))
{
f_render_fight(&npc, pc_scr_pos, offs);
if (do_update_fight && rnd::one_in(npc.visible ? 20 : 28))
{
auto& bs = npc.blood_splats.emplace_back(m_environment.get(), npc.pos + offs, rnd::dice(4), sim_time_s, offs);
bs.curr_room = npc.curr_room;
bs.curr_corridor = npc.curr_corridor;
bs.is_underground = npc.is_underground;
}
}
}
}
}
}
}
public:
DungGine(const std::string& exe_folder, bool use_fow, DungGineTextureParams texture_params = {})
: message_handler(std::make_unique<MessageHandler>())
, use_fog_of_war(use_fow)
{
m_screen_helper = std::make_unique<ScreenHelper>();
m_environment = std::make_unique<Environment>();
m_environment->load_textures(exe_folder, texture_params);
m_inventory = std::make_unique<Inventory>();
m_keyboard = std::make_unique<Keyboard>(m_environment.get(), m_inventory.get(), message_handler.get(),
m_player,
all_keys, all_lamps, all_weapons, all_potions, all_armour,
all_npcs,
tbd, debug);
}
void load_dungeon(BSPTree* bsp_tree)
{
m_environment->load_dungeon(bsp_tree);
}
void style_dungeon()
{
m_environment->style_dungeon(m_latitude, m_longitude);
}
void set_player_character(char ch) { m_player.character = ch; }
void set_player_style(const Style& style) { m_player.style = style; }
bool place_player(const RC& screen_size, std::optional<RC> world_pos = std::nullopt)
{
const auto world_size = m_environment->get_world_size();
m_screen_helper->set_screen_size(screen_size);
if (world_pos.has_value())
m_player.pos = world_pos.value();
else
m_player.pos = world_size / 2;
m_player.last_pos = m_player.pos;
const auto& room_corridor_map = m_environment->get_room_corridor_map();
const int c_max_num_iters = 1e5_i;
int num_iters = 0;
do
{
for (const auto& cp : room_corridor_map)
if (cp.second->is_inside_corridor(m_player.pos))
{
m_player.is_spawned = true;
m_player.curr_corridor = cp.second;
m_screen_helper->focus_on_world_pos_mid_screen(m_player.pos);
return true;
}
m_player.pos += { rnd::rand_int(-2, +2), rnd::rand_int(-2, +2) };
m_player.pos = m_player.pos.clamp(0, world_size.r, 0, world_size.c);
} while (++num_iters < c_max_num_iters);
return false;
}
// Randomizes the starting direction of the sun and the starting season.
void configure_sun_rand(float minutes_per_day = 20.f, float minutes_per_year = 120.f,
Latitude latitude = Latitude::NorthernHemisphere,
Longitude longitude = Longitude::F,
bool use_per_room_lat_long_for_sun_dir = true)
{
configure_sun(rnd::rand(), minutes_per_day,
static_cast<Season>(rnd::rand_int(0, 7)), minutes_per_year,
latitude, longitude, use_per_room_lat_long_for_sun_dir);
}
void configure_sun(float sun_day_t_offs = 0.f, float minutes_per_day = 20.f,
Season start_season = Season::Spring, float minutes_per_year = 120.f,
Latitude latitude = Latitude::NorthernHemisphere,
Longitude longitude = Longitude::F,
bool use_per_room_lat_long_for_sun_dir = true)
{
m_latitude = latitude;
m_longitude = longitude;
m_season = start_season;
m_sun_year_t_offs = static_cast<float>(start_season)/7;
m_sun_minutes_per_year = minutes_per_year;
m_sun_minutes_per_day = minutes_per_day;
m_sun_day_t_offs = math::clamp(sun_day_t_offs, 0.f, 1.f);
m_sun_dir = m_solar_motion.get_solar_direction(m_latitude, m_longitude, m_season, m_sun_day_t_offs);
m_use_per_room_lat_long_for_sun_dir = use_per_room_lat_long_for_sun_dir;
}
bool place_keys(bool only_place_on_dry_land)
{
const auto world_size = m_environment->get_world_size();
const auto& door_vec = m_environment->fetch_doors();
const int c_max_num_iters = 1e5_i;
int num_iters = 0;
bool valid_pos = false;
for (auto* d : door_vec)
{
if (d->is_locked)
{
Key key;
key.key_id = d->key_id;
do
{
key.pos =
{
rnd::rand_int(0, world_size.r),
rnd::rand_int(0, world_size.c)
};
BSPNode* room = nullptr;
valid_pos = m_environment->is_inside_any_room(key.pos, &room);
if (only_place_on_dry_land &&
room != nullptr &&
!is_dry(m_environment->get_terrain(key.pos)))
{
valid_pos = false;
}
} while (num_iters++ < c_max_num_iters && !valid_pos);
BSPNode* leaf = nullptr;
if (!m_environment->is_inside_any_room(key.pos, &leaf))
return false;
if (leaf != nullptr)
{
key.curr_room = leaf;
key.is_underground = m_environment->is_underground(leaf);
}
all_keys.emplace_back(key);
}
}
return true;
}
bool place_lamps(int num_torches, int num_lanterns, int num_magic_lamps, bool only_place_on_dry_land)
{
const auto world_size = m_environment->get_world_size();
const int c_max_num_iters = 1e5_i;
int num_iters = 0;
bool valid_pos = false;
const int num_lamps = num_torches + num_lanterns + num_magic_lamps;
int ctr_torches = 0;
int ctr_lanterns = 0;
int ctr_magic_lamps = 0;
for (int lamp_idx = 0; lamp_idx < num_lamps; ++lamp_idx)
{
Lamp lamp;
Lamp::LampType lamp_type = Lamp::LampType::Torch;
if (ctr_torches++ < num_torches)