-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGlue.cpp
3228 lines (2587 loc) · 90.3 KB
/
Glue.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
/*
Copyright 2011 Matt DeVore
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "StdAfx.h"
#include "Buffer.h"
#include "Gfx.h"
#include "GfxBasic.h"
#include "GfxPretty.h"
#include "CompactMap.h"
#include "Fixed.h"
#include "Logger.h"
#include "Profiler.h"
#include "MusicLib.h"
#include "Timer.h"
#include "Menu.h"
#include "RawLoad.h"
#include "Weather.h"
#include "Fire.h"
#include "Character.h"
#include "Glue.h"
#include "Deeds.h"
#include "LevelEnd.h"
#include "PowerUp.h"
#include "Net.h"
#include "GammaEffects.h"
#include "BitMatrix.h"
#include "Resource.h"
#include "Keyboard.h"
#include "Difficulty.h"
#include "Sound.h"
using std::bitset;
using std::pair;
using std::max;
using std::min;
using std::swap;
using std::list;
using std::string;
using std::queue;
using std::multiset;
using std::set;
using std::auto_ptr;
using std::endl;
using std::vector;
const int BMP_SPCOUNT = 51;
const int BMP_MPCOUNT = 91;
const int BITMAP_COUNT[] = {0, BMP_SPCOUNT, BMP_MPCOUNT};
const int XCOOR_ACCOMPLISHMENTTEXT = 5;
const int YCOOR_ACCOMPLISHMENTTEXT = 183;
const COLORREF COLOR_ACCOMPLISHMENTTEXT = RGB(0,128,0);
const char *const SYNCRATE_FORMAT = "%d";
const int MAX_TIMERCHAR = 9;
const int MAX_TIMERSECONDS = Fixed(99 * 60 + 59);
const int FRAMERATE_BUFFERLEN = 10;
// INTRODUCTION-RELATED CONSTANTS
const int MAXSTARDIMNESS = 10;
const int NUMSTARS = 1500;
const float TIMETOTHROWBACK = 2.25f;
const float TIMETOSCROLL = 100.0f;
const int TRANSITIONSQUARESIZE = 350;
const float TRANSITIONSECSPERSQUARE = 1.0f/80.0f;
const float MAXFLASHTIME = 5.0f;
const RECT UPPERBLACKAREA = {0,0,800,75}; // left,top,right,bottom
const RECT LOWERBLACKAREA = {0,525,800,600};
const RECT DISPLAYAREA = {0,75,800,525};
const int MODEWIDTH = 800;
const int MODEHEIGHT = 600;
const COLORREF FLASHCOLOR1 = RGB(255,0,0);
const COLORREF FLASHCOLOR2 = RGB(255,255,0);
// how fast to flash
const float FLASHCOLORPERSEC = 0.06f;
const int SCREENROWS = 450;
const float SCREENMINROW = -225;
const float VIEWERDISTANCE = 1000.0f;
const float SCREENWIDTHHALF = 400.0f;
const float STORYWIDTHHALFSQ = 390.0f * 390.0f;
const float STORYANGLE = 3.14159f / 3.0f;
const float SCREENHEIGHTHALF = 225.0f;
const float STORYANGLECOS = cos(STORYANGLE);
const float STORYANGLESIN = sin(STORYANGLE);
const int STORY_WIDTH = 320, STORY_HEIGHT = 591;
// END OF INTRODUCTION-RELATED CONSTANTS
// constants for sound volume and balance calculation are not in floating-point,
// because they wouldn't fit
// use slightly different collision detection in ufo level
const int ALWAYSPUSH = ~(1 << 9);
const int MAX_STRINGLEN = 150;
const int LONG_STRINGLEN = 500;
const int LEVEL_NONE = -1;
const int POINTSFORSUICIDE = -1;
const int POINTSFORHOMICIDE = 1;
const int MAXSCORE = 9999;
const int MINSCORE = -9999;
const DWORD MINFRAMESTOKEEPMESSAGE = 20;
const DWORD FRAMESTODISPLAYMSG = 120;
// coordinates of the character to display durring selection
const int DEMOCHAR_X = 288;
const int DEMOCHAR_Y = 165;
const float DEMOCHAR_SECSTOCHANGEDIR = 1.0f;
const float DEMOCHAR_SECSTOSTEP = 0.1f;
const int DEMOCHAR_X2 = 288; // coordinates to display after selection
const int DEMOCHAR_Y2 = 125;
const int MENUACTION_ESCAPE = 0;
const int MENUACTION_RETURN = 1;
const int SCORE_X_OFFSET = -10;
const unsigned short AMMOCAPACITY[] = {130, 500, 6};
const unsigned short AMMOSTARTING[] = {25, 0, 0};
enum {
GLUESTATE_UNINITIALIZED,
GLUESTATE_INTRODUCTION,
GLUESTATE_MAINMENU,
GLUESTATE_LEVELSELECT,
GLUESTATE_DIFFICULTYSELECT,
GLUESTATE_GAME,
GLUESTATE_CONFIRMQUIT,
GLUESTATE_ENTERNAME,
GLUESTATE_PICKCHARACTER,
GLUESTATE_SELECTCONNECTIONMETHOD,
GLUESTATE_PICKGAME,
GLUESTATE_PICKVIDEOMODE,
GLUESTATE_PRESSESCAPEINSTRUCTIONS,
GLUESTATE_CANSEENORMALLY
};
const char LEVEL_NAMES[][40] =
{"The End of the Beginning",
"Out of the Office and into the Fire",
"Out of the Office and Viva Zepellin!",
"What goes up must come SPLAT! Excuse me",
"Super Mario Super Fun Zone",
"Switzerland",
"Gibs Rum",
"¡Taco Taco!",
"Border Hopping and Famous Landmarks",
"Probe-mania",
"Welcome to Hawaii and Die",
"Tijuana: the Happiest Place on Earth"};
const char LEVEL_IDS[][3] =
{"1_",
"2A", "2B",
"3A", "3B",
"4_",
"5_",
"6A",
"7A",
"6B",
"7B",
"8A"};
const char *MENU_LEVELSELECTHEADER = "PICK A LEVEL";
const char *MENU_MAINMENU =
"ANDRADION 2\n"
"Single Player\n"
"Multiplayer\n"
"Video Options\n"
"Quit\n";
const char *MENU_PRESSESCAPEINSTRUCTIONS =
"PRESS ESC IF THE SCREEN GOES BLACK\n"
"Continue\n"
"Cancel\n";
const char *MENU_PICKVIDEOMODE =
"PICK NEW VIDEO MODE (currently #~)\n"
"1. Fast - 43Hz (for some flatscreens)\n"
"2. Fast normal\n"
"3. Pretty (modern CPUs only)\n";
const char *MENU_CANSEENORMALLY =
"CAN YOU SEE THE SCREEN NORMALLY?\n"
"No\n"
"Yes\n";
const char *MENU_CONFIRMATION =
"ARE YOU SURE?\n"
"No\n"
"Yes\n";
const char *MENU_GAMESLOT =
"PICK ROOM (holding down shift to host)\n"
"Happiness Village\n"
"Insurance Ranch\n"
"Summer School\n"
"Detour Den\n"
"DMV\n"
"Middle School\n"
"Gibbs' Class\n"
"Turnabout Shack\n"
"Joe Henderson\n"
"Robert Semple\n"
"Matthew Turner\n"
"Mary Farmer\n";
const char *MENU_PICKCHARACTER =
"PICK CHARACTER\n"
"Sally\n"
"Milton\n"
"Evil Mr. Turner\n"
"Mr. Turner\n"
"The Switz\n"
"Charmin\n"
"Pepsi One\n"
"Coca-Cola Classic\n"
"Kool-Aid Guy\n";
const char *UNAVAILABLE_LEVEL = "(Unavailable - keep playing!)";
const char *MAXSCORE_MESSAGE = "You got max score!";
enum {GLUEHSM_NOTHING, GLUEHSM_NEWPLAYER, GLUEHSM_SESSIONLOST};
enum {MAINMENU_SP, MAINMENU_MP, MAINMENU_VIDEOOPTIONS, MAINMENU_QUIT,
NUM_MAINMENUITEMS};
enum {ESCAPEINSTRUCTIONS_CONTINUE, ESCAPEINSTRUCTIONS_CANCEL,
NUM_ESCAPEINSTRUCTIONSITEMS};
enum {CONFIRMATION_NO, CONFIRMATION_YES, NUM_CONFIRMATIONITEMS};
enum {RESOURCELOAD_NONE,
RESOURCELOAD_SP,
RESOURCELOAD_MP};
const COLORREF COLOR_HEADING = RGB(0,128,0);
const COLORREF COLOR_UNSELECTED = RGB(255,128,128);
const COLORREF COLOR_SELECTED = RGB(0,255,255);
const COLORREF COLOR_SHADOW = RGB(128,0,0);
const int SHADOW_OFFSET = 1;
// difficulty level used for multiplayer sessions
const int MPDIFFICULTY = 2;
// number of game slots on multiplayer game selects
const int NUM_MPGAMESLOTS = 12;
const int LOADINGMETER_MINHEIGHT = 9;
const int LOADINGMETER_MAXHEIGHT = 15;
const FIXEDNUM FREQFACTOR_OKGOTITBACKWARDS = Fixed(1.2f);
const FIXEDNUM FREQFACTOR_OKGOTITNORMAL = Fixed(0.80f);
const char *const MIDI_RESOURCE_TYPE = "MIDI";
const char *const CMP_RESOURCE_TYPE = "CMP";
const char *const ONE_NUMBER_FORMAT = "%d";
const char *const TWO_NUMBERS_FORMAT = "%d/%d";
const int SCORE_AND_TIMER_Y = 184;
const int WAV_PAUSE = 18;
const float SECONDS_BETWEEN_PAUSE_FLIPS = 0.5f;
const BYTE PAUSE_KEY = 'P';
const int FRAMESTOFLASHSCORE = 150;
const int MAX_CHARS_PER_LINE = 39;
const int CACHED_SECTORS = 9;
const int CACHED_SECTORS_HIGH = 3;
const int CACHED_SECTORS_WIDE = 3;
const double YOUWINTUNE_LENGTH = 4.0f;
const int FONTHEIGHT = 16;
const int FONTWIDTH = 8;
const int FIRST_FONTCHAR = '!';
const int LAST_FONTCHAR = '~';
const FIXEDNUM TIMER_INC_PER_FRAME = Fixed(0.04f);
const char *WINDOW_CAPTION = "Andradion 2";
const int SECTOR_WIDTH = 160;
const int SECTOR_HEIGHT = 100;
const int CACHE_ULEFT = 1;
const int CACHE_UMIDDLE = 2;
const int CACHE_URIGHT = 4;
const int CACHE_CLEFT = 8;
const int CACHE_CMIDDLE = 16;
const int CACHE_CRIGHT = 32;
const int CACHE_BLEFT = 64;
const int CACHE_BMIDDLE = 128;
const int CACHE_BRIGHT = 256;
const int CACHE_BOTTOMROW = 64 | 128 | 256;
const int CACHE_TOPROW = 1 | 2 | 4;
const int CACHE_LEFTCOLUMN = 1 | 8 | 64;
const int CACHE_RIGHTCOLUMN = 4 | 32 | 256;
const int CACHE_EVERYTHING = 511;
// profile names
enum {Main_Game_Loop,
Recaching,
Enemy_Logic,
Hero_Logic,
Draw_Things,
Draw_Character,
U_Cmp_Drawing_N_Weather,
Weather_One_Frame,
Draw_Extra_Stats_N_Msgs,
L_Cmp_Drawing,
Draw_Meters,
NUM_PROFILES};
struct Sector {
auto_ptr<CompactMap> upperCell, lowerCell;
set<int> powerups, enemies;
list<CLevelEnd> levelEnds;
};
typedef char Score[11];
template<class c,class f> inline c Range(c minimum, c maximum, f progress) {
// this function will simply take the progress var,
// and return a value from minimum to maximum, where it would
// return minimum if progress == 0, and maximum if progress == 1
// and anything inbetween would be a linear function derived
// from that range.
return c(f(maximum-minimum) * progress) + minimum;
}
#ifdef _DEBUG
static HGDIOBJ profiler_font;
const int PROFILER_FONT_SIZE = 8;
#endif
static string last_music;
static bool disable_music = false;
static FIXEDNUM max_center_screen_x, max_center_screen_y;
static auto_ptr<Gfx::Font> font;
// x-coordinate of the current top-of-screen message
static int msg_x;
// current message on the screen
static string message;
static HWND hWnd;
static HINSTANCE hInstance;
static int state = GLUESTATE_UNINITIALIZED;
static auto_ptr<CBitMatrix> walking_data; // on = inside, off = outside
static int width_in_tiles, height_in_tiles;
static Array<Sector> sectors;
static int sector_width, sector_height;
static auto_ptr<CMenu> m;
static list<CLevelEnd> lends;
static int model; // character we are playing as
static CTimer char_demo_stepper;
static CTimer char_demo_direction_changer;
// how long the current message has been up
static int frames_for_current_message;
static string KILLEDYOURSELF;
static string KILLED;
static string YOU;
static string YOUKILLED;
static string KILLEDTHEMSELVES;
static string SPKILLED; // string displayed when killed in single player
static vector<POINT> possible_starting_spots;
static FIXEDNUM since_start;
// (used for mp) number of powerups there are when no backpacks are left
static int std_powerups;
static int border_color;
static int led_color;
static int msg_and_score_color;
static int score_flash_color_1;
static int score_flash_color_2;
// these statics make it easier to draw the compact maps faster
// by caching them. This way, the most that can be drawn each frame
// is five, but usually none. Those that are not "redrawn" are cached
// into un-compressed DirectDraw surfaces
static pair<Gfx::Surface *, Gfx::Surface *> cached[CACHED_SECTORS];
// index of upper most-left most sector in the cached array
static int upper_left_sector;
// the column and row of the upper left sector that is cached
static int ul_cached_sector_x, ul_cached_sector_y;
// this array of strings contain data for the user to see
// that concern his accomplishments
enum {DEEDS_SUMMARY, DEEDS_BESTTIME,
DEEDS_BESTSCORE, DEEDS_LINECOUNT};
static string accomplishment_lines[DEEDS_LINECOUNT];
static queue<BYTE> key_presses;
static string player_name;
static int char_demo_direction;
static int level;
static auto_ptr<Gfx::Surface> bitmaps[BMP_MPCOUNT];
static int bitmaps_loaded = 0;
static vector<BYTE> character_sectors;
static float spf;
static DWORD fps;
static vector<CPowerUp> powerups;
static Array<Context> contexts;
static int current_context;
static int max_score;
static auto_ptr<Com> com;
static void Levels(vector<string>& target);
static void ShowMouseCursor();
static void HideMouseCursor();
static pair<const BYTE *, HGLOBAL> LoadLevelPaletteOnly();
static void LoadLevel(bool load_flesh, bool load_bone);
static int MenuLoop();
static void PrepareMenu();
static void LoadBitmaps(int type);
static void Introduction();
static void EndGame();
static void Flip();
static void PrepareForMPGame();
static void GetLevelTimerMinSec(int *min, int *sec, int *hund);
static void Game();
static bool Menu();
static void FlushKeyPresses();
static void AddPossibleStartingSpot(FIXEDNUM x, FIXEDNUM y);
static void LoadCmps(int level_width, int level_height, bool skip_wd_resize);
// draws to the front buffer the current score
static void WriteScorePretty(Score *score, BYTE color);
static void WriteMessageTimerAndScore(Context *cxt);
static void WriteString(int x, int y, const char *str, int color,
int shadow_color = -1);
static void Recache(int flags);
static void PlayMusicAccordingly(int state_change_indicator);
static void FillAccomplishmentLines();
static void FilterMovement(const POINT *start, POINT *end);
static void SetGfx();
static void ReleaseGfxElements();
static void ExtractByte(const BYTE **, int *);
static void ExtractWord(const BYTE **, int *);
static int CalculateSector(Character::Ptr ch);
static Character::Ptr AddCharacter();
static void ClearCharacters(bool keep_first);
static void AnalyzePalette();
static void CleanUpAfterGame();
class NetGameBehavior : public NetFeedback {
public:
NetGameBehavior() : NetFeedback() {}
virtual void SetWeatherState(unsigned int new_state) throw() {
WtrSetState(new_state);
}
virtual void EnemyFiresBazooka(unsigned int index,
unsigned short x_hit,
unsigned short y_hit) throw() {
Fire *new_fire = Fire::UnusedSlot();
if (new_fire) {
Character::Ptr ch(Character::Get(index+1));
new_fire->Setup(ch->X(), ch->Y(),
FixedCnvTo<long>(x_hit), FixedCnvTo(y_hit));
}
}
virtual void EnemyFiresPistol(unsigned int index) throw() {
Fire *new_fire = Fire::UnusedSlot();
if (new_fire) {
Character::Ptr ch(Character::Get(index+1));
new_fire->Setup(ch->X(), ch->Y(), ch->Direction(), WEAPON_PISTOL, true);
}
}
virtual void EnemyFiresMachineGun(unsigned int index) throw() {
Fire *new_fire = Fire::UnusedSlot();
if (new_fire) {
Character::Ptr ch(Character::Get(index+1));
new_fire->Setup(ch->X(), ch->Y(),
ch->Direction(), WEAPON_MACHINEGUN, true);
}
}
virtual void PickUpPowerUp(unsigned short index) throw() {
if (index < powerups.size()) {
vector<CPowerUp>::iterator p = powerups.begin() + index;
if (p->Regenerates()) {
p->PickUp();
} else {
*p = powerups[powerups.size() - 1];
powerups.resize(powerups.size() - 1);
}
}
}
virtual void ClearEnemyArray() throw() {
logger << "Call to clear enemy array" << endl;
ClearCharacters(true);
}
virtual void CreateEnemy(unsigned int model) throw() {
AddCharacter()->Setup(model);
}
virtual void SetEnemyWeapon(unsigned int index, unsigned int weapon)
throw() {
Character::Get(index+1)->SetWeapon(weapon);
}
virtual void SetEnemyPosition(unsigned int index,
unsigned short x,
unsigned short y) throw() {
Character::Get(index+1)->SetPosition
(FixedCnvTo<long>(x), FixedCnvTo<long>(y));
}
virtual void SetEnemyDirection(unsigned int index,
unsigned int direction) throw() {
Character::Get(index+1)->SetDirection(direction);
}
virtual void WalkEnemy(unsigned int index) throw() {
Character::Ptr ch(Character::Get(index+1));
ch->Walk(false);
ch->TryToMove();
}
virtual void KillEnemy(unsigned int index, WORD *ammo) throw() {
vector<CPowerUp>::iterator p;
FIXEDNUM got_data[WEAPON_COUNT];
Character::Ptr ch(Character::Get(index+1));
powerups.resize(powerups.size() + 1);
p = powerups.end() - 1;
for (int i = 0; i < WEAPON_COUNT; i++) {
got_data[i] = (FIXEDNUM)ammo[i];
}
p->Setup(ch->X(), ch->Y(), got_data);
}
virtual void HurtEnemy(unsigned int index) throw() {
Character::Get(index+1)->Hurt();
}
virtual void HurtHero(unsigned int weapon_type) throw() {
Character::Get(0)->SubtractHealth(weapon_type);
}
virtual void PlayerLeaving(const char *name) throw() {
try {
int name_strlen = strlen(name);
string format;
GluStrLoad(IDS_OLDPLAYER, format);
Buffer buf(name_strlen + format.length() + 1);
sprintf((char *)buf.Get(), format.c_str(), name);
logger << "Posting message of player leaving to screen" << endl;
GluPostMessage((const char *)buf.Get());
} catch (std::bad_alloc& ba) { }
}
virtual void PlayerJoining(const char *name) throw() {
try {
int name_strlen = strlen(name);
string format;
GluStrLoad(IDS_NEWPLAYER, format);
Buffer buf(name_strlen + format.length() + 1);
sprintf((char *)buf.Get(), format.c_str(), name);
logger << "Posting player join message to screen" << endl;
GluPostMessage((const char *)buf.Get());
} catch (std::bad_alloc& ba) { }
}
};
// dialog proc. This is a callback function that
// sends messages to the code entity that defines
// how the intro box works. This box's controls
// and the locations of them are defined in the
// resource
static BOOL CALLBACK CfgDlgProc(HWND hwndDlg, UINT uMsg,
WPARAM wParam, LPARAM) {
switch(uMsg) {
case WM_COMMAND: {
// get the identifier of the control, which is always passed
// through the lower word of the wParam parameter
WORD ctrl = LOWORD(wParam);
if(IDLAUNCH == ctrl || IDQUIT == ctrl || IDLAUNCHWITHOUTMUSIC == ctrl) {
// the launch or quit or launch w/o music btn was pressed
char txt[MAX_STRINGLEN];
int sync_rate;
// get the text of the sync rate edit box, where the user specifies
// how often andradion 2 peers communicate their location
GetDlgItemText(hwndDlg, IDC_SYNC, txt, MAX_STRINGLEN);
// set sync rate to a value which will be detected
// as invalid. If the scanf function does not convert
// the string because it is invalid or something,
// and the sync_rate var isn't touched, then the if()
// block will see the error
sync_rate = 0;
// scan the sync rate from txt using the mapped tchar function
// of scanf
sscanf(txt, SYNCRATE_FORMAT, &sync_rate);
// see if the sync_rate was invalid
if(sync_rate < MIN_SYNCRATE || sync_rate > MAX_SYNCRATE) {
// invalid sync rate was entered
// display error
// load two strings that make up the message box of the error
string error_msg;
GluStrLoad(IDS_INVALIDSYNCRATE, error_msg);
MessageBox(hwndDlg, error_msg.c_str(),
WINDOW_CAPTION, MB_ICONSTOP);
} else {
DeeSetSyncRate(sync_rate);
// a valid sync rate was entered
if(IDLAUNCHWITHOUTMUSIC == ctrl) {
MusicStop();
disable_music = true;
}
EndDialog(hwndDlg, LOWORD(wParam));
}
}
return FALSE;
}
case WM_SHOWWINDOW: {
// use this opportunity to do somethings to initialize
// set the hyper welcome box music
GluSetMusic(false,IDR_WELCOMEBOXMUSIC);
char number_buffer[MAX_STRINGLEN];
itoa(DeeSyncRate(), number_buffer, 10);
// set the text in the sync rate edit box to what we just got
// from the sprintf function
SetDlgItemText(hwndDlg,IDC_SYNC,number_buffer);
return FALSE;
}
// we want the currently-in-focus control to be chosen automatically
case WM_INITDIALOG: return TRUE;
default: return FALSE;
}
}
static int GetSpeed() {return fps / 25;}
static void SetSpeed(int index) {
logger << "SetSpeed(" << index << ") called" << endl;
switch(NetInGame() ? 1 : index) {
case 0:
// slow the game down
spf = 0.08f; // more seconds per frame
fps = 12; // fewer frames per second
SndSetPlaybackFrequency(Fixed(0.5f));
SetTempo(DefaultTempo()/2.0f);
WtrSetSoundPlaybackFrequency(FixedCnvFrom<long>(Fixed(0.5f)
* SOUNDRESOURCEFREQ));
break;
case 1:
// normal game speed
spf = 0.04f;
fps = 25;
SndSetPlaybackFrequency(Fixed(1.0f));
SetTempo(DefaultTempo());
WtrSetSoundPlaybackFrequency(FixedCnvFrom<long>(Fixed(1.0f)
* SOUNDRESOURCEFREQ));
break;
case 2:
// speed the game up
spf = 0.02f;
fps = 50;
SndSetPlaybackFrequency(Fixed(2.0f));
SetTempo(DefaultTempo()*2.0f);
WtrSetSoundPlaybackFrequency(FixedCnvFrom<long>(Fixed(2.0f)
* SOUNDRESOURCEFREQ));
}
logger << "SetSpeed() returning" << endl;
}
class StarFiller : public Gfx::SurfaceFiller {
public:
virtual void Fill(BYTE *starsb, int p,
Gfx::Surface *surf) throw() {
logger << "Filling star surface" << endl;
BYTE *clearing_point = starsb;
for (int y = 0; y < surf->GetHeight(); y++) {
memset(clearing_point, 0, surf->GetWidth());
clearing_point += p;
}
for (int i = 0; i < NUMSTARS; i++) {
// plot a bunch of stars
// make a small plus sign for each star
int x = (rand()%(surf->GetWidth()-2))+1;
int y = (rand()%(surf->GetHeight()-2))+1;
BYTE c = 255-(rand()%MAXSTARDIMNESS);
starsb[y*p+x] = c;
starsb[(y+1)*p+x] = starsb[(y-1)*p+x] = starsb[y*p+x+1] =
starsb[y*p+x-1] = c/2;
}
logger << "Done filling star surface" << endl;
}
};
static void Introduction() {
short STORYCOOR[SCREENROWS], STORYWIDTH[SCREENROWS];
// calculate STORYCOOR and STORYWIDTH values
for (int i = 0; i < SCREENROWS; i++) {
float Y = SCREENMINROW + (float)i;
float MplusY = Y + SCREENHEIGHTHALF;
float S = MplusY
* (STORYANGLECOS + STORYANGLESIN
* tan(STORYANGLE + atan(Y / VIEWERDISTANCE)));
float Z = STORYANGLESIN * S;
STORYCOOR[i] = (short)(S / 4.0f);
STORYWIDTH[i] = (short)(VIEWERDISTANCE * STORYWIDTHHALFSQ
/ SCREENWIDTHHALF
/ (Z + VIEWERDISTANCE));
}
auto_ptr<Gfx::Surface> stars, story, turner;
CTimer timer, inc_or_dec;
RECT dest, source;
int inx = DISPLAYAREA.right - DISPLAYAREA.left;
int iny = DISPLAYAREA.bottom - DISPLAYAREA.top;
state = GLUESTATE_INTRODUCTION; // we are in the intro right now
logger << "Entering graphics mode" << endl;
assert(!Gfx::Get());
GfxBasic::Initialize(hWnd, MODEWIDTH, MODEHEIGHT, 0, MODEWIDTH, MODEHEIGHT);
logger << "Setup the Introduction palette" << endl;
GamInitializeWithIntroPalette();
logger << "Create starscape surface" << endl;
stars = Gfx::Get()->CreateSurface
(inx, iny, auto_ptr<Gfx::SurfaceFiller>(new StarFiller()));
logger << "Load story bmp" << endl;
story = Gfx::BitmapSurfaceFiller::CreateSurfaceFromBitmap
(Gfx::Get(), hInstance, MAKEINTRESOURCE(IDB_STORY));
logger << "Load Turner in crosshairs bmp" << endl;
turner = Gfx::BitmapSurfaceFiller::CreateSurfaceFromBitmap
(Gfx::Get(), hInstance, MAKEINTRESOURCE(IDB_TURNER));
AutoComPtr<IDirectSoundBuffer> warpout;
DWORD warp_status; // playing or not of the above sound
// load the warpout sound
auto_ptr<Resource> warpout_resource(new Resource("DAT", "SFX"));
void *warpout_data = (void *)warpout_resource->GetPtr();
// we locked it successfully
int warpout_size = *(int *)warpout_data;
warpout_data = (void *)(warpout_resource->GetPtr(sizeof(int)));
warpout = CreateSBFromRawData
(SndDirectSound().Get(), warpout_data, warpout_size, 0,
SOUNDRESOURCEFREQ, SOUNDRESOURCEBPS, 1);
warpout_resource.reset();
logger << "Play Intro Music" << endl;
GluSetMusic(false, IDR_INTROMUSIC);
// load polygon data for splash screen
int polygon_count, *vertex_counts, *polygon_vertices;
auto_ptr<Resource> splash_resource
(new Resource("DAT", MAKEINTRESOURCE(IDR_SPLASH)));
const BYTE *locked = splash_resource->GetPtr();
// load the meaningful data
polygon_count = (int)*locked++;
// get the vertex counts
int total_vertex_count = 0;
vertex_counts = new int[polygon_count];
for (int i = 0; i < polygon_count; i++) {
vertex_counts[i] = (int)*locked++;
total_vertex_count += vertex_counts[i];
}
// get each vertex coordinate
polygon_vertices = new int[total_vertex_count * 2];
for (int i = 0; i < total_vertex_count; i++) {
polygon_vertices[i * 2] = (int)*locked++;
polygon_vertices[i * 2+1] = (int)*locked++;
polygon_vertices[i * 2] *= MODEWIDTH;
polygon_vertices[i * 2] /= 0x100;
polygon_vertices[i * 2+1] *= MODEHEIGHT;
polygon_vertices[i * 2+1] /= 0x100;
}
splash_resource.reset();
if (LogResult("Value of warpout pointer", warpout)) {
LogResult("Play warpout sound", warpout->Play(0,0,0));
}
CTimer total_flash;
// we need a red brush and a red pen, and a yellow brush and a yellow pen
HBRUSH brush1 = CreateSolidBrush(FLASHCOLOR1);
HBRUSH brush2 = CreateSolidBrush(FLASHCOLOR2);
HPEN pen1 = CreatePen(PS_SOLID, 1, FLASHCOLOR1);
HPEN pen2 = CreatePen(PS_SOLID, 1, FLASHCOLOR2);
do {
CTimer frame; // this makes sure we don't flip too quick
HDC dc = GfxBasic::Get()->GetDC();
if(dc) {
swap(brush1, brush2);
swap(pen1, pen2);
// blit the background
HBRUSH old_brush = (HBRUSH)SelectObject(dc, (HGDIOBJ)brush1);
Rectangle(dc, 0, 0, MODEWIDTH, MODEHEIGHT);
// select the objects for the text
SelectObject(dc, (HGDIOBJ)brush2);
HPEN old_pen = (HPEN)SelectObject(dc,(HGDIOBJ)pen2);
// blit the text
PolyPolygon(dc, (const POINT *)polygon_vertices,
vertex_counts, polygon_count);
SelectObject(dc, (HGDIOBJ)old_brush);
SelectObject(dc, (HGDIOBJ)old_pen);
GfxBasic::Get()->ReleaseDC(dc);
} while (frame.SecondsPassed32() < FLASHCOLORPERSEC);
Gfx::Get()->Flip();
} while ((!warpout || SUCCEEDED(warpout->GetStatus(&warp_status)))
&& (warp_status & DSBSTATUS_PLAYING)
&& (total_flash.SecondsPassed32() < MAXFLASHTIME));
// get rid of those extra brushes we made
DeleteObject((HGDIOBJ)brush1);
DeleteObject((HGDIOBJ)brush2);
DeleteObject((HGDIOBJ)pen1);
DeleteObject((HGDIOBJ)pen2);
warpout.Reset();
Delete(&polygon_vertices);
Delete(&vertex_counts);
// done loading!
timer.Restart();
FlushKeyPresses();
inc_or_dec.Restart();
do {
// put the stars and black spots on the back buffer
stars->Draw(DISPLAYAREA.left, DISPLAYAREA.top, false);
Gfx::Get()->Rectangle(&UPPERBLACKAREA, 0, false);
Gfx::Get()->Rectangle(&LOWERBLACKAREA, 0, false);
float progress = timer.SecondsPassed32() / TIMETOTHROWBACK;
dest.left = Range(0,iny/2,progress) + (inx - iny) / 2;
dest.top = Range(0,iny/2,progress) + DISPLAYAREA.top;
dest.right = Range(iny,iny/2,progress) + (inx - iny) / 2;
dest.bottom = Range(iny,iny/2,progress) + DISPLAYAREA.top;
if(dest.left >= dest.right || dest.top >= dest.bottom) {
break;
}
// put the turner photo on the back buffer
turner->DrawScale(&dest, 0, true);
Flip();
} while (timer.SecondsPassed32() <= TIMETOTHROWBACK
&& key_presses.empty());
inc_or_dec.Pause();
turner.reset();
// now show the story
FlushKeyPresses();
timer.Restart();
int max_storyy = (int)(STORY_HEIGHT + iny);
bool key_pressed = false;
do {
// put the stars and black spots on the back buffer
stars->Draw(DISPLAYAREA.left, DISPLAYAREA.top, false);
Gfx::Get()->Rectangle(&UPPERBLACKAREA, 0, false);
Gfx::Get()->Rectangle(&LOWERBLACKAREA, 0, false);
int storyy=Range(0,max_storyy,timer.SecondsPassed32()/TIMETOSCROLL);
source.left = 0;
source.right = STORY_WIDTH;
source.top = storyy;
source.bottom = storyy+1;
dest.top = DISPLAYAREA.bottom - 1;
dest.bottom = DISPLAYAREA.bottom;
for(int index = 0; index < SCREENROWS; index++) {
dest.left = MODEWIDTH / 2 - STORYWIDTH[index];
dest.right = MODEWIDTH - dest.left;
dest.top--;
dest.bottom--;
source.top = storyy - STORYCOOR[index];
if(source.top < STORY_HEIGHT && source.top >= 0
&& dest.right > dest.left) {
source.bottom = source.top + 1;
story->DrawScale(&dest, &source, true);
}
}
while (!key_pressed && !key_presses.empty()) {
switch(key_presses.front()) {
case VK_NEXT:
logger << "PGDN" << endl;
timer += inc_or_dec;
key_presses.pop();
if(timer.SecondsPassed32() >= TIMETOSCROLL) {
timer -= inc_or_dec;
}
break;
case VK_PRIOR:
logger << "PGUP" << endl;
timer -= inc_or_dec;
key_presses.pop();
if(0 > timer.SecondsPassedInt()) {
timer.Restart();
}
break;
case VK_SPACE:
logger << "SPACE" << endl;
if(timer.Paused()) {
timer.Resume();
} else {
timer.Pause();