]> icculus.org git repositories - taylor/freespace2.git/blob - src/playerman/managepilot.cpp
merge in some code cleanup
[taylor/freespace2.git] / src / playerman / managepilot.cpp
1 /*
2  * Copyright (C) Volition, Inc. 1999.  All rights reserved.
3  *
4  * All source code herein is the property of Volition, Inc. You may not sell 
5  * or otherwise commercially exploit the source or things you created based on
6  * the source.
7  */
8
9 /*
10  * $Logfile: /Freespace2/code/Playerman/ManagePilot.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * ManagePilot.cpp has code to load and save pilot files, and to select and 
16  * manage the pilot
17  *
18  * $Log$
19  * Revision 1.6  2004/07/04 11:41:24  taylor
20  * warning fixes, cross platform pilot compat with OSX-Linux-Windows
21  *
22  * Revision 1.5  2003/05/25 02:30:43  taylor
23  * Freespace 1 support
24  *
25  * Revision 1.4  2002/06/09 04:41:25  relnev
26  * added copyright header
27  *
28  * Revision 1.3  2002/06/09 03:16:05  relnev
29  * added _splitpath.
30  *
31  * removed unneeded asm, old sdl 2d setup.
32  *
33  * fixed crash caused by opengl_get_region.
34  *
35  * Revision 1.2  2002/05/07 03:16:50  theoddone33
36  * The Great Newline Fix
37  *
38  * Revision 1.1.1.1  2002/05/03 03:28:11  root
39  * Initial import.
40  *
41  * 
42  * 41    9/13/99 4:52p Dave
43  * RESPAWN FIX
44  * 
45  * 40    9/01/99 10:09a Dave
46  * Pirate bob.
47  * 
48  * 39    8/26/99 8:49p Jefff
49  * old player file compatibility with new medal stuff
50  * 
51  * 38    8/22/99 5:53p Dave
52  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
53  * instead of ship designations for multiplayer players.
54  * 
55  * 37    8/16/99 4:06p Dave
56  * Big honking checkin.
57  * 
58  * 36    8/11/99 11:36a Jefff
59  * added compatibility w/ fs2 demo plr version
60  * 
61  * 35    8/10/99 3:46p Jefff
62  * changes for Intelligence section of new tech room
63  * 
64  * 34    8/04/99 11:38p Andsager
65  * make new pilot detail level match registry info.
66  * 
67  * 33    8/02/99 9:55p Dave
68  * Hardcode a nice hud color config for the demo.
69  * 
70  * 32    8/02/99 9:13p Dave
71  * Added popup tips.
72  * 
73  * 31    8/01/99 12:39p Dave
74  * Added HUD contrast control key (for nebula).
75  * 
76  * 30    7/30/99 10:31p Dave
77  * Added comm menu to the configurable hud files.
78  * 
79  * 29    7/29/99 10:47p Dave
80  * Standardized D3D fogging using vertex fog. Shook out Savage 4 bugs.
81  * 
82  * 28    7/29/99 12:05a Dave
83  * Nebula speed optimizations.
84  * 
85  * 27    7/24/99 1:54p Dave
86  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
87  * missions.
88  * 
89  * 26    6/22/99 7:03p Dave
90  * New detail options screen.
91  * 
92  * 25    6/16/99 4:06p Dave
93  * New pilot info popup. Added new draw-bitmap-as-poly function.
94  * 
95  * 24    6/11/99 11:13a Dave
96  * last minute changes before press tour build.
97  * 
98  * 23    6/08/99 1:14a Dave
99  * Multi colored hud test.
100  * 
101  * 22    5/03/99 8:33p Dave
102  * New version of multi host options screen.
103  * 
104  * 21    3/24/99 4:05p Dave
105  * Put in support for assigning the player to a specific squadron with a
106  * specific logo. Preliminary work for doing pos/orient checksumming in
107  * multiplayer to reduce bandwidth.
108  * 
109  * 20    1/30/99 1:29a Dave
110  * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
111  * screen.  Fixed beam weapon death messages.
112  * 
113  * 19    1/29/99 2:08a Dave
114  * Fixed beam weapon collisions with players. Reduced size of scoring
115  * struct for multiplayer. Disabled PXO.
116  * 
117  * 18    1/21/99 2:06p Dave
118  * Final checkin for multiplayer testing.
119  * 
120  * 17    1/15/99 2:49p Dave
121  * Fixed creation of pilots.
122  * 
123  * 16    1/14/99 6:06p Dave
124  * 100% full squad logo support for single player and multiplayer.
125  * 
126  * 15    1/12/99 3:15a Dave
127  * Barracks screen support for selecting squad logos. We need real artwork
128  * :)
129  * 
130  * 14    1/06/99 2:24p Dave
131  * Stubs and release build fixes.
132  * 
133  * 13    12/14/98 12:13p Dave
134  * Spiffed up xfer system a bit. Put in support for squad logo file xfer.
135  * Need to test now.
136  * 
137  * 12    11/20/98 11:16a Dave
138  * Fixed up IPX support a bit. Making sure that switching modes and
139  * loading/saving pilot files maintains proper state.
140  * 
141  * 11    11/19/98 4:51p Dave
142  * Ignore multiplayer protocol settings in the pilot file for now.
143  * 
144  * 10    11/19/98 4:19p Dave
145  * Put IPX sockets back in psnet. Consolidated all multiplayer config
146  * files into one.
147  * 
148  * 9     10/13/98 2:47p Andsager
149  * Remove reference to Tech_shivan_species_avail
150  * 
151  * 8     10/13/98 9:29a Dave
152  * Started neatening up freespace.h. Many variables renamed and
153  * reorganized. Added AlphaColors.[h,cpp]
154  * 
155  * 7     10/12/98 9:30a Andsager
156  * Clean up barracks.cpp.  Remove unneeded ".h" files from ManagePilot
157  * 
158  * 6     10/09/98 5:17p Andsager
159  * move barracks screen into barracks.cpp
160  * 
161  * 5     10/09/98 2:57p Dave
162  * Starting splitting up OS stuff.
163  * 
164  * 4     10/08/98 9:19a Andsager
165  * Clean up pilot player read and write, starting with new version.
166  * 
167  * 3     10/07/98 6:27p Dave
168  * Globalized mission and campaign file extensions. Removed Silent Threat
169  * special code. Moved \cache \players and \multidata into the \data
170  * directory.
171  * 
172  * 2     10/07/98 10:53a Dave
173  * Initial checkin.
174  * 
175  * 1     10/07/98 10:50a Dave
176  * 
177  * 279   9/21/98 10:02p Dave
178  * Last minute changes to techroom weapon/ship/species stuff.
179  * 
180  * 278   9/08/98 12:10p Andsager
181  * Fixed a bug with saving ship and weapon info techroom flags.
182  * 
183  * 277   9/01/98 4:25p Dave
184  * Put in total (I think) backwards compatibility between mission disk
185  * freespace and non mission disk freespace, including pilot files and
186  * campaign savefiles.
187  * 
188  * 276   6/09/98 10:31a Hoffoss
189  * Created index numbers for all xstr() references.  Any new xstr() stuff
190  * added from here on out should be added to the end if the list.  The
191  * current list count can be found in FreeSpace.cpp (search for
192  * XSTR_SIZE).
193  * 
194  * 275   6/05/98 9:49a Lawrance
195  * OEM changes
196  * 
197  * 274   6/01/98 11:43a John
198  * JAS & MK:  Classified all strings for localization.
199  * 
200  * 273   5/26/98 11:53a Allender
201  * fix multiplayer problems and sexpression crash
202  * 
203  * 272   5/24/98 2:46p Lawrance
204  * Fix bug where skill level would be reset to default when switching
205  * between pilots
206  * 
207  * 271   5/23/98 4:02p Allender
208  * version change
209  * 
210  * 270   5/23/98 2:41p Mike
211  * Make Easy the default skill level and prevent old pilot's skill level
212  * from carrying into new pilot.
213  *
214 */
215
216 #include <errno.h>
217 #include "managepilot.h"
218 #include "2d.h"
219 #include "freespace.h"
220 #include "hudsquadmsg.h"
221 #include "sound.h"
222 #include "multi.h"
223 #include "eventmusic.h"
224 #include "audiostr.h"
225 #include "osregistry.h"
226 #include "font.h"
227 #include "playermenu.h"
228 #include "missionshipchoice.h"
229 #include "hudconfig.h"
230 #include "popup.h"
231 #include "redalert.h"
232 #include "techmenu.h"
233 #include "joy.h"
234 #include "mouse.h"
235 #include "cutscenes.h"
236 #include "bmpman.h"
237 #include "key.h"
238
239 // update this when altering data that is read/written to .PLR file
240 #ifndef MAKE_FS1
241 #define CURRENT_PLAYER_FILE_VERSION                             140
242 #else
243 // 141: add more FS1 detail settings
244 // 142: HUD config settings (brightness)
245 #define CURRENT_PLAYER_FILE_VERSION                             142
246 #define PREVIOUS_PLAYER_FILE_VERSION                    140
247 #endif
248 #define FS2_DEMO_PLAYER_FILE_VERSION                            135
249 #ifndef MAKE_FS1
250 #define LOWEST_COMPATIBLE_PLAYER_FILE_VERSION   CURRENT_PLAYER_FILE_VERSION                     // demo plr files should work in final
251 #else
252 #define LOWEST_COMPATIBLE_PLAYER_FILE_VERSION   PREVIOUS_PLAYER_FILE_VERSION
253 #endif
254
255 // keep track of pilot file changes here 
256 // version 2    : Added squad logo filename
257 // version 3    : Changed size of scoring struct. use ushort instead of ints for storing alltime kills by ship type
258 // version 4/5 : Added squadron name field
259 // version 6    : changed max length on a multiplayer options field
260 // version 130  : changed size of hud config struct
261 // version 133 : misc changes. new hud gauge
262 // version 134 : added HUD contrast toggle key
263 // version 135 : added tips flag  (THIS IS THE DEMO VERSION - RETAIN COMPATIBILITY FROM HERE ON OUT)
264 // version 136 : added intelligence flags to tech room visibility data
265 // version 137 : 2 new HUD gauges. 
266 // version 138  : new multiplayer config
267 // version 139 : # medals increased - added compatibility with old plr file versions
268 // version 140 : ships table reordered. clear out old pilot files
269 // search for PLAYER INIT for new pilot initialization stuff. I _think_ its in the right spot for now
270 #define PLR_FILE_ID     0x46505346      // FPSF, unique signiture to identify a .PLR file (FreeSpace Player File)  // FPSF appears as FSPF in file.
271
272 // Current content of a .PLR file
273 //
274
275 // Global variables
276 int Player_sel_mode;
277
278 // pilot pic image list stuff ( call pilot_load_pic_list() to make these valid )
279 char Pilot_images_arr[MAX_PILOT_IMAGES][MAX_FILENAME_LEN];
280 char *Pilot_image_names[MAX_PILOT_IMAGES];
281 int Num_pilot_images = 0;
282
283 // squad logo list stuff (call pilot_load_squad_pic_list() to make these valid )
284 char Pilot_squad_images_arr[MAX_PILOT_IMAGES][MAX_FILENAME_LEN];
285 char *Pilot_squad_image_names[MAX_PILOT_IMAGES];
286 int Num_pilot_squad_images = 0;
287
288 static uint Player_file_version;
289
290 // forward declarations
291 void read_detail_settings(CFILE *file, int Player_file_version);
292 void write_detail_settings(CFILE *file);
293 void read_stats_block(CFILE *file, int Player_file_version, scoring_struct *stats);
294 void write_stats_block(CFILE *file, scoring_struct *stats);
295 void read_multiplayer_options(player *p,CFILE *file);
296 void write_multiplayer_options(player *p,CFILE *file);
297
298 static SDL_Keycode keycode_translate_from(short keycode);
299 static short keycode_translate_to(SDL_Keycode keycode);
300
301 // internal function to delete a player file.  Called after a pilot is obsoleted, and when a pilot is deleted
302 // used in barracks and player_select
303 void delete_pilot_file( const char *pilot_name, int single )
304 {
305         char filename[MAX_FILENAME_LEN];
306         char basename[MAX_FILENAME_LEN];
307
308         // get the player file.
309
310         base_filename(pilot_name, basename, SDL_arraysize(basename));
311
312         SDL_strlcpy( filename, basename, SDL_arraysize(filename) );
313         SDL_strlcat(filename, NOX(".plr"), SDL_arraysize(filename) );
314         if (Player_sel_mode == PLAYER_SELECT_MODE_SINGLE){
315                 cf_delete(filename, CF_TYPE_SINGLE_PLAYERS);
316         } else {
317                 cf_delete(filename, CF_TYPE_MULTI_PLAYERS);
318         }
319
320         // we must try and delete the campaign save files for a pilot as well.
321         mission_campaign_delete_all_savefiles( basename, !single );
322 }
323
324 // check if a pilot file is valid or not (i.e. is usable, not out of date, etc)
325 // used in barracks and player_select
326 int verify_pilot_file(const char *filename, int single, int *rank)
327 {
328         CFILE   *file;
329         uint id, file_version;
330         int type;
331
332         filename = cf_add_ext(filename, NOX(".plr"));
333         
334         if (single){
335                 file = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_SINGLE_PLAYERS);
336         } else {
337                 file = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_MULTI_PLAYERS);
338         }
339
340         if (!file){
341                 return -1;
342         }
343
344         id = cfread_uint(file);
345         if (id != PLR_FILE_ID) {
346                 nprintf(("Warning", "Player file has invalid signature\n"));
347                 cfclose(file);
348                 delete_pilot_file( filename, single );
349                 return -1;
350         }
351
352         // check for compatibility here
353         file_version = cfread_uint(file);
354 /*      if (file_version < INITIAL_RELEASE_FILE_VERSION) { */
355 //      if (file_version != CURRENT_PLAYER_FILE_VERSION) {
356         if (file_version < LOWEST_COMPATIBLE_PLAYER_FILE_VERSION) {
357                 nprintf(("Warning", "WARNING => Player file is outdated and not compatible...\n"));
358                 cfclose(file);
359                 delete_pilot_file( filename, single );
360                 return -1;
361         }
362
363         type = !cfread_ubyte(file);
364         if (rank){
365                 *rank = 0;      
366         }
367                 
368         if (rank){
369                 *rank = cfread_int(file);
370         } else {
371                 cfread_int(file);
372         }
373
374         cfclose(file);
375         if (type != single){
376                 return -1;
377         }
378
379         return 0;
380 }
381
382 void pilot_write_techroom_data(CFILE *file)
383 {
384         int idx;                
385         ubyte out;
386
387         // write the ship and weapon count
388         cfwrite_int(Num_ship_types, file);
389         cfwrite_int(Num_weapon_types, file);
390         cfwrite_int(Intel_info_size, file);
391
392         // write all ship flags out
393         for (idx=0; idx<Num_ship_types; idx++) {
394                 out = (Ship_info[idx].flags & SIF_IN_TECH_DATABASE) ? (ubyte)1 : (ubyte)0;              
395                 cfwrite_ubyte(out, file);                               
396         }
397
398         // write all weapon types out
399         for (idx=0; idx<Num_weapon_types; idx++) {
400                 out = (Weapon_info[idx].wi_flags & WIF_IN_TECH_DATABASE) ? (ubyte)1 : (ubyte)0;
401                 cfwrite_ubyte(out, file);
402         }       
403
404         // write all intel entry flags out
405         for (idx=0; idx<Intel_info_size; idx++) {
406                 cfwrite_ubyte((ubyte)Intel_info[idx].in_tech_db, file);
407         }
408 }
409
410 void pilot_read_techroom_data(CFILE *file)
411 {
412         int idx;
413         int ship_count, weapon_count, intel_count;
414         ubyte in;
415
416         // read in ship and weapon counts
417         ship_count = cfread_int(file);
418         weapon_count = cfread_int(file);
419         SDL_assert(ship_count <= MAX_SHIP_TYPES);
420         SDL_assert(weapon_count <= MAX_WEAPON_TYPES);
421
422         // maintain compatibility w/ demo version
423         if (Player_file_version < 136) {
424                 // skip over all this data, because the lack of tech room in the demo
425                 // left this all hosed in the demo .plr files
426                 // this will all get initialized as if this fella was a new pilot
427                 for (idx=0; idx<ship_count+weapon_count; idx++) {
428                         cfread_ubyte(file);
429                 }
430
431         } else {
432
433                 intel_count = cfread_int(file);
434                 SDL_assert(intel_count <= MAX_INTEL_ENTRIES);
435
436                 // read all ships in
437                 for (idx=0; idx<ship_count; idx++) {
438                         in = cfread_ubyte(file);
439                         if (in) {
440                                 Ship_info[idx].flags |= SIF_IN_TECH_DATABASE | SIF_IN_TECH_DATABASE_M;
441                         } else {
442                                 Ship_info[idx].flags &= ~SIF_IN_TECH_DATABASE;
443                         }
444                 }
445
446                 // read all weapons in
447                 for (idx=0; idx<weapon_count; idx++) {
448                         in = cfread_ubyte(file);
449                         if (in) {
450                                 Weapon_info[idx].wi_flags |= WIF_IN_TECH_DATABASE;
451                         } else {
452                                 Weapon_info[idx].wi_flags &= ~WIF_IN_TECH_DATABASE;
453                         }
454                 }
455
456                 // read all intel entries in
457                 for (idx=0; idx<intel_count; idx++) {
458                         in = cfread_ubyte(file);
459                         if (in) {
460                                 Intel_info[idx].in_tech_db = 1;
461                         } else {
462                                 Intel_info[idx].in_tech_db = 0;
463                         }
464                 }
465         }
466 }
467
468 // write out the player ship selection
469 void pilot_write_loadout(CFILE *file)
470 {
471         int i, j;
472         wss_unit *slot; 
473
474         cfwrite_string_len(Player_loadout.filename, file);
475         cfwrite_string_len(Player_loadout.last_modified, file);
476
477         // write ship and weapon counts
478         cfwrite_int(Num_ship_types, file);
479         cfwrite_int(Num_weapon_types, file);
480
481         // write ship pool
482         for ( i = 0; i < Num_ship_types; i++ ) {
483                 cfwrite_int(Player_loadout.ship_pool[i], file);
484         }
485
486         // write weapons pool
487         for ( i = 0; i < Num_weapon_types; i++ ) {
488                 cfwrite_int(Player_loadout.weapon_pool[i], file);
489         }
490
491         // write ship loadouts
492         for ( i = 0; i < MAX_WSS_SLOTS; i++ ) {
493                 slot = &Player_loadout.unit_data[i];
494                 cfwrite_int(slot->ship_class, file);
495                 for ( j = 0; j < MAX_WL_WEAPONS; j++ ) {
496                         cfwrite_int(slot->wep[j], file);
497                         cfwrite_int(slot->wep_count[j], file);
498                 }
499         }
500 }
501
502 // read in the ship selection for the pilot
503 void pilot_read_loadout(CFILE *file)
504 {
505         int i, j;
506         wss_unit *slot;
507         int ship_count, weapon_count;
508
509         memset(Player_loadout.filename, 0, MAX_FILENAME_LEN);
510         cfread_string_len(Player_loadout.filename, MAX_FILENAME_LEN, file);
511
512         memset(Player_loadout.last_modified, 0, DATE_TIME_LENGTH);      
513         cfread_string_len(Player_loadout.last_modified, DATE_TIME_LENGTH, file);        
514
515         // read in ship and weapon counts
516         ship_count = cfread_int(file);
517         weapon_count = cfread_int(file);
518         SDL_assert(ship_count <= MAX_SHIP_TYPES);
519         SDL_assert(weapon_count <= MAX_WEAPON_TYPES);
520
521         // read in ship pool
522         for ( i = 0; i < ship_count; i++ ) {
523                 Player_loadout.ship_pool[i] = cfread_int(file);
524         }
525
526         // read in weapons pool
527         for ( i = 0; i < weapon_count; i++ ) {
528                 Player_loadout.weapon_pool[i] = cfread_int(file);
529         }
530
531         // read in loadout info
532         for ( i = 0; i < MAX_WSS_SLOTS; i++ ) {
533                 slot = &Player_loadout.unit_data[i];
534                 slot->ship_class = cfread_int(file);
535                 for ( j = 0; j < MAX_WL_WEAPONS; j++ ) {
536                         slot->wep[j] = cfread_int(file);
537                         slot->wep_count[j] = cfread_int(file);
538                 }
539         }
540 }
541
542 // read_pilot_file()
543 //
544 // returns 0 - file read in correctly
545 //        -1 - .PLR file doesn't exist or file not compatible
546 //        >0 - errno from fopen error
547 // if single == 1, look for players in the single players directory, otherwise look in the 
548 // multiplayers directory
549 int read_pilot_file(const char *callsign, int single, player *p)
550 {
551         ubyte num_ctrls;
552         ubyte is_multi = 0;
553         char filename[MAX_FILENAME_LEN], ship_name[NAME_LENGTH];
554         CFILE   *file;
555         uint id;
556         int idx;
557         int i, key_value;
558
559         if (!p) {
560                 SDL_assert((Player_num >= 0) && (Player_num < MAX_PLAYERS));
561                 p = &Players[Player_num];
562         }
563
564         //sprintf(filename, "%-.8s.plr",Players[Player_num].callsign);
565         SDL_assert(strlen(callsign) < MAX_FILENAME_LEN - 4);  // ensure we won't overrun the buffer
566         SDL_strlcpy( filename, callsign, SDL_arraysize(filename) );
567         SDL_strlcat( filename, NOX(".plr"), SDL_arraysize(filename) );
568
569         // if we're a standalone server in multiplayer, just fill in some bogus values since we don't have a pilot file
570         if ((Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_STANDALONE_SERVER)) {
571                 memset(Player, 0, sizeof(player));
572                 SDL_strlcpy(Player->callsign, NOX("Standalone"), SDL_arraysize(Player->callsign));
573                 SDL_strlcpy(Player->short_callsign, NOX("Standalone"), SDL_arraysize(Player->short_callsign));
574                 return 0;
575         }
576         
577         // see comments at the beginning of function
578         if (single) {
579                 file = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_SINGLE_PLAYERS);
580         } else {
581                 file = cfopen(filename, "rb", CFILE_NORMAL, CF_TYPE_MULTI_PLAYERS);
582         }
583
584         if (!file) {
585                 return errno;
586         }
587
588         id = cfread_uint(file);
589         if (id != PLR_FILE_ID) {
590                 Warning(LOCATION, "Player file has invalid signature");
591                 cfclose(file);
592                 return -1;
593         }
594
595         // check for compatibility here
596         Player_file_version = cfread_uint(file);
597         cf_set_version( file, Player_file_version );
598
599         if (Player_file_version < LOWEST_COMPATIBLE_PLAYER_FILE_VERSION) {
600                 nprintf(("Warning", "WARNING => Player file is outdated and not compatible...\n"));
601                 cfclose(file);
602                 delete_pilot_file( filename, single );
603                 return -1;
604         }
605
606         // read in whether he's a multiplayer or not
607         is_multi = cfread_ubyte(file);
608         if (is_multi){
609                 p->flags |= PLAYER_FLAGS_IS_MULTI;
610         } else {
611                 p->flags &= ~PLAYER_FLAGS_IS_MULTI;     // this takes care of unsetting any leftover bits from a (possibly) previously selected pilot
612         }
613
614         // read in rank.
615         cfread_int(file);  
616
617         // get player location
618         p->on_bastion = cfread_ubyte(file);
619
620         // tips?
621         p->tips = cfread_int(file);
622
623         // write out the image file name
624         cfread_string_len(p->image_filename, MAX_FILENAME_LEN - 1, file);
625
626         // write out the image file name
627         p->insignia_texture = -1;
628         cfread_string_len(p->squad_name, NAME_LENGTH, file);
629         cfread_string_len(p->squad_filename, MAX_FILENAME_LEN - 1, file);
630         player_set_squad_bitmap(p, p->squad_filename);
631
632         // deal with campaign stuff.  The way we store the information in the file is to first store the
633         // name of the current campaign that the player is playing.  Next we store the info regarding the campaigns
634         // that the player is currently playing
635         memset(p->current_campaign, 0, MAX_FILENAME_LEN);
636         cfread_string_len(p->current_campaign, MAX_FILENAME_LEN, file);
637
638         // read in the ship name for last ship flown by the player
639         memset(ship_name, 0, NAME_LENGTH);
640         cfread_string_len(ship_name, NAME_LENGTH, file);
641         p->last_ship_flown_si_index = ship_info_lookup(ship_name);
642         if ( p->last_ship_flown_si_index < 0 ) {
643                 nprintf(("Warning","WARNING => Ship class %s not located in Ship_info[] in player file\n",ship_name));
644                 p->last_ship_flown_si_index = ship_info_lookup(default_player_ship);
645         }
646
647         // set all the entries in the control config arrays to -1 (undefined)
648         control_config_clear();
649
650         // ---------------------------------------------
651         // read in the keyboard/joystick mapping
652         // ---------------------------------------------
653         num_ctrls = cfread_ubyte(file);
654         for (i=0; i<num_ctrls; i++) {
655                 key_value = cfread_short(file);
656                 // NOTE: next two lines are only here for transitioning from 255 to -1 as undefined key items
657                 if (key_value == 255)
658                         key_value = -1;
659
660                 Control_config[i].key_id = keycode_translate_from((short)key_value);
661
662                 key_value = cfread_short(file);
663                 // NOTE: next two lines are only here for transitioning from 255 to -1 as undefined key items
664                 if (key_value == 255)
665                         key_value = -1;
666
667                 Control_config[i].joy_id = (short) key_value;
668         }
669         
670         HUD_config.show_flags = cfread_int(file);       
671         HUD_config.show_flags2 = cfread_int(file);
672
673         HUD_config.popup_flags = cfread_int(file);
674         HUD_config.popup_flags2 = cfread_int(file);
675
676         HUD_config.num_msg_window_lines = cfread_ubyte(file);                   
677         HUD_config.rp_flags = cfread_int(file);
678         HUD_config.rp_dist =    cfread_int(file);
679 #ifdef MAKE_FS1
680         if(Player_file_version >= 142){
681                 HUD_config.main_color = cfread_int(file);
682                 HUD_color_alpha = cfread_int(file);
683         }
684         if ( HUD_color_alpha < HUD_COLOR_ALPHA_USER_MIN ) {
685                 HUD_color_alpha = HUD_COLOR_ALPHA_DEFAULT;
686         }
687         hud_config_record_color(HUD_config.main_color);
688 #endif
689
690         // added 2 gauges with version 137
691         if(Player_file_version < 137){
692                 for(idx=0; idx<NUM_HUD_GAUGES-2; idx++){
693                         cfread(&HUD_config.clr[idx], sizeof(color), 1, file);
694                 }
695
696                 // set the 2 new gauges to be radar color
697                 memcpy(&HUD_config.clr[NUM_HUD_GAUGES-2], &HUD_config.clr[HUD_RADAR], sizeof(color));
698                 memcpy(&HUD_config.clr[NUM_HUD_GAUGES-1], &HUD_config.clr[HUD_RADAR], sizeof(color));
699         } else {
700                 for(idx=0; idx<NUM_HUD_GAUGES; idx++){
701                         cfread(&HUD_config.clr[idx], sizeof(color), 1, file);
702                 }
703         }
704
705         // read in the cutscenes which have been viewed
706         Cutscenes_viewable = cfread_int(file);
707
708         Master_sound_volume = cfread_float(file);
709         Master_event_music_volume = cfread_float(file);
710         Master_voice_volume = cfread_float(file);
711
712         audiostream_set_volume_all(Master_voice_volume, ASF_VOICE);
713         audiostream_set_volume_all(Master_event_music_volume, ASF_EVENTMUSIC);
714
715         if ( Master_event_music_volume > 0.0f ) {
716                 Event_music_enabled = 1;
717         } else {
718                 Event_music_enabled = 0;
719         }
720
721         read_detail_settings(file, Player_file_version);
722
723         // restore list of most recently played missions
724         Num_recent_missions = cfread_int( file );
725         SDL_assert(Num_recent_missions <= MAX_RECENT_MISSIONS);
726         for ( i = 0; i < Num_recent_missions; i++ ) {
727                 char *p;
728
729                 cfread_string_len( Recent_missions[i], MAX_FILENAME_LEN, file);
730                 // Remove the extension
731                 p = SDL_strchr(Recent_missions[i], '.');
732                 if (p)
733                         *p = 0;
734         }
735         
736         // use this block of stats from now on
737         read_stats_block(file, Player_file_version, &p->stats); 
738
739    Game_skill_level = cfread_int(file);
740
741         for (i=0; i<NUM_JOY_AXIS_ACTIONS; i++) {
742                 Axis_map_to[i] = cfread_int(file);
743                 Invert_axis[i] = cfread_int(file);
744         }
745
746         // restore some player flags
747         Player[Player_num].save_flags = cfread_int(file);
748
749         // restore the most recent ship selection       
750         pilot_read_loadout(file);       
751
752         // read in multiplayer options
753         read_multiplayer_options(p,file);
754
755         p->readyroom_listing_mode = cfread_int(file);
756         Briefing_voice_enabled = cfread_int(file);
757
758         // restore the default netgame protocol mode
759         int protocol_temp = cfread_int(file);
760         switch(protocol_temp){
761                 // TCP & PXO
762                 case NET_VMT:
763                         Multi_options_g.pxo = 1;
764                         Multi_options_g.protocol = NET_TCP;
765                         break;
766
767                 // plain TCP
768                 case NET_TCP:
769                         Multi_options_g.protocol = NET_TCP;
770                         break;
771
772                 // in case of IPX, which is deprecated
773                 default:
774                         Multi_options_g.protocol = NET_TCP;
775                         break;
776         }       
777
778         // restore wingman status used by red alert missions
779         red_alert_read_wingman_status(file, Player_file_version);
780
781         // read techroom data
782         pilot_read_techroom_data(file);
783
784         // restore auto-advance pref
785         Player->auto_advance = cfread_int(file);
786
787         Use_mouse_to_fly = cfread_int(file);
788         Mouse_sensitivity = cfread_int(file);
789         Joy_sensitivity = cfread_int(file);
790         Dead_zone_size = cfread_int(file);
791
792         if (cfclose(file))
793                 return errno;
794
795         // restore the callsign into the Player structure
796         SDL_strlcpy(p->callsign, callsign, SDL_arraysize(p->callsign));
797
798         // restore the truncated callsign into Player structure
799         pilot_set_short_callsign(p, SHORT_CALLSIGN_PIXEL_W);
800         
801         // when we store the LastPlayer key, we have to mark it as being single or multiplayer, so we know where to look for him
802         // (since we could have a single and a multiplayer pilot with the same callsign)
803         // we'll distinguish them by putting an M and the end of the multiplayer callsign and a P at the end of a single player
804         char cat[35];
805
806         SDL_strlcpy(cat, p->callsign, SDL_arraysize(cat));
807         if (is_multi)
808                 SDL_strlcat(cat, NOX("M"), SDL_arraysize(cat));
809         else
810                 SDL_strlcat(cat, NOX("S"), SDL_arraysize(cat));
811
812         os_config_write_string( NULL, "LastPlayer", cat );
813 /*
814         // if he's not a multiplayer pilot, then load in the campaign file at this point!
815         if (!is_multi) {
816                 if (mission_campaign_load_by_name(campaign_fname)) {
817                         strcpy(campaign_fname, BUILTIN_CAMPAIGN);
818                         if (mission_campaign_load_by_name(campaign_fname))
819                                 SDL_assert(0);
820                 }
821         }
822         //Campaign.current_mission = mission_num;*/
823
824         hud_squadmsg_save_keys();                       // when new pilot read in, must save info for squadmate messaging
825
826         return 0;
827 }
828
829 void read_stats_block(CFILE *file, int Player_file_version, scoring_struct *stats)
830 {
831         int i, total;
832    
833         init_scoring_element(stats);
834         stats->score = cfread_int(file);
835         stats->rank = cfread_int(file);
836         stats->assists = cfread_int(file);
837
838         if (Player_file_version < 139) {
839                 // support for FS2_DEMO pilots that still have FS1 medal info in the .plr files
840                 for (i=0; i < NUM_MEDALS_FS1; i++) {
841                         cfread_int(file);                       // dummy read
842                 }
843         } else {
844                 // read the usual way
845                 for (i=0; i < NUM_MEDALS; i++) {
846                         stats->medals[i] = cfread_int(file);
847                 }
848         }
849
850         total = cfread_int(file);
851         if (total > MAX_SHIP_TYPES){
852                 Warning(LOCATION, "Some ship kill information will be lost due to MAX_SHIP_TYPES decrease");
853         }
854
855         for (i=0; i<total && i<MAX_SHIP_TYPES; i++){
856                 stats->kills[i] = cfread_ushort(file);
857         }
858
859         stats->kill_count = cfread_int(file);
860         stats->kill_count_ok = cfread_int(file);
861         
862         stats->p_shots_fired = cfread_uint(file);
863         stats->s_shots_fired = cfread_uint(file);
864         stats->p_shots_hit = cfread_uint(file);
865         stats->s_shots_hit = cfread_uint(file);
866         
867    stats->p_bonehead_hits = cfread_uint(file);
868         stats->s_bonehead_hits = cfread_uint(file);
869         stats->bonehead_kills = cfread_uint(file);
870 }
871
872 // grab the various detail settings
873 void read_detail_settings(CFILE *file, int pfile_version)
874 {
875         // mass read the Detail struct
876 #ifdef MAKE_FS1
877         // add in extra detail settings
878         if(pfile_version < 141){
879                 cfread( &Detail, sizeof(detail_levels) - sizeof(Detail.engine_glows), 1, file );
880         } else {
881                 cfread( &Detail, sizeof(detail_levels), 1, file );
882         }
883 #else
884         cfread( &Detail, sizeof(detail_levels), 1, file );
885 #endif
886
887         // swap, swap, swap
888         Detail.setting = INTEL_INT(Detail.setting);
889
890         // hack for old pilot files with big-endian data
891         if ( (Detail.setting >= -1) && (Detail.setting <= 5) ) {
892                 // new way - it's little-endian...
893                 Detail.nebula_detail = INTEL_INT(Detail.nebula_detail);
894                 Detail.detail_distance = INTEL_INT(Detail.detail_distance);
895                 Detail.hardware_textures = INTEL_INT(Detail.hardware_textures);
896                 Detail.num_small_debris = INTEL_INT(Detail.num_small_debris);
897                 Detail.num_particles = INTEL_INT(Detail.num_particles);
898                 Detail.num_stars = INTEL_INT(Detail.num_stars);
899                 Detail.shield_effects = INTEL_INT(Detail.shield_effects);
900                 Detail.lighting = INTEL_INT(Detail.lighting);
901                 Detail.targetview_model = INTEL_INT(Detail.targetview_model);
902                 Detail.planets_suns = INTEL_INT(Detail.planets_suns);
903                 Detail.weapon_extras = INTEL_INT(Detail.weapon_extras);
904 #ifdef MAKE_FS1
905                 if (pfile_version >= 141)
906                         Detail.engine_glows = INTEL_INT(Detail.engine_glows);
907 #endif
908         } else {
909                 // it's the old way... un-swap and the new way will be used on save
910                 Detail.setting = INTEL_INT(Detail.setting);
911         }
912 }
913
914 // Will write the pilot file in the most current format
915 //
916 // if single == 1, save into the single players directory, else save into the multiplayers directory
917 int write_pilot_file_core(player *p)
918 {
919         char filename[MAX_FILENAME_LEN + 1];
920    int i, si_index, idx;
921         ubyte is_multi;
922         CFILE *file;
923
924         // never save a pilot file for the standalone server in multiplayer
925         if ((Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_STANDALONE_SERVER)) {
926                 return 0;
927         }
928
929         if (!p) {
930                 SDL_assert((Player_num >= 0) && (Player_num < MAX_PLAYERS));
931                 p = &Players[Player_num];
932         }
933
934         i = strlen(p->callsign);
935         if (i == 0)
936                 return 0;       //      This means there is no player, probably meaning he was deleted and game exited from same screen.
937
938         SDL_assert((i > 0) && (i <= MAX_FILENAME_LEN - 4));  // ensure we won't overrun the buffer
939         SDL_strlcpy( filename, p->callsign, SDL_arraysize(filename));
940         SDL_strlcat( filename, NOX(".plr"), SDL_arraysize(filename) );
941
942         // determine if this pilot is a multiplayer pilot or not
943         if (p->flags & PLAYER_FLAGS_IS_MULTI){
944                 is_multi = 1;
945         } else {
946                 is_multi = 0;
947         }
948
949         // see above
950         if ( !is_multi ){
951                 file = cfopen(filename, "wb", CFILE_NORMAL, CF_TYPE_SINGLE_PLAYERS);
952         } else {
953                 file = cfopen(filename, "wb", CFILE_NORMAL, CF_TYPE_MULTI_PLAYERS);
954         }
955
956         if (!file){
957                 return errno;
958         }
959
960         // Write out player's info
961         cfwrite_uint(PLR_FILE_ID, file);
962         cfwrite_uint(CURRENT_PLAYER_FILE_VERSION, file);
963
964         cfwrite_ubyte(is_multi, file);
965         cfwrite_int(p->stats.rank, file);
966         cfwrite_ubyte((ubyte) p->on_bastion, file);
967
968         cfwrite_int(p->tips, file);
969
970         // write out the image file name
971         cfwrite_string_len(p->image_filename, file);
972
973         // write out the image file name
974         cfwrite_string_len(p->squad_name, file);
975         cfwrite_string_len(p->squad_filename, file);
976
977         // write out the name of the player's active campaign.
978         cfwrite_string_len(p->current_campaign, file);  
979
980         // write the ship name for last ship flown by the player
981         si_index = p->last_ship_flown_si_index;
982         if((si_index < 0) || (si_index >= Num_ship_types)){
983                 si_index = 0;
984         }
985
986         cfwrite_string_len(Ship_info[si_index].name, file);
987
988         // ---------------------------------------------
989         // write the keyboard/joystick configuration
990         // ---------------------------------------------
991         short key_id = 0;
992         cfwrite_ubyte( CCFG_MAX, file );
993         for (i=0; i<CCFG_MAX; i++) {
994                 key_id = keycode_translate_to(Control_config[i].key_id);
995                 cfwrite_short( key_id, file );
996                 cfwrite_short( Control_config[i].joy_id, file );
997         }               
998
999         // if this hud is an observer, the player ended the last mission as an observer, so we should
1000         // restore his "real" ship HUD.
1001         HUD_CONFIG_TYPE hc_temp;
1002         hc_temp.show_flags = 0;
1003         int stored_observer = 0;
1004         if ( HUD_config.is_observer ){
1005                 // if we're in mission, copy the HUD we're currently using
1006                 if(Game_mode & GM_IN_MISSION){                  
1007                         memcpy(&hc_temp,&HUD_config,sizeof(HUD_CONFIG_TYPE));
1008                         stored_observer = 1;
1009                 }
1010
1011                 hud_config_restore();                           
1012         }
1013
1014         // write the hud configuration
1015         cfwrite_int(HUD_config.show_flags, file);       
1016         cfwrite_int(HUD_config.show_flags2, file);      
1017         cfwrite_int(HUD_config.popup_flags, file);      
1018         cfwrite_int(HUD_config.popup_flags2, file);     
1019         cfwrite_ubyte( (ubyte) HUD_config.num_msg_window_lines, file );
1020         cfwrite_int( HUD_config.rp_flags, file );
1021         cfwrite_int( HUD_config.rp_dist, file );
1022 #ifdef MAKE_FS1
1023         cfwrite_int( HUD_config.main_color, file );
1024         cfwrite_int( HUD_color_alpha, file );
1025 #endif
1026         for(idx=0; idx<NUM_HUD_GAUGES; idx++){
1027                 cfwrite(&HUD_config.clr[idx], sizeof(color), 1, file);
1028         }
1029
1030         // restore the HUD we backed up
1031         if( (Game_mode & GM_IN_MISSION) && stored_observer ){           
1032                 memcpy(&HUD_config,&hc_temp,sizeof(HUD_CONFIG_TYPE));
1033         }
1034
1035         // write the cutscenes which have been viewed
1036         cfwrite_int(Cutscenes_viewable, file);
1037
1038         // store the digital sound fx volume, and music volume
1039         cfwrite_float(Master_sound_volume, file);
1040         cfwrite_float(Master_event_music_volume, file);
1041         cfwrite_float(Master_voice_volume, file);
1042
1043
1044         //cfwrite( &Detail, sizeof(detail_levels), 1, file );
1045         write_detail_settings(file);
1046
1047         // store list of most recently played missions
1048         cfwrite_int(Num_recent_missions, file);
1049         for (i=0; i<Num_recent_missions; i++) {
1050                 cfwrite_string_len(Recent_missions[i], file);
1051         }
1052
1053         // write the player stats
1054         write_stats_block(file, &p->stats);     
1055    cfwrite_int(Game_skill_level, file);
1056
1057         for (i=0; i<NUM_JOY_AXIS_ACTIONS; i++) {
1058                 cfwrite_int(Axis_map_to[i], file);
1059                 cfwrite_int(Invert_axis[i], file);
1060         }
1061
1062         // store some player flags
1063    cfwrite_int(Player->save_flags, file);
1064
1065         // store ship selection for most recent mission
1066         pilot_write_loadout(file);
1067
1068         // read in multiplayer options  
1069         write_multiplayer_options(p, file);
1070
1071         cfwrite_int(p->readyroom_listing_mode, file);
1072    cfwrite_int(Briefing_voice_enabled, file);
1073
1074         // store the default netgame protocol mode for this pilot
1075         SDL_assert(Multi_options_g.protocol == NET_TCP);
1076         if (Multi_options_g.pxo == 1) {
1077                 cfwrite_int(NET_VMT, file);
1078         } else {
1079                 cfwrite_int(NET_TCP, file);
1080         }
1081
1082         red_alert_write_wingman_status(file);
1083         pilot_write_techroom_data(file);
1084
1085         // store auto-advance pref
1086    cfwrite_int(Player->auto_advance, file);
1087
1088         cfwrite_int(Use_mouse_to_fly, file);
1089         cfwrite_int(Mouse_sensitivity, file);
1090         cfwrite_int(Joy_sensitivity, file);
1091         cfwrite_int(Dead_zone_size, file);
1092
1093         if (!cfclose(file))
1094                 return 0;
1095
1096         return errno;
1097 }
1098
1099 int write_pilot_file(player *the_player)
1100 {
1101         int pilot_write_rval;
1102         do {
1103                 // write_pilot_file_core returns 0 if ok, non-zero for error
1104                 pilot_write_rval = write_pilot_file_core(the_player);
1105
1106                 // check with user if write not successful
1107                 if (pilot_write_rval) {
1108                         int popup_rval = popup(PF_TITLE_RED | PF_TITLE_BIG, 3, XSTR( "&Retry", 41), XSTR( "&Ignore", 42), XSTR( "&Quit Game", 43),
1109                                 XSTR( "Warning\nFailed to save pilot file.  You may be out of disk space.  If so, you should press Alt-Tab, free up some disk space, then come back and choose retry.\n", 44) );
1110
1111                         // quit game popup return value (2)
1112                         if (popup_rval == 2) {
1113                                 exit(1);
1114                         }
1115
1116                         // _ignore_ popup return value (1) - don't save the file
1117                         if (popup_rval) {
1118                                 return pilot_write_rval;
1119                         }
1120
1121                         // retry popup return value (0) - try again 
1122                 }
1123
1124         } while (pilot_write_rval);
1125
1126         // write successful
1127         return 0;
1128 }
1129
1130 void write_stats_block(CFILE *file,scoring_struct *stats)
1131 {
1132         int i;
1133         int total;
1134
1135         cfwrite_int(stats->score, file);
1136         cfwrite_int(stats->rank, file);
1137         cfwrite_int(stats->assists, file);
1138         for (i=0; i<NUM_MEDALS; i++){
1139                 cfwrite_int(stats->medals[i], file);
1140         }
1141
1142         total = MAX_SHIP_TYPES;
1143         while (total && !stats->kills[total - 1]){  // find last used element
1144                 total--;
1145         }
1146
1147         cfwrite_int(total, file);
1148         for (i=0; i<total; i++){
1149                 cfwrite_ushort(stats->kills[i], file);
1150         }
1151
1152         cfwrite_int(stats->kill_count,file);
1153         cfwrite_int(stats->kill_count_ok,file);
1154
1155    cfwrite_uint(stats->p_shots_fired,file);
1156         cfwrite_uint(stats->s_shots_fired,file);
1157         cfwrite_uint(stats->p_shots_hit,file);
1158         cfwrite_uint(stats->s_shots_hit,file);
1159         cfwrite_uint(stats->p_bonehead_hits,file);
1160         cfwrite_uint(stats->s_bonehead_hits,file);
1161         cfwrite_uint(stats->bonehead_kills,file);
1162 }
1163
1164 // write the various detail settings
1165 void write_detail_settings(CFILE *file)
1166 {
1167         // we still need sane values in the Detail struct so create
1168         // a temporary one to value swap and write to file
1169         detail_levels Detail_tmp;
1170         memset(&Detail_tmp, 0, sizeof(detail_levels));
1171         memcpy(&Detail_tmp, &Detail, sizeof(detail_levels));
1172
1173         // swap, swap, swap - on big-endian this will convert back to little-endian
1174         Detail_tmp.setting = INTEL_INT(Detail_tmp.setting);
1175         Detail_tmp.nebula_detail = INTEL_INT(Detail_tmp.nebula_detail);
1176         Detail_tmp.detail_distance = INTEL_INT(Detail_tmp.detail_distance);
1177         Detail_tmp.hardware_textures = INTEL_INT(Detail_tmp.hardware_textures);
1178         Detail_tmp.num_small_debris = INTEL_INT(Detail_tmp.num_small_debris);
1179         Detail_tmp.num_particles = INTEL_INT(Detail_tmp.num_particles);
1180         Detail_tmp.num_stars = INTEL_INT(Detail_tmp.num_stars);
1181         Detail_tmp.shield_effects = INTEL_INT(Detail_tmp.shield_effects);
1182         Detail_tmp.lighting = INTEL_INT(Detail_tmp.lighting);
1183         Detail_tmp.targetview_model = INTEL_INT(Detail_tmp.targetview_model);
1184         Detail_tmp.planets_suns = INTEL_INT(Detail_tmp.planets_suns);
1185         Detail_tmp.weapon_extras = INTEL_INT(Detail_tmp.weapon_extras);
1186
1187 #ifdef MAKE_FS1
1188         Detail.engine_glows = INTEL_INT(Detail.engine_glows);
1189 #endif // MAKE_FS1
1190
1191         cfwrite( &Detail_tmp, sizeof(detail_levels), 1, file );
1192 }
1193
1194 // write multiplayer information
1195 void write_multiplayer_options(player *p,CFILE *file)
1196 {       
1197         // write the netgame options
1198         cfwrite_ubyte(p->m_server_options.squad_set,file);
1199         cfwrite_ubyte(p->m_server_options.endgame_set,file);    
1200         cfwrite_int(p->m_server_options.flags,file);
1201         cfwrite_uint(p->m_server_options.respawn,file);
1202         cfwrite_ubyte(p->m_server_options.max_observers,file);
1203         cfwrite_ubyte(p->m_server_options.skill_level,file);
1204         cfwrite_ubyte(p->m_server_options.voice_qos,file);
1205         cfwrite_int(p->m_server_options.voice_token_wait,file);
1206         cfwrite_int(p->m_server_options.voice_record_time,file);
1207         cfwrite(&p->m_server_options.mission_time_limit,sizeof(fix),1,file);
1208         cfwrite_int(p->m_server_options.kill_limit,file);
1209
1210         // write the local options
1211         cfwrite_int(p->m_local_options.flags,file);
1212         cfwrite_int(p->m_local_options.obj_update_level,file);
1213 }
1214
1215 // read multiplayer options
1216 void read_multiplayer_options(player *p,CFILE *file)
1217 {
1218         // read the netgame options
1219         p->m_server_options.squad_set = cfread_ubyte(file);
1220         p->m_server_options.endgame_set = cfread_ubyte(file);   
1221         p->m_server_options.flags = cfread_int(file);
1222         p->m_server_options.respawn = cfread_uint(file);
1223         p->m_server_options.max_observers = cfread_ubyte(file);
1224         p->m_server_options.skill_level = cfread_ubyte(file);
1225         p->m_server_options.voice_qos = cfread_ubyte(file);
1226         p->m_server_options.voice_token_wait = cfread_int(file);
1227         p->m_server_options.voice_record_time = cfread_int(file);
1228         cfread(&p->m_server_options.mission_time_limit,sizeof(fix),1,file);
1229         p->m_server_options.kill_limit = cfread_int(file);
1230
1231         // read the local options
1232         p->m_local_options.flags = cfread_int(file);
1233         p->m_local_options.obj_update_level = cfread_int(file);
1234 }
1235
1236 // run thorough an open file (at the beginning) and see if this pilot is a multiplayer pilot
1237 int is_pilot_multi(CFILE *fp)
1238 {
1239         uint id,file_version;
1240         ubyte is_multi;
1241         
1242         id = cfread_uint(fp);
1243         if (id != PLR_FILE_ID) {
1244                 Warning(LOCATION, "Player file has invalid signature");
1245                 cfclose(fp);
1246                 return -1;
1247         }
1248
1249         // check for compatibility here
1250         file_version = cfread_uint(fp);
1251         if (file_version < LOWEST_COMPATIBLE_PLAYER_FILE_VERSION) {
1252                 nprintf(("Warning", "WARNING => Player file is outdated and not compatible...\n"));
1253                 cfclose(fp);
1254                 return -1;
1255         }
1256
1257         // read in whether he's a multiplayer or not
1258         is_multi = cfread_ubyte(fp);
1259         if (is_multi)
1260                 return 1;
1261
1262         return 0;
1263 }
1264
1265 int is_pilot_multi(player *p)
1266 {
1267         return (p->flags & PLAYER_FLAGS_IS_MULTI) ? 1 : 0;
1268 }
1269
1270 // this works on barracks and player_select interface screens
1271 void init_new_pilot(player *p, int reset)
1272 {
1273         int cur_speed;
1274
1275         if (reset) {
1276                 hud_set_default_hud_config(p);          // use a default hud config
1277
1278                 // in the demo, load up the hardcoded hcf file
1279 #ifdef FS2_DEMO
1280                 hud_config_color_load("hud_1.hcf");
1281 #else
1282                 hud_config_color_load("hud_3.hcf");
1283 #endif
1284
1285                 control_config_reset_defaults();                // get a default keyboard config
1286                 player_set_pilot_defaults(p);                   // set up any player struct defaults
1287
1288                 cur_speed = os_config_read_uint(NULL, NOX("ComputerSpeed"), 2 );
1289                 if ( cur_speed < 0 )    {
1290                         cur_speed = 0;
1291                 } else if ( cur_speed >= NUM_DEFAULT_DETAIL_LEVELS )    {
1292                         cur_speed = NUM_DEFAULT_DETAIL_LEVELS-1;
1293                 }       
1294                 // always set to high
1295                 // DKA: 8/4/99 USE speed from registry
1296                 // cur_speed = NUM_DEFAULT_DETAIL_LEVELS-2;
1297
1298 #if NUM_DEFAULT_DETAIL_LEVELS != 4
1299 #error Code in ManagePilot assumes NUM_DEFAULT_DETAIL_LEVELS = 4
1300 #endif
1301
1302                 detail_level_set(cur_speed);
1303
1304                 Game_skill_level = game_get_default_skill_level();
1305
1306                 mprintf(( "Setting detail level to %d because of new pilot\n", cur_speed ));
1307                 Use_mouse_to_fly = 0;
1308                 Mouse_sensitivity = 4;
1309                 Joy_sensitivity = 9;
1310                 Dead_zone_size = 10;
1311         }
1312
1313         // unassigned squadron
1314         SDL_strlcpy(p->squad_name, XSTR("Unassigned", 1255), SDL_arraysize(p->squad_name));
1315         SDL_strlcpy(p->squad_filename, "", SDL_arraysize(p->squad_filename));
1316
1317         // set him to be a single player pilot by default (the actual creation routines will change this if necessary)
1318         p->flags &= ~PLAYER_FLAGS_IS_MULTI;
1319
1320         // effectively sets the length return by strlen() to 0  
1321         Campaign.filename[0] = 0;
1322         p->on_bastion = 0;
1323
1324         // pick a random pilot image for this guy
1325         if (reset){
1326                 pilot_set_random_pic(p);
1327                 p->insignia_texture = -1;
1328                 pilot_set_random_squad_pic(p);
1329         }
1330
1331         init_scoring_element(&p->stats);        
1332         
1333         p->stats.score = 0;
1334         p->stats.rank = RANK_ENSIGN;    
1335
1336         p->tips = 1;
1337
1338         Multi_options_g.protocol = NET_TCP;     
1339
1340         // initialize default multiplayer options
1341         multi_options_set_netgame_defaults(&p->m_server_options);
1342         multi_options_set_local_defaults(&p->m_local_options);
1343
1344         Player_loadout.filename[0] = 0;
1345
1346         // reset the cutscenes which can be viewed
1347         if ( reset ){
1348                 Cutscenes_viewable = INTRO_CUTSCENE_FLAG;
1349         }
1350 }
1351
1352 void pilot_set_short_callsign(player *p, int max_width)
1353 {
1354         SDL_strlcpy(p->short_callsign, p->callsign, SDL_arraysize(p->short_callsign));
1355         gr_set_font(FONT1);
1356         gr_force_fit_string(p->short_callsign, CALLSIGN_LEN - 1, max_width);
1357         gr_get_string_size( &(p->short_callsign_width), NULL, p->short_callsign );
1358 }
1359
1360 // pick a random image for the passed player
1361 void pilot_set_random_pic(player *p)
1362 {
1363         // if there are no available pilot pics, set the image filename to null
1364         if (Num_pilot_images <= 0) {
1365                 SDL_strlcpy(p->image_filename, "", SDL_arraysize(p->image_filename));
1366         } else {
1367                 // pick a random name from the list
1368                 int random_index = rand() % Num_pilot_images;
1369                 SDL_assert((random_index >= 0) && (random_index < Num_pilot_images));
1370                 SDL_strlcpy(p->image_filename, Pilot_images_arr[random_index], SDL_arraysize(p->image_filename));
1371         }       
1372 }
1373
1374 // pick a random image for the passed player
1375 void pilot_set_random_squad_pic(player *p)
1376 {       
1377         // if there are no available pilot pics, set the image filename to null
1378         if (Num_pilot_squad_images <= 0) {
1379                 player_set_squad_bitmap(p, "");
1380                 // strcpy(p->squad_filename, "");               
1381         } else {
1382                 // pick a random name from the list
1383                 int random_index = rand() % Num_pilot_squad_images;             
1384                 SDL_assert((random_index >= 0) && (random_index < Num_pilot_squad_images));
1385                 player_set_squad_bitmap(p, Pilot_squad_images_arr[random_index]); 
1386                 // strcpy(p->squad_filename, Pilot_squad_images_arr[random_index]);
1387         }       
1388 }
1389
1390 // format a pilot's callsign into a "personal" form - ie, adding a 's or just an ' as appropriate
1391 void pilot_format_callsign_personal(const char *in_callsign, char *out_callsign, const int out_size)
1392 {
1393         // don't do anything if we've got invalid strings
1394         if((in_callsign == NULL) || (out_callsign == NULL)){
1395                 return;
1396         }
1397
1398         // copy the original string
1399         SDL_strlcpy(out_callsign, in_callsign, out_size);
1400
1401         // tack on the appropriate postfix
1402         if(in_callsign[strlen(in_callsign) - 1] == 's'){                
1403                 SDL_strlcat(out_callsign,XSTR( "\'", 45), out_size);
1404         } else {
1405                 SDL_strlcat(out_callsign,XSTR( "\'s", 46), out_size);
1406         }
1407 }
1408
1409 // throw up a popup asking the user to verify the overwrite of an existing pilot name
1410 // 1 == ok to overwrite, 0 == not ok
1411 int pilot_verify_overwrite()
1412 {
1413         return popup(PF_USE_AFFIRMATIVE_ICON | PF_USE_NEGATIVE_ICON | PF_TITLE_RED | PF_TITLE_BIG, 2, XSTR( "&No", 47), XSTR( "&Yes", 48), XSTR( "Warning\nA duplicate pilot exists\nOverwrite?", 49));
1414 }
1415
1416 extern int Skip_packfile_search;  // located in CFileList.cpp
1417
1418
1419 // load up the list of pilot image filenames (do this at game startup as well as barracks startup)
1420 void pilot_load_pic_list()
1421 {
1422         Num_pilot_images = 0;
1423         
1424         // load pilot images from the player images directory
1425         Num_pilot_images = cf_get_file_list_preallocated(MAX_PILOT_IMAGES, Pilot_images_arr, Pilot_image_names, CF_TYPE_PLAYER_IMAGES_MAIN, NOX("*.pcx"));
1426
1427         // sort all filenames
1428         cf_sort_filenames(Num_pilot_images, Pilot_image_names, CF_SORT_NAME);
1429 }
1430
1431 // load up the list of pilot squad filenames
1432 void pilot_load_squad_pic_list()
1433 {
1434         Num_pilot_squad_images = 0;
1435         
1436         // load pilot images from the player images directory
1437         Num_pilot_squad_images = cf_get_file_list_preallocated(MAX_PILOT_IMAGES, Pilot_squad_images_arr, Pilot_squad_image_names, CF_TYPE_SQUAD_IMAGES_MAIN, NOX("*.pcx"));
1438
1439         // sort all filenames
1440         cf_sort_filenames(Num_pilot_squad_images, Pilot_squad_image_names, CF_SORT_NAME);
1441 }
1442
1443 // will attempt to load an insignia bitmap and set it as active for the player
1444 void player_set_squad_bitmap(player *p, const char *fname)
1445 {
1446         // sanity check
1447         if(p == NULL){
1448                 return;
1449         }
1450
1451         // if he has another bitmap already - unload it
1452         if(p->insignia_texture >= 0){
1453                 bm_unload(p->insignia_texture);
1454         }
1455
1456         p->insignia_texture = -1;
1457
1458         // try and set the new one
1459         if (fname != p->squad_filename) {
1460                 SDL_strlcpy(p->squad_filename, fname, SDL_arraysize(p->squad_filename));
1461         }
1462
1463         if(strlen(p->squad_filename) > 0){
1464                 p->insignia_texture = bm_load_duplicate(fname);
1465                 
1466                 // lock is as a transparent texture
1467                 if(p->insignia_texture != -1){
1468                         bm_lock(p->insignia_texture, 16, BMP_TEX_XPARENT);
1469                         bm_unlock(p->insignia_texture);
1470                 }
1471         }
1472
1473         /*
1474         flen = strlen(filename);
1475         elen = strlen(ext);
1476         SDL_assert(flen < MAX_PATH_LEN);
1477         strcpy(path, filename);
1478         if ((flen < 4) || SDL_strcasecmp(path + flen - elen, ext)) {
1479                 SDL_assert(flen + elen < MAX_PATH_LEN);
1480                 strcat(path, ext);
1481         }
1482         */
1483 }
1484
1485 // set squadron
1486 void player_set_squad(player *p, const char *squad_name)
1487 {
1488         // sanity check
1489         if(p == NULL){
1490                 return;
1491         }
1492
1493         SDL_strlcpy(p->squad_name, squad_name, SDL_arraysize(p->squad_name));
1494 }
1495
1496 DCF(pilot,"Changes pilot stats. (Like reset campaign)" )
1497 {
1498         if (Dc_command) {
1499                 dc_get_arg(ARG_STRING);
1500                 if (!strcmp(Dc_arg, NOX("reset"))) {
1501                         if (strlen(Campaign.filename)) {
1502                                 mission_campaign_savefile_delete(Campaign.filename);
1503                                 mission_campaign_load(Campaign.filename);
1504                         }
1505
1506                 } else {
1507                         Dc_help = 1;  // print usage, not stats
1508                 }
1509         }
1510
1511         if (Dc_help) {
1512                 dc_printf( "Usage: pilot keyword\nWhere keyword can be in the following forms:\n" );
1513                 dc_printf( "pilot reset                 Resets campaign stats.\n" );
1514                 Dc_status = 0;  // don't print status if help is printed.  Too messy.
1515         }
1516
1517         if (Dc_status) {
1518                 // no stats
1519         }
1520 }
1521
1522 struct fs_keycode_t {
1523         short fs_code;
1524         SDL_Keycode sdl_code;
1525 };
1526
1527 static const fs_keycode_t keycode_lookup[] = {
1528         { /* KEY_0 */           0x0B,   SDLK_0                  },
1529         { /* KEY_1 */           0x02,   SDLK_1                  },
1530         { /* KEY_2 */           0x03,   SDLK_2                  },
1531         { /* KEY_3 */           0x04,   SDLK_3                  },
1532         { /* KEY_4 */           0x05,   SDLK_4                  },
1533         { /* KEY_5 */           0x06,   SDLK_5                  },
1534         { /* KEY_6 */           0x07,   SDLK_6                  },
1535         { /* KEY_7 */           0x08,   SDLK_7                  },
1536         { /* KEY_8 */           0x09,   SDLK_8                  },
1537         { /* KEY_9 */           0x0A,   SDLK_9                  },
1538         { /* KEY_A */           0x1E,   SDLK_a                  },
1539         { /* KEY_B */           0x30,   SDLK_b                  },
1540         { /* KEY_C */           0x2E,   SDLK_c                  },
1541         { /* KEY_D */           0x20,   SDLK_d                  },
1542         { /* KEY_E */           0x12,   SDLK_e                  },
1543         { /* KEY_F */           0x21,   SDLK_f                  },
1544         { /* KEY_G */           0x22,   SDLK_g                  },
1545         { /* KEY_H */           0x23,   SDLK_h                  },
1546         { /* KEY_I */           0x17,   SDLK_i                  },
1547         { /* KEY_J */           0x24,   SDLK_j                  },
1548         { /* KEY_K */           0x25,   SDLK_k                  },
1549         { /* KEY_L */           0x26,   SDLK_l                  },
1550         { /* KEY_M */           0x32,   SDLK_m                  },
1551         { /* KEY_N */           0x31,   SDLK_n                  },
1552         { /* KEY_O */           0x18,   SDLK_o                  },
1553         { /* KEY_P */           0x19,   SDLK_p                  },
1554         { /* KEY_Q */           0x10,   SDLK_q                  },
1555         { /* KEY_R */           0x13,   SDLK_r                  },
1556         { /* KEY_S */           0x1F,   SDLK_s                  },
1557         { /* KEY_T */           0x14,   SDLK_t                  },
1558         { /* KEY_U */           0x16,   SDLK_u                  },
1559         { /* KEY_V */           0x2F,   SDLK_v                  },
1560         { /* KEY_W */           0x11,   SDLK_w                  },
1561         { /* KEY_X */           0x2D,   SDLK_x                  },
1562         { /* KEY_Y */           0x15,   SDLK_y                  },
1563         { /* KEY_Z */           0x2C,   SDLK_z                  },
1564         { /* KEY_MINUS */       0x0C,   SDLK_MINUS              },
1565         { /* KEY_EQUAL */       0x0D,   SDLK_EQUALS             },
1566         { /* KEY_DIVIDE */      0x35,   SDLK_SLASH              },
1567         { /* KEY_SLASH */       0x2B,   SDLK_BACKSLASH  },
1568         { /* KEY_SLASH_UK */    0x56,   SDLK_BACKSLASH  },
1569         { /* KEY_COMMA */       0x33,   SDLK_COMMA              },
1570         { /* KEY_PERIOD */      0x34,   SDLK_PERIOD             },
1571         { /* KEY_SEMICOL */     0x27,   SDLK_SEMICOLON  },
1572         { /* KEY_LBRACKET */    0x1A,   SDLK_LEFTBRACKET        },
1573         { /* KEY_RBRACKET */    0x1B,   SDLK_RIGHTBRACKET       },
1574         { /* KEY_RAPOSTRO */    0x28,   SDLK_QUOTE              },
1575         { /* KEY_LAPOSTRO */    0x29,   SDLK_BACKQUOTE  },
1576         { /* KEY_ESC */         0x01,   SDLK_ESCAPE             },
1577         { /* KEY_ENTER */       0x1C,   SDLK_RETURN             },
1578         { /* KEY_BACKSP */      0x0E,   SDLK_BACKSPACE  },
1579         { /* KEY_TAB */         0x0F,   SDLK_TAB                },
1580         { /* KEY_SPACEBAR */    0x39,   SDLK_SPACE              },
1581         { /* KEY_NUMLOCK */     0x61,   SDLK_NUMLOCKCLEAR       },
1582         { /* KEY_SCROLLOCK */   0x46,   SDLK_SCROLLLOCK },
1583         { /* KEY_CAPSLOCK */    0x3A,   SDLK_CAPSLOCK   },
1584         { /* KEY_LSHIFT */      0x2A,   SDLK_LSHIFT             },
1585         { /* KEY_RSHIFT */      0x36,   SDLK_RSHIFT             },
1586         { /* KEY_LALT */        0x38,   SDLK_LALT               },
1587         { /* KEY_RALT */        0xB8,   SDLK_RALT               },
1588         { /* KEY_LCTRL */       0x1D,   SDLK_LCTRL              },
1589         { /* KEY_RCTRL */       0x9D,   SDLK_RCTRL              },
1590         { /* KEY_F1 */          0x3B,   SDLK_F1                 },
1591         { /* KEY_F2 */          0x3C,   SDLK_F2                 },
1592         { /* KEY_F3 */          0x3D,   SDLK_F3                 },
1593         { /* KEY_F4 */          0x3E,   SDLK_F4                 },
1594         { /* KEY_F5 */          0x3F,   SDLK_F5                 },
1595         { /* KEY_F6 */          0x40,   SDLK_F6                 },
1596         { /* KEY_F7 */          0x41,   SDLK_F7                 },
1597         { /* KEY_F8 */          0x42,   SDLK_F8                 },
1598         { /* KEY_F9 */          0x43,   SDLK_F9                 },
1599         { /* KEY_F10 */         0x44,   SDLK_F10                },
1600         { /* KEY_F11 */         0x57,   SDLK_F11                },
1601         { /* KEY_F12 */         0x58,   SDLK_F12                },
1602         { /* KEY_PAD0 */        0x52,   SDLK_KP_0               },
1603         { /* KEY_PAD1 */        0x4F,   SDLK_KP_1               },
1604         { /* KEY_PAD2 */        0x50,   SDLK_KP_2               },
1605         { /* KEY_PAD3 */        0x51,   SDLK_KP_3               },
1606         { /* KEY_PAD4 */        0x4B,   SDLK_KP_4               },
1607         { /* KEY_PAD5 */        0x4C,   SDLK_KP_5               },
1608         { /* KEY_PAD6 */        0x4D,   SDLK_KP_6               },
1609         { /* KEY_PAD7 */        0x47,   SDLK_KP_7               },
1610         { /* KEY_PAD8 */        0x48,   SDLK_KP_8               },
1611         { /* KEY_PAD9 */        0x49,   SDLK_KP_9               },
1612         { /* KEY_PADMINUS */    0x4A,   SDLK_KP_MINUS   },
1613         { /* KEY_PADPLUS */     0x4E,   SDLK_KP_PLUS    },
1614         { /* KEY_PADPERIOD */   0x53,   SDLK_KP_PERIOD  },
1615         { /* KEY_PADDIVIDE */   0xB5,   SDLK_KP_DIVIDE  },
1616         { /* KEY_PADMULTIPLY */ 0x37,   SDLK_KP_MULTIPLY        },
1617         { /* KEY_PADENTER */    0x9C,   SDLK_KP_ENTER   },
1618         { /* KEY_INSERT */      0xD2,   SDLK_INSERT             },
1619         { /* KEY_HOME */        0xC7,   SDLK_HOME               },
1620         { /* KEY_PAGEUP */      0xC9,   SDLK_PAGEUP             },
1621         { /* KEY_DELETE */      0xd3,   SDLK_DELETE             },
1622         { /* KEY_END */         0xCF,   SDLK_END                },
1623         { /* KEY_PAGEDOWN */    0xD1,   SDLK_PAGEDOWN   },
1624         { /* KEY_UP */          0xC8,   SDLK_UP                 },
1625         { /* KEY_DOWN */        0xD0,   SDLK_DOWN               },
1626         { /* KEY_LEFT */        0xCB,   SDLK_LEFT               },
1627         { /* KEY_RIGHT */       0xCD,   SDLK_RIGHT              },
1628         { /* KEY_PRINT_SCRN */  0xB7,   SDLK_PRINTSCREEN        },
1629         { /* KEY_PAUSE */       0x45,   SDLK_PAUSE              },
1630         { /* KEY_BREAK */       0xc6,   SDLK_PAUSE              }
1631 };
1632
1633 static SDL_Keycode keycode_translate_from(short keycode)
1634 {
1635         const int tbl_size = sizeof(keycode_lookup) / sizeof(fs_keycode_t);
1636
1637         if (keycode < 0) {
1638                 return -1;
1639         }
1640
1641         int mods = keycode & 0xf900;
1642         keycode &= KEY_MASK;
1643
1644         for (int i = 0; i < tbl_size; i++) {
1645                 if (keycode_lookup[i].fs_code == keycode) {
1646                         return (SDL_Keycode)(keycode_lookup[i].sdl_code | mods);
1647                 }
1648         }
1649
1650         return -1;
1651 }
1652
1653 static short keycode_translate_to(SDL_Keycode keycode)
1654 {
1655         const int tbl_size = sizeof(keycode_lookup) / sizeof(fs_keycode_t);
1656
1657         if (keycode < 0) {
1658                 return -1;
1659         }
1660
1661         int mods = keycode & 0xf900;
1662         keycode &= KEY_MASK;
1663
1664         for (int i = 0; i < tbl_size; i++) {
1665                 if (keycode_lookup[i].sdl_code == keycode) {
1666                         return (short)(keycode_lookup[i].fs_code | mods);
1667                 }
1668         }
1669
1670         return -1;
1671 }