/
gamesession.cpp
1308 lines (1109 loc) · 38.4 KB
/
gamesession.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
/** @file gamesession.cpp Logical game session and saved session marshalling.
*
* @authors Copyright © 2003-2014 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2014 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include "gamesession.h"
#include <de/App>
#include <de/ArrayValue>
#include <de/NumberValue>
#include <de/RecordValue>
#include <de/Time>
#include <de/ZipArchive>
#include <de/game/SavedSession>
#include <doomsday/defs/episode.h>
#include "d_netsv.h"
#include "g_common.h"
#include "hu_menu.h"
#include "hu_inventory.h"
#include "mapstatewriter.h"
#include "p_inventory.h"
#include "p_map.h"
#include "p_mapsetup.h"
#include "p_savedef.h"
#include "p_saveg.h"
#include "p_saveio.h"
#include "p_sound.h"
#include "p_tick.h"
#if __JDOOM__
# include "doomv9mapstatereader.h"
#endif
#if __JHERETIC__
# include "hereticv13mapstatereader.h"
#endif
using namespace de;
using de::game::SavedSession;
using de::game::SessionMetadata;
namespace common {
namespace internal
{
static String composeSaveInfo(SessionMetadata const &metadata)
{
String info;
QTextStream os(&info);
os.setCodec("UTF-8");
// Write header and misc info.
Time now;
os << "# Doomsday Engine saved game session package.\n#"
<< "\n# Generator: GameSession (libcommon)"
<< "\n# Generation Date: " + now.asDateTime().toString(Qt::SystemLocaleShortDate);
// Write metadata.
os << "\n\n" + metadata.asTextWithInfoSyntax() + "\n";
return info;
}
static Block serializeCurrentMapState(bool excludePlayers = false)
{
Block data;
SV_OpenFileForWrite(data);
writer_s *writer = SV_NewWriter();
MapStateWriter().write(writer, excludePlayers);
Writer_Delete(writer);
SV_CloseFile();
return data;
}
}
using namespace internal;
static GameSession *singleton;
static String const internalSavePath = "/home/cache/internal.save";
DENG2_PIMPL(GameSession), public SavedSession::IMapStateReaderFactory
{
String episodeId;
GameRuleset rules;
bool inProgress; ///< @c true= session is in progress / internal.save exists.
Instance(Public *i) : Base(i), inProgress(false)
{
DENG2_ASSERT(singleton == 0);
singleton = thisPublic;
}
inline String userSavePath(String const &fileName) {
return Session::savePath() / fileName + ".save";
}
void cleanupInternalSave()
{
// Ensure the internal save folder exists.
App::fileSystem().makeFolder(internalSavePath.fileNamePath());
// Ensure that any pre-existing internal save is destroyed.
// This may happen if the game was not shutdown properly in the event of a crash.
/// @todo It may be possible to recover this session if it was written successfully
/// before the fatal error occurred.
Session::removeSaved(internalSavePath);
}
/**
* Returns SessionMetadata for the game configuration in progress.
*/
SessionMetadata metadata()
{
DENG2_ASSERT(inProgress);
SessionMetadata meta;
meta.set("gameIdentityKey", Session::gameId());
meta.set("episode", episodeId);
meta.set("userDescription", "(Unsaved)");
meta.set("mapUri", ::gameMapUri.compose());
meta.set("mapTime", ::mapTime);
meta.add("gameRules", self.rules().toRecord()); // Takes ownership.
ArrayValue *array = new ArrayValue;
for(int i = 0; i < MAXPLAYERS; ++i)
{
bool playerIsPresent = CPP_BOOL(players[i].plr->inGame);
*array << NumberValue(playerIsPresent, NumberValue::Boolean);
}
meta.set("players", array); // Takes ownership.
meta.set("sessionId", uint(Timer_RealMilliseconds() + (mapTime << 24)));
return meta;
}
/**
* Update/create a new SavedSession at the specified @a path from the current
* game state.
*/
SavedSession &updateSavedSession(String const &path, SessionMetadata const &metadata)
{
DENG2_ASSERT(inProgress);
LOG_AS("GameSession");
LOG_RES_VERBOSE("Serializing to \"%s\"...") << path;
// Does the .save already exist?
SavedSession *saved = App::rootFolder().tryLocate<SavedSession>(path);
if(saved)
{
DENG2_ASSERT(saved->mode().testFlag(File::Write));
saved->replaceFile("Info") << composeSaveInfo(metadata).toUtf8();
}
else
{
// Create an empty package containing only the metadata.
File &save = App::rootFolder().replaceFile(path);
ZipArchive arch;
arch.add("Info", composeSaveInfo(metadata).toUtf8());
de::Writer(save) << arch;
save.flush();
// We can now reinterpret and populate the contents of the archive.
saved = &save.reinterpret()->as<SavedSession>();
saved->populate();
}
// Save the current game state to the .save package.
#if __JHEXEN__
de::Writer(saved->replaceFile("ACScriptState")).withHeader()
<< Game_ACScriptInterpreter().serializeWorldState();
#endif
Folder &mapsFolder = App::fileSystem().makeFolder(saved->path() / "maps");
DENG2_ASSERT(mapsFolder.mode().testFlag(File::Write));
mapsFolder.replaceFile(gameMapUri.path() + "State")
<< serializeCurrentMapState();
saved->flush(); // No need to populate; FS2 Files already in sync with source data.
saved->cacheMetadata(metadata); // Avoid immediately reopening the .save package.
return *saved;
}
#if __JDOOM__ || __JDOOM64__
void applyRuleFastMonsters(dd_bool fast)
{
static dd_bool oldFast = false;
// Only modify when the rule changes state.
if(fast == oldFast) return;
oldFast = fast;
/// @fixme Kludge: Assumes the original values speed values haven't been modified!
for(int i = S_SARG_RUN1; i <= S_SARG_RUN8; ++i)
{
STATES[i].tics = fast? 1 : 2;
}
for(int i = S_SARG_ATK1; i <= S_SARG_ATK3; ++i)
{
STATES[i].tics = fast? 4 : 8;
}
for(int i = S_SARG_PAIN; i <= S_SARG_PAIN2; ++i)
{
STATES[i].tics = fast? 1 : 2;
}
// Kludge end.
}
#endif
#if __JDOOM__ || __JHERETIC__ || __JDOOM64__
void applyRuleFastMissiles(dd_bool fast)
{
struct missileinfo_s {
mobjtype_t type;
float speed[2];
}
MonsterMissileInfo[] =
{
#if __JDOOM__ || __JDOOM64__
{ MT_BRUISERSHOT, {15, 20} },
{ MT_HEADSHOT, {10, 20} },
{ MT_TROOPSHOT, {10, 20} },
# if __JDOOM64__
{ MT_BRUISERSHOTRED, {15, 20} },
{ MT_NTROSHOT, {20, 40} },
# endif
#elif __JHERETIC__
{ MT_IMPBALL, {10, 20} },
{ MT_MUMMYFX1, {9, 18} },
{ MT_KNIGHTAXE, {9, 18} },
{ MT_REDAXE, {9, 18} },
{ MT_BEASTBALL, {12, 20} },
{ MT_WIZFX1, {18, 24} },
{ MT_SNAKEPRO_A, {14, 20} },
{ MT_SNAKEPRO_B, {14, 20} },
{ MT_HEADFX1, {13, 20} },
{ MT_HEADFX3, {10, 18} },
{ MT_MNTRFX1, {20, 26} },
{ MT_MNTRFX2, {14, 20} },
{ MT_SRCRFX1, {20, 28} },
{ MT_SOR2FX1, {20, 28} },
#endif
{ mobjtype_t(-1), {-1, -1} }
};
static dd_bool oldFast = false;
// Only modify when the rule changes state.
if(fast == oldFast) return;
oldFast = fast;
/// @fixme Kludge: Assumes the original values speed values haven't been modified!
for(int i = 0; MonsterMissileInfo[i].type != -1; ++i)
{
MOBJINFO[MonsterMissileInfo[i].type].speed =
MonsterMissileInfo[i].speed[fast? 1 : 0];
}
// Kludge end.
}
#endif
void applyCurrentRules()
{
if(rules.skill < SM_NOTHINGS)
rules.skill = SM_NOTHINGS;
if(rules.skill > NUM_SKILL_MODES - 1)
rules.skill = skillmode_t(NUM_SKILL_MODES - 1);
if(!IS_NETGAME)
{
#if !__JHEXEN__
rules.deathmatch = false;
rules.respawnMonsters = CommandLine_Check("-respawn")? true : false;
rules.noMonsters = CommandLine_Exists("-nomonsters")? true : false;
#endif
#if __JDOOM__ || __JHERETIC__
// Is respawning enabled at all in nightmare skill?
if(rules.skill == SM_NIGHTMARE)
{
rules.respawnMonsters = cfg.respawnMonstersNightmare;
}
#endif
}
else if(IS_DEDICATED)
{
#if !__JHEXEN__
rules.deathmatch = cfg.netDeathmatch;
rules.respawnMonsters = cfg.netRespawn;
rules.noMonsters = cfg.netNoMonsters;
/*rules.*/cfg.jumpEnabled = cfg.netJumping;
#else
rules.randomClasses = cfg.netRandomClass;
#endif
}
// Fast monsters?
#if __JDOOM__ || __JDOOM64__
dd_bool fastMonsters = rules.fast;
# if __JDOOM__
if(rules.skill == SM_NIGHTMARE)
{
fastMonsters = true;
}
# endif
applyRuleFastMonsters(fastMonsters);
#endif
// Fast missiles?
#if __JDOOM__ || __JHERETIC__ || __JDOOM64__
dd_bool fastMissiles = rules.fast;
# if !__JDOOM64__
if(rules.skill == SM_NIGHTMARE)
{
fastMissiles = true;
}
# endif
applyRuleFastMissiles(fastMissiles);
#endif
NetSv_UpdateGameConfigDescription();
// Update game status cvars:
Con_SetInteger2("game-skill", rules.skill, SVF_WRITE_OVERRIDE);
}
/**
* Constructs a MapStateReader for serialized map state format interpretation.
*/
SavedSession::MapStateReader *makeMapStateReader(
SavedSession const &session, String const &mapUriAsText)
{
de::Uri const mapUri(mapUriAsText, RC_NULL);
File const &mapStateFile = session.locateState<File const>(String("maps") / mapUri.path());
if(!SV_OpenFileForRead(mapStateFile))
{
/// @throw Error The serialized map state file could not be opened for read.
throw Error("GameSession::makeMapStateReader", "Failed to open \"" + mapStateFile.path() + "\" for read");
}
std::unique_ptr<SavedSession::MapStateReader> p;
reader_s *reader = SV_NewReader();
int const magic = Reader_ReadInt32(reader);
if(magic == MY_SAVE_MAGIC || MY_CLIENT_SAVE_MAGIC) // Native format.
{
p.reset(new MapStateReader(session));
}
#if __JDOOM__
else if(magic == 0x1DEAD600) // DoomV9
{
p.reset(new DoomV9MapStateReader(session));
}
#endif
#if __JHERETIC__
else if(magic == 0x7D9A1200) // HereticV13
{
p.reset(new HereticV13MapStateReader(session));
}
#endif
SV_CloseFile();
if(p.get())
{
return p.release();
}
/// @throw Error The format of the serialized map state was not recognized.
throw Error("GameSession::makeMapStateReader", "Unrecognized map state format");
}
void loadSaved(String const &savePath)
{
::briefDisabled = true;
G_StopDemo();
Hu_MenuCommand(MCMD_CLOSEFAST);
FI_StackClear(); // Stop any running InFine scripts.
M_ResetRandom();
if(!IS_CLIENT)
{
for(int i = 0; i < MAXPLAYERS; ++i)
{
player_t *plr = players + i;
if(plr->plr->inGame)
{
// Force players to be initialized upon first map load.
plr->playerState = PST_REBORN;
#if __JHEXEN__
plr->worldTimer = 0;
#else
plr->didSecret = false;
#endif
}
}
}
inProgress = false;
if(savePath.compareWithoutCase(internalSavePath))
{
// Perform necessary prep.
cleanupInternalSave();
// Copy the save to the internal savegame.
Session::copySaved(internalSavePath, savePath);
}
/*
* SavedSession deserialization begins.
*/
SavedSession const &saved = App::rootFolder().locate<SavedSession>(internalSavePath);
SessionMetadata const &metadata = saved.metadata();
// Ensure a complete game ruleset is available.
GameRuleset *newRules;
try
{
newRules = GameRuleset::fromRecord(metadata.subrecord("gameRules"));
}
catch(Record::NotFoundError const &)
{
// The game rules are incomplete. Likely because they were missing from a savegame that
// was converted from a vanilla format (in which most of these values are omitted).
// Therefore we must assume the user has correctly configured the session accordingly.
LOG_WARNING("Using current game rules as basis for loading savegame \"%s\"."
" (The original save format omits this information).")
<< saved.path();
// Use the current rules as our basis.
newRules = GameRuleset::fromRecord(metadata.subrecord("gameRules"), &rules);
}
rules = *newRules;
applyCurrentRules();
delete newRules; newRules = 0;
#if __JHEXEN__
// Deserialize the world ACS state.
if(File const *state = saved.tryLocateStateFile("ACScript"))
{
Game_ACScriptInterpreter().readWorldState(de::Reader(*state).withHeader());
}
#endif
inProgress = true;
episodeId = metadata.gets("episode");
setMap(de::Uri(metadata.gets("mapUri"), RC_NULL));
//::gameMapEntrance = mapEntrance; // not saved??
reloadMap();
#if !__JHEXEN__
::mapTime = metadata.geti("mapTime");
#endif
String const gameMapUriAsText = ::gameMapUri.compose();
makeMapStateReader(saved, gameMapUriAsText)->read(gameMapUriAsText);
}
void setMap(de::Uri const &mapUri)
{
DENG2_ASSERT(inProgress);
::gameMapUri = mapUri;
// Update game status cvars:
Con_SetString2("map-episode", episodeId.toUtf8().constData(), SVF_WRITE_OVERRIDE);
Con_SetUri2 ("map-id", reinterpret_cast<uri_s *>(&::gameMapUri), SVF_WRITE_OVERRIDE);
String hubId;
if(Record const *hubRec = defn::Episode(*self.episodeDef()).tryFindHubByMapId(::gameMapUri.compose()))
{
hubId = hubRec->gets("id");
}
Con_SetString2("map-hub", hubId.toUtf8().constData(), SVF_WRITE_OVERRIDE);
}
/**
* Reload the @em current map.
*
* @param revisit @c true= load progress in this map from a previous visit in the current
* game session. If no saved progress exists then the map will be in the default state.
*/
void reloadMap(bool revisit = false)
{
DENG2_ASSERT(inProgress);
Pause_End();
// Close open HUDs.
for(uint i = 0; i < MAXPLAYERS; ++i)
{
ST_CloseAll(i, true/*fast*/);
}
// Delete raw images to conserve texture memory.
DD_Executef(true, "texreset raw");
// Are we playing a briefing? (No, if we've already visited this map).
if(revisit)
{
briefDisabled = true;
}
char const *briefing = G_InFineBriefing(); // current map
// Restart the map music?
if(!briefing)
{
#if __JHEXEN__
/**
* @note Kludge: Due to the way music is managed with Hexen, unless we explicitly stop
* the current playing track the engine will not change tracks. This is due to the use
* of the runtime-updated "currentmap" definition (the engine thinks music has not changed
* because the current Music definition is the same).
*
* It only worked previously was because the waiting-for-map-load song was started prior
* to map loading.
*
* @todo Rethink the Music definition stuff with regard to Hexen. Why not create definitions
* during startup by parsing MAPINFO?
*/
S_StopMusic();
//S_StartMusic("chess", true); // Waiting-for-map-load song
#endif
S_MapMusic(&gameMapUri);
S_PauseMusic(true);
}
P_SetupMap(gameMapUri);
if(revisit)
{
// We've been here before; deserialize the saved map state.
#if __JHEXEN__
targetPlayerAddrs = 0; // player mobj redirection...
#endif
SavedSession const &saved = App::rootFolder().locate<SavedSession>(internalSavePath);
String const gameMapUriAsText = ::gameMapUri.compose();
std::unique_ptr<SavedSession::MapStateReader> reader(
makeMapStateReader(saved, gameMapUriAsText));
reader->read(gameMapUriAsText);
}
if(!G_StartFinale(briefing, 0, FIMODE_BEFORE, 0))
{
// No briefing; begin the map.
HU_WakeWidgets(-1/* all players */);
G_BeginMap();
}
Z_CheckHeap();
}
#if __JHEXEN__
struct playerbackup_t
{
player_t player;
uint numInventoryItems[NUM_INVENTORYITEM_TYPES];
inventoryitemtype_t readyItem;
};
void backupPlayersInHub(playerbackup_t playerBackup[MAXPLAYERS])
{
DENG2_ASSERT(playerBackup != 0);
for(int i = 0; i < MAXPLAYERS; ++i)
{
playerbackup_t *pb = playerBackup + i;
player_t const *plr = players + i;
std::memcpy(&pb->player, plr, sizeof(player_t));
// Make a copy of the inventory states also.
for(int k = 0; k < NUM_INVENTORYITEM_TYPES; ++k)
{
pb->numInventoryItems[k] = P_InventoryCount(i, inventoryitemtype_t(k));
}
pb->readyItem = P_InventoryReadyItem(i);
}
}
/**
* @param playerBackup Player state backup.
* @param mapEntrance Logical entry point number used to enter the map.
*/
void restorePlayersInHub(playerbackup_t playerBackup[MAXPLAYERS], uint mapEntrance)
{
DENG2_ASSERT(playerBackup != 0);
mobj_t *targetPlayerMobj = 0;
for(int i = 0; i < MAXPLAYERS; ++i)
{
playerbackup_t *pb = playerBackup + i;
player_t *plr = players + i;
ddplayer_t *ddplr = plr->plr;
int oldKeys = 0, oldPieces = 0;
dd_bool oldWeaponOwned[NUM_WEAPON_TYPES];
if(!ddplr->inGame) continue;
std::memcpy(plr, &pb->player, sizeof(player_t));
// Reset the inventory as it will now be restored from the backup.
P_InventoryEmpty(i);
for(int k = 0; k < NUM_INVENTORYITEM_TYPES; ++k)
{
// Don't give back the wings of wrath if reborn.
if(k == IIT_FLY && plr->playerState == PST_REBORN)
continue;
for(uint m = 0; m < pb->numInventoryItems[k]; ++m)
{
P_InventoryGive(i, inventoryitemtype_t(k), true);
}
}
P_InventorySetReadyItem(i, pb->readyItem);
ST_LogEmpty(i);
plr->attacker = 0;
plr->poisoner = 0;
if(IS_NETGAME || rules.deathmatch)
{
// In a network game, force all players to be alive
if(plr->playerState == PST_DEAD)
{
plr->playerState = PST_REBORN;
}
if(!rules.deathmatch)
{
// Cooperative net-play; retain keys and weapons.
oldKeys = plr->keys;
oldPieces = plr->pieces;
for(int k = 0; k < NUM_WEAPON_TYPES; ++k)
{
oldWeaponOwned[k] = plr->weapons[k].owned;
}
}
}
bool wasReborn = (plr->playerState == PST_REBORN);
if(rules.deathmatch)
{
de::zap(plr->frags);
ddplr->mo = 0;
G_DeathMatchSpawnPlayer(i);
}
else
{
if(playerstart_t const *start = P_GetPlayerStart(mapEntrance, i, false))
{
mapspot_t const *spot = &mapSpots[start->spot];
P_SpawnPlayer(i, cfg.playerClass[i], spot->origin[VX],
spot->origin[VY], spot->origin[VZ], spot->angle,
spot->flags, false, true);
}
else
{
P_SpawnPlayer(i, cfg.playerClass[i], 0, 0, 0, 0,
MSF_Z_FLOOR, true, true);
}
}
if(wasReborn && IS_NETGAME && !rules.deathmatch)
{
int bestWeapon = 0;
// Restore keys and weapons when reborn in co-op.
plr->keys = oldKeys;
plr->pieces = oldPieces;
for(int k = 0; k < NUM_WEAPON_TYPES; ++k)
{
if(oldWeaponOwned[k])
{
bestWeapon = k;
plr->weapons[k].owned = true;
}
}
plr->ammo[AT_BLUEMANA].owned = 25; /// @todo values.ded
plr->ammo[AT_GREENMANA].owned = 25; /// @todo values.ded
// Bring up the best weapon.
if(bestWeapon)
{
plr->pendingWeapon = weapontype_t(bestWeapon);
}
}
}
for(int i = 0; i < MAXPLAYERS; ++i)
{
player_t *plr = players + i;
ddplayer_t *ddplr = plr->plr;
if(!ddplr->inGame) continue;
if(!targetPlayerMobj)
{
targetPlayerMobj = ddplr->mo;
}
}
/// @todo Redirect anything targeting a player mobj
/// FIXME! This only supports single player games!!
if(targetPlayerAddrs)
{
for(targetplraddress_t *p = targetPlayerAddrs; p; p = p->next)
{
*(p->address) = targetPlayerMobj;
}
SV_ClearTargetPlayers();
/*
* When XG is available in Hexen, call this after updating target player
* references (after a load) - ds
// The activator mobjs must be set.
XL_UpdateActivators();
*/
}
// Destroy all things touching players.
P_TelefragMobjsTouchingPlayers();
}
#endif // __JHEXEN__
};
GameSession::GameSession()
: d(new Instance(this))
{}
GameSession::~GameSession()
{
LOG_AS("~GameSession");
d.reset();
singleton = 0;
}
GameSession &GameSession::gameSession()
{
DENG2_ASSERT(singleton != 0);
return *singleton;
}
bool GameSession::hasBegun()
{
return d->inProgress;
}
bool GameSession::loadingPossible()
{
return !(IS_CLIENT && !Get(DD_PLAYBACK));
}
bool GameSession::savingPossible()
{
if(IS_CLIENT || Get(DD_PLAYBACK)) return false;
if(!hasBegun()) return false;
if(GS_MAP != G_GameState()) return false;
/// @todo fixme: what about splitscreen!
player_t *player = &players[CONSOLEPLAYER];
if(PST_DEAD == player->playerState) return false;
return true;
}
Record *GameSession::episodeDef()
{
if(hasBegun())
{
/// @todo cache this result?
return Defs().episodes.tryFind("id", d->episodeId);
}
return 0;
}
String GameSession::episodeId()
{
return hasBegun()? d->episodeId : "";
}
Record *GameSession::mapGraphNodeDef()
{
if(Record const *episode = episodeDef())
{
/// @todo cache this result?
return defn::Episode(*episode).tryFindMapGraphNode(::gameMapUri.compose());
}
return 0;
}
Record *GameSession::mapInfo()
{
if(hasBegun())
{
/// @todo cache this result?
return Defs().mapInfos.tryFind("id", ::gameMapUri.compose());
}
return 0;
}
de::Uri GameSession::mapUri()
{
return hasBegun()? ::gameMapUri : de::Uri();
}
de::Uri GameSession::mapUriForNamedExit(String name)
{
LOG_AS("GameSession");
if(Record const *mgNode = mapGraphNodeDef())
{
// Build a lookup table mapping exit ids to exit records.
QMap<String, Record const *> exits;
for(Value const *value : mgNode->geta("exit").elements())
{
Record const &exit = value->as<RecordValue>().dereference();
String id = exit.gets("id");
if(!id.isEmpty())
{
exits.insert(id, &exit);
}
}
//qDebug() << "map exits" << exits;
// Locate the named exit record.
Record const *chosenExit = 0;
if(exits.count() > 1)
{
auto found = exits.constFind(name.toLower());
if(found != exits.constEnd())
{
chosenExit = found.value();
}
else
{
LOG_SCR_WARNING("Episode '%s' map \"%s\" defines no Exit with ID '%s'")
<< d->episodeId
<< ::gameMapUri
<< name;
}
}
else if(exits.count() == 1)
{
chosenExit = exits.first();
String chosenExitId = chosenExit->gets("id");
if(chosenExitId != name.toLower())
{
LOGDEV_SCR_NOTE("Exit ID:%s chosen instead of '%s'")
<< chosenExitId << name;
}
}
else
{
LOG_SCR_WARNING("Episode '%s' map \"%s\" defines no exits")
<< d->episodeId
<< ::gameMapUri;
}
if(chosenExit)
{
return de::Uri(chosenExit->gets("targetMap"), RC_NULL);
}
}
return de::Uri();
}
GameRuleset const &GameSession::rules() const
{
return d->rules;
}
void GameSession::applyNewRules(GameRuleset const &newRules)
{
LOG_AS("GameSession");
d->rules = newRules;
if(hasBegun())
{
d->applyCurrentRules();
LOGDEV_WARNING("Applied new rules while in progress!");
} // Otherwise deferred
}
bool GameSession::progressRestoredOnReload() const
{
if(d->rules.deathmatch) return false; // Never.
#if __JHEXEN__
return true; // Cannot be disabled.
#else
return cfg.loadLastSaveOnReborn;
#endif
}
void GameSession::end()
{
if(!hasBegun()) return;
#if __JHEXEN__
Game_ACScriptInterpreter().reset();
#endif
Session::removeSaved(internalSavePath);
d->inProgress = false;
LOG_MSG("Game ended");
}
void GameSession::endAndBeginTitle()
{
end();
if(char const *script = G_InFine("title"))
{
G_StartFinale(script, FF_LOCAL, FIMODE_NORMAL, "title");
return;
}
/// @throw Error A title script must always be defined.
throw Error("GameSession::endAndBeginTitle", "An InFine 'title' script must be defined");
}
void GameSession::begin(GameRuleset const &newRules, String const &episodeId,
de::Uri const &mapUri, uint mapEntrance)
{
if(hasBegun())
{
/// @throw InProgressError Cannot begin a new session before the current session has ended.
throw InProgressError("GameSession::begin", "The game session has already begun");
}
LOG_MSG("Game begins...");
// Ensure the episode id is good.
if(!Defs().episodes.has("id", episodeId))
{
throw Error("GameSession::begin", "Episode '" + episodeId + "' is not known");
}
// Ensure the map truly exists.
if(!P_MapExists(mapUri.compose().toUtf8().constData()))
{
throw Error("GameSession::begin", "Map \"" + mapUri.asText() + "\" does not exist");
}
// Perform necessary prep.
d->cleanupInternalSave();
G_StopDemo();
// Close the menu if open.
Hu_MenuCommand(MCMD_CLOSEFAST);
// If there are any InFine scripts running, they must be stopped.
FI_StackClear();
// Ignore a game action possibly set by script stop hooks; this is a completely new session.
G_SetGameAction(GA_NONE);
if(!IS_CLIENT)
{
for(uint i = 0; i < MAXPLAYERS; ++i)
{
player_t *plr = players + i;
if(plr->plr->inGame)
{
// Force players to be initialized upon first map load.
plr->playerState = PST_REBORN;
#if __JHEXEN__
plr->worldTimer = 0;
#else
plr->didSecret = false;
#endif