]> icculus.org git repositories - taylor/freespace2.git/blob - src/network/multiutil.cpp
cleanup of multi related cfg options
[taylor/freespace2.git] / src / network / multiutil.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/Network/MultiUtil.cpp $
11  * $Revision$
12  * $Date$
13  * $Author$
14  *
15  * C file that contains misc. functions to support multiplayer
16  *
17  * $Log$
18  * Revision 1.10  2006/04/26 19:48:58  taylor
19  * various big-endian fixes, mainly networking support related
20  *
21  * Revision 1.9  2003/05/25 02:30:43  taylor
22  * Freespace 1 support
23  *
24  * Revision 1.8  2002/06/17 06:33:10  relnev
25  * ryan's struct patch for gcc 2.95
26  *
27  * Revision 1.7  2002/06/09 04:41:24  relnev
28  * added copyright header
29  *
30  * Revision 1.6  2002/06/05 08:05:29  relnev
31  * stub/warning removal.
32  *
33  * reworked the sound code.
34  *
35  * Revision 1.5  2002/06/02 04:26:34  relnev
36  * warning cleanup
37  *
38  * Revision 1.4  2002/05/27 00:40:47  theoddone33
39  * Fix net_addr vs net_addr_t
40  *
41  * Revision 1.3  2002/05/26 20:49:54  theoddone33
42  * More progress
43  *
44  * Revision 1.2  2002/05/07 03:16:47  theoddone33
45  * The Great Newline Fix
46  *
47  * Revision 1.1.1.1  2002/05/03 03:28:10  root
48  * Initial import.
49  *
50  * 
51  * 47    9/15/99 1:45a Dave
52  * Don't init joystick on standalone. Fixed campaign mode on standalone.
53  * Fixed no-score-report problem in TvT
54  * 
55  * 46    9/09/99 8:53p Dave
56  * Fixed multiplayer degenerate orientation case problem. Make sure warp
57  * effect never goes lower than LOD 1. 
58  * 
59  * 45    8/24/99 1:50a Dave
60  * Fixed client-side afterburner stuttering. Added checkbox for no version
61  * checking on PXO join. Made button info passing more friendly between
62  * client and server.
63  * 
64  * 44    8/23/99 10:30a Dave
65  * Make sure a kill limit of 0 really means "no kill limit"
66  * 
67  * 43    8/22/99 5:53p Dave
68  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
69  * instead of ship designations for multiplayer players.
70  * 
71  * 42    8/22/99 1:19p Dave
72  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
73  * which d3d cards are detected.
74  * 
75  * 41    8/19/99 10:59a Dave
76  * Packet loss detection.
77  * 
78  * 40    8/06/99 2:44a Dave
79  * Make sure dead players who leave respawn AI.
80  * 
81  * 39    8/06/99 12:29a Dave
82  * Multiple bug fixes.
83  * 
84  * 38    8/03/99 11:02p Dave
85  * Maybe fixed sync problems in multiplayer.
86  * 
87  * 37    7/30/99 7:01p Dave
88  * Dogfight escort gauge. Fixed up laser rendering in Glide.
89  * 
90  * 36    7/26/99 5:50p Dave
91  * Revised ingame join. Better? We'll see....
92  * 
93  * 35    7/15/99 9:20a Andsager
94  * FS2_DEMO initial checkin
95  * 
96  * 34    7/08/99 10:53a Dave
97  * New multiplayer interpolation scheme. Not 100% done yet, but still
98  * better than the old way.
99  * 
100  * 33    6/25/99 5:04p Jasenw
101  * Added some debug line stuff.
102  * 
103  * 32    6/16/99 4:06p Dave
104  * New pilot info popup. Added new draw-bitmap-as-poly function.
105  * 
106  * 31    5/18/99 11:50a Andsager
107  * Remove unused object type OBJ_GHOST_SAVE
108  * 
109  * 30    5/04/99 5:20p Dave
110  * Fixed up multiplayer join screen and host options screen. Should both
111  * be at 100% now.
112  * 
113  * 29    5/03/99 8:33p Dave
114  * New version of multi host options screen.
115  * 
116  * 28    4/27/99 12:16a Dave
117  * Fixed beam weapon muzzle glow problem. Fixed premature timeout on the
118  * pxo server list screen. Fixed secondary firing for hosts on a
119  * standalone. Fixed wacky multiplayer weapon "shuddering" problem.
120  * 
121  * 27    4/25/99 7:43p Dave
122  * Misc small bug fixes. Made sun draw properly.
123  * 
124  * 26    4/25/99 3:02p Dave
125  * Build defines for the E3 build.
126  * 
127  * 25    4/09/99 2:21p Dave
128  * Multiplayer beta stuff. CD checking.
129  * 
130  * 24    4/08/99 2:10a Dave
131  * Numerous bug fixes for the beta. Added builtin mission info for the
132  * beta.
133  * 
134  * 23    3/10/99 6:50p Dave
135  * Changed the way we buffer packets for all clients. Optimized turret
136  * fired packets. Did some weapon firing optimizations.
137  * 
138  * 22    3/09/99 6:24p Dave
139  * More work on object update revamping. Identified several sources of
140  * unnecessary bandwidth.
141  * 
142  * 21    3/08/99 7:03p Dave
143  * First run of new object update system. Looks very promising.
144  * 
145  * 20    3/01/99 10:00a Dave
146  * Fxied several dogfight related stats bugs.
147  * 
148  * 19    2/24/99 2:25p Dave
149  * Fixed up chatbox bugs. Made squad war reporting better. Fixed a respawn
150  * bug for dogfight more.
151  * 
152  * 18    2/23/99 2:29p Dave
153  * First run of oldschool dogfight mode. 
154  * 
155  * 17    2/12/99 6:16p Dave
156  * Pre-mission Squad War code is 95% done.
157  * 
158  * 16    2/11/99 3:08p Dave
159  * PXO refresh button. Very preliminary squad war support.
160  * 
161  * 15    2/08/99 5:07p Dave
162  * FS2 chat server support. FS2 specific validated missions.
163  * 
164  * 14    1/30/99 1:29a Dave
165  * Fixed nebula thumbnail problem. Full support for 1024x768 choose pilot
166  * screen.  Fixed beam weapon death messages.
167  * 
168  * 13    1/14/99 6:06p Dave
169  * 100% full squad logo support for single player and multiplayer.
170  * 
171  * 12    1/12/99 4:07a Dave
172  * Put in barracks code support for selecting squad logos. Properly
173  * distribute squad logos in a multiplayer game.
174  * 
175  * 11    12/14/98 4:01p Dave
176  * Got multi_data stuff working well with new xfer stuff. 
177  * 
178  * 10    12/14/98 12:13p Dave
179  * Spiffed up xfer system a bit. Put in support for squad logo file xfer.
180  * Need to test now.
181  * 
182  * 9     11/19/98 4:19p Dave
183  * Put IPX sockets back in psnet. Consolidated all multiplayer config
184  * files into one.
185  * 
186  * 8     11/19/98 8:04a Dave
187  * Full support for D3-style reliable sockets. Revamped packet lag/loss
188  * system, made it receiver side and at the lowest possible level.
189  * 
190  * 7     11/17/98 11:12a Dave
191  * Removed player identification by address. Now assign explicit id #'s.
192  * 
193  * 6     11/05/98 5:55p Dave
194  * Big pass at reducing #includes
195  * 
196  * 5     10/13/98 9:29a Dave
197  * Started neatening up freespace.h. Many variables renamed and
198  * reorganized. Added AlphaColors.[h,cpp]
199  * 
200  * 4     10/09/98 2:57p Dave
201  * Starting splitting up OS stuff.
202  * 
203  * 3     10/07/98 6:27p Dave
204  * Globalized mission and campaign file extensions. Removed Silent Threat
205  * special code. Moved \cache \players and \multidata into the \data
206  * directory.
207  * 
208  * 2     10/07/98 10:53a Dave
209  * Initial checkin.
210  * 
211  * 1     10/07/98 10:50a Dave
212  * 
213  * 283   9/28/98 1:54p Dave
214  * Make sure French and German don't xfer builtin files they don't have
215  * (to themselves)
216  * 
217  * 282   9/28/98 1:41p Dave
218  * Properly detect "builtin" missions.
219  * 
220  * 281   9/21/98 11:46p Dave
221  * Flag mission disk players in the right spot.
222  * 
223  * 280   9/15/98 7:24p Dave
224  * Minor UI changes. Localized bunch of new text.
225  * 
226  * $NoKeywords: $
227  */
228
229 #ifndef PLAT_UNIX
230 #include <winsock.h>
231 #else
232 #include <sys/types.h>
233 #include <sys/socket.h>
234 #include <netinet/in.h>
235 #include <arpa/inet.h>
236 #include <netdb.h>
237 #include <errno.h>
238 #endif
239 #include <ctype.h>
240 #include "multiutil.h"
241 #include "multimsgs.h"
242 #include "multi.h"
243 #include "linklist.h"
244 #include "gamesequence.h"
245 #include "hudmessage.h"
246 #include "freespace.h"
247 #include "key.h"
248 #include "2d.h"
249 #include "weapon.h"
250 #include "timer.h"
251 #include "ship.h"
252 #include "psnet.h"
253 #include "player.h"
254 #include "missionparse.h"
255 #include "missionshipchoice.h"
256 #include "missionscreencommon.h"
257 #include "missionweaponchoice.h"
258 #include "multi_xfer.h"
259 #include "stand_gui.h"
260 #include "shipfx.h"
261 #include "object.h"
262 #include "managepilot.h"
263 #include "multiteamselect.h"
264 #include "shiphit.h"
265 #include "missiondebrief.h"
266 #include "observer.h"
267 #include "missionmessage.h"
268 #include "multilag.h"
269 #include "popup.h"
270 #include "popupdead.h"
271 #include "hudconfig.h"
272 #include "multiui.h"
273 #include "optionsmenu.h"
274 #include "missionhotkey.h"
275 #include "missiongoals.h"
276 #include "afterburner.h"
277 #include "chatbox.h"
278 #include "multi_kick.h"
279 #include "multi_data.h"
280 #include "multi_voice.h"
281 #include "multi_ping.h"
282 #include "multi_team.h"
283 #include "multi_respawn.h"
284 #include "multi_ingame.h"
285 #include "multi_observer.h"
286 #include "multi_pinfo.h"
287 #include "multi_endgame.h"
288 #include "multi_pmsg.h"
289 #include "multi_pause.h"
290 #include "multi_obj.h"
291 #include "multi_log.h"
292 #include "multi_rate.h"
293 #include "osregistry.h"
294 #include "hudescort.h"
295
296 extern int MSG_WINDOW_X_START;  // used to position multiplayer text messages
297 extern int MSG_WINDOW_Y_START;
298 extern int MSG_WINDOW_HEIGHT;
299
300 // if a client doesn't receive an update for an object after this many seconds, query server
301 // as to the objects status.
302 #define MULTI_CLIENT_OBJ_TIMEOUT                10
303 #define MAX_SHIPS_PER_QUERY                     10
304
305
306 // this function assignes the given object with the given signature.  If the signature is 0, then we choose
307 // the next signature number from the correct pool.  I thought that it might be desireable
308 // to not always have to take the next signature on the list.  what_kind is used to assign either a
309 // permanent or non-permanent signature to an object.  permanent signatures are used for ships, non_permanent
310 // signatures are used for everything else.
311 ushort multi_assign_network_signature( int what_kind )
312 {
313         ushort sig;     
314
315         // do limit checking on the permanent and non_permanent signatures.  Ships are considered "permanent"
316         // as are debris and asteroids since they don't die very often.  It would be vary rare for this
317         // value (the permanent signature) to wrap.  For now, this condition is an error condition
318         if ( what_kind == MULTI_SIG_SHIP ) {
319                 if ( Next_ship_signature == 0 ){
320                         Next_ship_signature = SHIP_SIG_MIN;
321                 }
322
323                 sig = Next_ship_signature++;
324
325                 if ( Next_ship_signature == SHIP_SIG_MAX ) {
326                         Int3();                 // get Allender -- signature stuff wrapped.
327                         Next_ship_signature = SHIP_SIG_MIN;
328                 }
329
330                 // signature stuff for asteroids.
331         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
332                 if ( Next_asteroid_signature == 0 ){
333                         Next_asteroid_signature = ASTEROID_SIG_MIN;
334                 }
335
336                 sig = Next_asteroid_signature++;
337                 if ( Next_asteroid_signature == ASTEROID_SIG_MAX ) {
338                         Int3();                 // get Allender -- signature stuff wrapped.
339                         Next_asteroid_signature = ASTEROID_SIG_MIN;
340                 }
341
342                 // signatures for debris
343         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
344                 if ( Next_debris_signature == 0 ){
345                         Next_debris_signature = DEBRIS_SIG_MIN;
346                 }
347
348                 sig = Next_debris_signature++;
349                 if ( Next_debris_signature == DEBRIS_SIG_MAX ) {
350                         Int3();                 // get Allender -- signature stuff wrapped.
351                         Next_debris_signature = DEBRIS_SIG_MIN;
352                 }
353
354                 // signature stuff for weapons and other expendable things.
355         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
356                 if ( Next_non_perm_signature == 0 ){
357                         Next_non_perm_signature = NPERM_SIG_MIN;
358                 }
359
360                 sig = Next_non_perm_signature++;
361                 if ( Next_non_perm_signature == NPERM_SIG_MAX ){
362                         Next_non_perm_signature = NPERM_SIG_MIN;
363                 }
364         } else {
365                 Int3();         // get allender - Illegal signature type requested
366                 sig = 0;
367         }
368
369         return sig;
370 }
371
372 // this function returns the next network signature that will be used for a newly created object
373 // what_kind parameter tells us what kind of signature to get -- permanent or non-permanent
374 ushort multi_get_next_network_signature( int what_kind )
375 {
376         if ( what_kind == MULTI_SIG_SHIP ) {
377                 if ( Next_ship_signature == 0 )
378                         Next_ship_signature = SHIP_SIG_MIN;
379                 return Next_ship_signature;
380
381         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
382                 if ( Next_debris_signature == 0 )
383                         Next_debris_signature = DEBRIS_SIG_MIN;
384                 return Next_debris_signature;
385
386         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
387                 if ( Next_asteroid_signature == 0 )
388                         Next_asteroid_signature = ASTEROID_SIG_MIN;
389                 return Next_asteroid_signature;
390
391         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
392                 if ( Next_non_perm_signature == 0 )
393                         Next_non_perm_signature = NPERM_SIG_MIN;
394                 return Next_non_perm_signature;
395
396         } else {
397                 Int3();                 // get allender
398                 return 0;
399         }
400 }
401
402 // this routine sets the network signature to the given value.  Should be called from client only
403 // and is used mainly for firing weapons.  what_kind tells us permanent or non-permanent signature
404 void multi_set_network_signature( ushort signature, int what_kind )
405 {
406         SDL_assert( signature != 0 );
407
408         if ( what_kind == MULTI_SIG_SHIP ) {
409                 SDL_assert( (signature >= SHIP_SIG_MIN) && (signature <= SHIP_SIG_MAX) );
410                 Next_ship_signature = signature;
411         } else if ( what_kind == MULTI_SIG_DEBRIS ) {
412                 SDL_assert( (signature >= DEBRIS_SIG_MIN) && (signature <= DEBRIS_SIG_MAX) );
413                 Next_debris_signature = signature;
414         } else if ( what_kind == MULTI_SIG_ASTEROID ) {
415                 SDL_assert( (signature >= ASTEROID_SIG_MIN) && (signature <= ASTEROID_SIG_MAX) );
416                 Next_asteroid_signature = signature;
417         } else if ( what_kind == MULTI_SIG_NON_PERMANENT ) {
418                 SDL_assert( (signature >= NPERM_SIG_MIN) && (signature <= NPERM_SIG_MAX) );
419                 Next_non_perm_signature = signature;
420         } else
421                 Int3();                 // get Allender
422 }
423
424 // multi_get_network_object() takes a net_signature and tries to locate the object in the object list
425 // with that network signature.  Returns NULL if the object cannot be found
426 object *multi_get_network_object( ushort net_signature )
427 {
428         object *objp;
429
430         if ( net_signature == 0 )
431                 return NULL;
432
433         if(GET_FIRST(&obj_used_list) == NULL)
434                 return NULL;
435
436         for ( objp = GET_FIRST(&obj_used_list); objp != END_OF_LIST(&obj_used_list); objp = GET_NEXT(objp) )
437                 if ( objp->net_signature == net_signature )
438                         break;
439
440         // if not found on used list, check create list
441         if ( objp == END_OF_LIST(&obj_used_list) ) {
442                 for ( objp = GET_FIRST(&obj_create_list); objp != END_OF_LIST(&obj_create_list); objp = GET_NEXT(objp) )
443                         if ( objp->net_signature == net_signature )
444                                 break;
445
446                 if ( objp == END_OF_LIST(&obj_create_list) )
447                         objp = NULL;
448         }
449
450         return objp;
451 }
452
453
454 // -------------------------------------------------------------------------------------------------
455 //      multi_random_death_word() will return a word from the below list at random.
456 //
457 //      Note:  Keep words grouped into sections of 10
458
459 #define NUM_DEATH_WORDS 40
460
461 const char *multi_random_death_word()
462 {
463         int index;
464
465         index = rand() % NUM_DEATH_WORDS;
466         switch (index) {
467                 case 0:
468                         return XSTR("zapped",853);
469                 case 1:
470                         return XSTR("caulked",854);
471                 case 2:
472                         return XSTR("killed",855);
473                 case 3:
474                         return XSTR("waxed",856);
475                 case 4:
476                         return XSTR("popped",857);
477                 case 5:
478                         return XSTR("murdered",858);
479                 case 6:
480                         return XSTR("bludgeoned",859);
481                 case 7:
482                         return XSTR("destroyed",860);
483                 case 8:
484                         return XSTR("iced",861);
485                 case 9:
486                         return XSTR("obliterated",862);
487                 case 10:
488                         return XSTR("toasted",863);
489                 case 11:
490                         return XSTR("roasted",864);
491                 case 12:
492                         return XSTR("turned into anti-matter",865);
493                 case 13:
494                         return XSTR("killed like a pig",866);
495                 case 14:
496                         return XSTR("taught a lesson",867);
497                 case 15:
498                         return XSTR("slaughtered with impunity",868);
499                 case 16:
500                         return XSTR("spanked like a naughty boy",869);
501                 case 17:
502                         return XSTR("skunked",870);
503                 case 18:
504                         return XSTR("beat senseless",871);
505                 case 19:
506                         return XSTR("shot up",872);
507                 case 20:
508                         return XSTR("spaced",873);
509                 case 21:
510                         return XSTR("hosed",874);
511                 case 22:
512                         return XSTR("capped",875);
513                 case 23:
514                         return XSTR("beat down",876);
515                 case 24:
516                         return XSTR("hit wit da shizzo",877);
517                 case 25:
518                         return XSTR("sk00led",878);
519                 case 26:
520                         return XSTR("whooped up",879);
521                 case 27:
522                         return XSTR("brought to the all-you-can-take whoop ass buffet",880);
523                 case 28:
524                         return XSTR("served up a whoop ass sandwich...hold the mercy",881);
525                 case 29:
526                         return XSTR("gibbed by Kayser Sozay's rocket",882);
527                 case 30:
528                         return XSTR("shot down",883);
529                 case 31:
530                         return XSTR("given early retirement",884);
531                 case 32:
532                         return XSTR("instructed",885);
533                 case 33:
534                         return XSTR("eviscerated",886);
535                 case 34:
536                         return XSTR("pummelled",887);
537                 case 35:
538                         return XSTR("eradicated",888);
539                 case 36:
540                         return XSTR("cleansed",889);
541                 case 37:
542                         return XSTR("perforated",890);
543                 case 38:
544                         return XSTR("canned",891);
545                 case 39:
546                         return XSTR("decompressed",892);
547         }
548
549         return NOX("Error");
550 }
551
552 // -------------------------------------------------------------------------------------------------
553 //      multi_random_chat_start() will return a word from the below list at random.
554 //
555 //
556
557 #define NUM_CHAT_START_WORDS    8
558 #define MAX_CHAT_PHRASE_LEN     25              // be careful not to exceed (or update if exceeded)
559
560 const char *multi_random_chat_start()
561 {
562         int index;
563
564         index = rand() % NUM_CHAT_START_WORDS;
565         switch (index) {
566                 case 0:
567                         return XSTR("says",893);
568                 case 1:
569                         return XSTR("bleats",894);
570                 case 2:
571                         return XSTR("opines",895);
572                 case 3:
573                         return XSTR("postulates",896);
574                 case 4:
575                         return XSTR("declares",897);
576                 case 5:
577                         return XSTR("vomits out",898);
578                 case 6:
579                         return XSTR("whines",899);
580                 case 7:
581                         return XSTR("barks",900);
582         }
583
584         return NOX("Error");
585 }
586
587 // -------------------------------------------------------------------------------------------------
588 //      multi_ship_class_lookup() will return the Ship_info[] index for the ship specified as a 
589 // parameter.
590 //
591 //
592
593 int multi_ship_class_lookup(const char* ship_name)
594 {
595         int i, player_ship_class;
596
597         // find the ship_info index for the ship_name
598
599         player_ship_class = -1;
600         for (i = 0; i < Num_ship_types; i++) {
601                 if ( !SDL_strcasecmp(Ship_info[i].name, ship_name) ) {
602                         player_ship_class = i;
603                         break;
604                 }
605         } // end for 
606
607         if (i == Num_ship_types){
608                 return -1;
609         }
610
611         return player_ship_class;
612 }
613
614 // -------------------------------------------------------------------------------------------------
615 //      find_player() is called when a packet arrives, and we need to know which net player to update.
616 // The matching is done based on the address and port.  Port checking is done in case multiple
617 // instances of FreeSpace are running on the same box.
618 //
619 //
620
621 int find_player( net_addr_t* addr )
622 {
623         int i;
624
625         for (i = 0; i < MAX_PLAYERS; i++ ) {
626                 if ( !MULTI_CONNECTED(Net_players[i])){
627                         continue;
628                 }
629                 if ( psnet_same( addr, &(Net_players[i].p_info.addr)) ){
630                         return i;
631                 }
632         }
633
634         return -1;
635 }
636
637 // so that we can lookup on the admin port transparently
638 int find_player_no_port(net_addr_t *addr)
639 {
640         int i;
641         int len;
642
643         for (i = 0; i < MAX_PLAYERS; i++ ) {
644                 if ( !MULTI_CONNECTED(Net_players[i])){
645                         continue;
646                 }
647                 if(addr->type == NET_IPX){
648                         len = 6;
649                 } else { 
650                         len = 4;
651                 }
652                 if ( memcmp(&addr->addr,&Net_players[i].p_info.addr.addr,len)== 0){
653                         return i;
654                 }
655         }
656
657         return -1;
658 }
659
660 int find_player_id(short player_id)
661 {
662         int i;
663         for (i = 0; i < MAX_PLAYERS; i++ ) {
664                 if ( !MULTI_CONNECTED(Net_players[i])){
665                         continue;
666                 }
667                 if(player_id == Net_players[i].player_id){
668                         return i;
669                 }
670         }       
671
672         // couldn't find the player
673         return -1;
674 }
675
676 // note this is only valid to do on a server!
677 int find_player_socket(PSNET_SOCKET_RELIABLE sock)
678 {
679         int i;
680         for (i = 0; i < MAX_PLAYERS; i++ ) {
681                 if ( !MULTI_CONNECTED(Net_players[i])){
682                         continue;
683                 }
684                 if(sock == Net_players[i].reliable_socket){
685                         return i;
686                 }
687         }       
688
689         // couldn't find the player
690         return -1;
691 }
692
693 // multi_find_player_by_object returns a player num (reference by Net_players[x]) when given a object *.
694 // used to find netplayers in game when only the object is known
695 int multi_find_player_by_object( object *objp )
696 {
697         int i, objnum;
698
699         objnum = OBJ_INDEX(objp);
700         for (i = 0; i < MAX_PLAYERS; i++ ) {
701                 if ( !MULTI_CONNECTED(Net_players[i])){
702                         continue;
703                 }
704                 if ( objnum == Net_players[i].player->objnum ){
705                         return i;
706                 }
707         }
708
709         // return -1 if the object is not found -- this is a bad situation, but we will handle it in higher
710         // level code
711         return -1;
712 }
713
714 // returns a player num based upon player object signature
715 int multi_find_player_by_signature( int signature )
716 {
717         int idx;
718
719         for(idx=0;idx<MAX_PLAYERS;idx++){
720                 // compare against each player's object signature
721                 if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].signature == signature)){
722                         // found the player
723                         return idx;
724                 }
725         }
726
727         // didn't find the player
728         return -1;
729 }
730
731 // returns a player num based upon object net signature
732 int multi_find_player_by_net_signature(ushort net_signature)
733 {
734         int idx;
735
736         for(idx=0;idx<MAX_PLAYERS;idx++){
737                 // compare against each player's object signature
738                 if(MULTI_CONNECTED(Net_players[idx]) && (Objects[Net_players[idx].player->objnum].net_signature == net_signature)){
739                         // found the player
740                         return idx;
741                 }
742         }
743
744         // didn't find the player
745         return -1;
746 }
747
748 int multi_find_player_by_ship_name(const char *ship_name)
749 {
750         int idx;
751
752         // bogus
753         if(ship_name == NULL){
754                 return -1;
755         }
756
757         for(idx=0; idx<MAX_PLAYERS; idx++){
758                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player != NULL) && (Net_players[idx].player->objnum >= 0) && (Net_players[idx].player->objnum < MAX_OBJECTS) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP) && 
759                         (Objects[Net_players[idx].player->objnum].instance >= 0) && (Objects[Net_players[idx].player->objnum].instance < MAX_SHIPS) && !SDL_strcasecmp(ship_name, Ships[Objects[Net_players[idx].player->objnum].instance].ship_name) ){
760                         return idx;
761                 }
762         }
763
764         // didn't find the player
765         return -1;
766 }
767
768 int multi_get_player_ship(int np_index)
769 {
770         // bogus
771         if((np_index < 0) || (np_index >= MAX_PLAYERS)){
772                 return -1;
773         }
774
775         // cool?
776         if(MULTI_CONNECTED(Net_players[np_index]) && !MULTI_OBSERVER(Net_players[np_index]) && !MULTI_STANDALONE(Net_players[np_index]) && 
777                 (Net_players[np_index].player != NULL) && (Net_players[np_index].player->objnum >= 0) && (Net_players[np_index].player->objnum < MAX_OBJECTS) && (Objects[Net_players[np_index].player->objnum].type == OBJ_SHIP) && 
778                 (Objects[Net_players[np_index].player->objnum].instance >= 0) && (Objects[Net_players[np_index].player->objnum].instance < MAX_SHIPS) ){
779
780                 return Objects[Net_players[np_index].player->objnum].instance;
781         }
782
783         // nope
784         return -1;
785 }
786
787 // find_open_netplayer_slot() attempts to find a free slot in the Net_players structure for a new player.
788 // it returns -1 if there is no new slot, and the slot number if one is found
789 // NOTE : this attempts to preserve a player object as long as possible for him to come back to
790 int multi_find_open_netplayer_slot()
791 {
792         int i;
793         int found_first;
794
795         found_first = -1;
796         for (i = 0; i < MAX_PLAYERS; i++)
797                 if ( !MULTI_CONNECTED(Net_players[i]) ){
798                    if(found_first == -1) {
799                                 found_first = i;
800                                 break;
801                         }
802                 }
803
804         if(i == MAX_PLAYERS){
805                 if(found_first == -1)
806                         return -1;
807                 else
808                         return found_first;
809         }
810
811         return i;
812 }
813
814 // find_open_player_slot() attempts to find an open player array slot.  The 0th element of the array
815 // should always be taken by the console player's pilot.  All other slots are up for grab though.
816 int multi_find_open_player_slot()
817 {
818         int i;
819
820         for (i = 0; i < MAX_PLAYERS; i++)
821                 if ( !(Players[i].flags & PLAYER_FLAGS_STRUCTURE_IN_USE) )
822                         break;
823         
824         if ( i == MAX_PLAYERS )
825                 return -1;
826
827         return i;
828 }
829
830 // stuff_netplayer_info stuffs information into the given Net_player structure.  It is called when
831 // a new person is entering the game.  The state of the Net_player is set to it's basic starting
832 // state
833 void stuff_netplayer_info( net_player *nplayer, net_addr_t *addr, int ship_class, player *pplayer )
834 {
835         nplayer->p_info.addr = *addr;
836         nplayer->flags |= NETINFO_FLAG_CONNECTED;
837         nplayer->state = NETPLAYER_STATE_JOINING;
838         nplayer->p_info.ship_class = ship_class;
839         nplayer->player = pplayer;
840         nplayer->p_info.options.obj_update_level = OBJ_UPDATE_HIGH;
841
842         // if setting up my net flags, then set the flag to say I can do networking.
843         if ( nplayer == Net_player ){
844                 nplayer->flags |= NETINFO_FLAG_DO_NETWORKING;
845         }
846 }
847
848 // multi_assign_player_ship takes a Net_player index and an object * and assigned that player to
849 // that object
850 void multi_assign_player_ship( int net_player, object *objp,int ship_class )
851 {
852         ship *shipp;
853         int idx;
854
855         SDL_assert ( MULTI_CONNECTED(Net_players[net_player]) );
856
857         shipp = &Ships[objp->instance];
858
859         Net_players[net_player].player->objnum = OBJ_INDEX(objp);
860         Net_players[net_player].p_info.ship_class = ship_class;
861
862         // check to see if we are assigning my player -- if so, then set Player_ship and Player_ai
863         if ( Net_player == &Net_players[net_player] ) {
864                 Player_obj = objp;
865                 Player_ship = shipp;
866                 Player_ai = &Ai_info[Player_ship->ai_index];
867         }
868
869         // find the parse object for this ship.  Also, set the wingman status stuff so wingman status gauge
870         // works properly.
871         Net_players[net_player].p_info.p_objp = mission_parse_get_arrival_ship( shipp->ship_name );
872         SDL_assert( Net_players[net_player].p_info.p_objp != NULL );            // get allender -- ship should be on list
873         Net_players[net_player].p_info.p_objp->ship_class = ship_class;         // be sure this gets set so respawns work
874
875         // game server and this client need to initialize this information so object updating
876         // works properly.
877         if ( MULTIPLAYER_MASTER || (Net_player == &Net_players[net_player]) ) {
878                 Net_players[net_player].s_info.eye_pos = objp->pos;
879                 Net_players[net_player].s_info.eye_orient = objp->orient;
880         }
881
882         // zero update info     
883         for(idx=0; idx<MAX_PLAYERS; idx++){
884                 shipp->np_updates[idx].orient_chksum = 0;
885                 shipp->np_updates[idx].pos_chksum = 0;
886                 shipp->np_updates[idx].seq = 0;
887                 shipp->np_updates[idx].status_update_stamp = -1;
888                 shipp->np_updates[idx].subsys_update_stamp = -1;
889                 shipp->np_updates[idx].update_stamp = -1;
890         }
891 }
892
893 // -------------------------------------------------------------------------------------------------
894 //      create_player() is called when a net player needs to be instantiated.  The ship that is created
895 // depends on the parameter ship_class.  Note that if ship_class is invalid, the ship default_player_ship
896 // is used.  Returns 1 on success, 0 otherwise
897
898 int multi_create_player( int net_player_num, player *pl, char* name, net_addr_t* addr, int ship_class, short id)
899 {
900         int player_ship_class = ship_class;
901         int i,current_player_count;
902
903         SDL_assert ( net_player_num < MAX_PLAYERS );                            // probably shoudln't be able to even get into this routine if no room  
904         
905         // blast _any_ old data
906         memset(&Net_players[net_player_num],0,sizeof(net_player));
907
908         // get the current # of players
909         current_player_count = multi_num_players();
910
911         // DOH!!! The lack of this caused many bugs. 
912         Net_players[net_player_num].flags = (NETINFO_FLAG_DO_NETWORKING);
913                 
914         if ( ship_class == -1 ) {
915                 nprintf(("Network","Network ==> ship class is -1, creating a default ship for multiplayer\n"));
916
917                 // find the ship that matches the string stored in default_player_ship
918
919                 for (i = 0; i < Num_ship_types; i++) {
920                         if ( !SDL_strcasecmp(Ship_info[i].name, default_player_ship) ) {
921                                 player_ship_class = i;
922                                 break;
923                         }
924                 }
925
926                 if (i == Num_ship_types)
927                         SDL_assert(0);
928         }
929         
930         if ( player_ship_class >= Num_ship_types ) {
931                 player_ship_class = multi_ship_class_lookup(default_player_ship);
932                 nprintf(("Network","Network ==> Ship class was %d Creating a default ship for multiplayer\n", player_ship_class));
933         }
934
935         // blast the old player data
936         memset(pl,0,sizeof(player));
937
938         // set up the net_player structure
939         stuff_netplayer_info( &Net_players[net_player_num], addr, player_ship_class, pl );
940         Net_players[net_player_num].s_info.num_last_buttons = 0;
941         // Net_players[net_player_num].respawn_count = 0;
942         Net_players[net_player_num].last_heard_time = timer_get_fixed_seconds();
943         Net_players[net_player_num].reliable_socket = INVALID_SOCKET;
944         Net_players[net_player_num].s_info.kick_timestamp = -1;
945         Net_players[net_player_num].s_info.voice_token_timestamp = -1;
946         Net_players[net_player_num].s_info.tracker_security_last = -1;
947         Net_players[net_player_num].s_info.target_objnum = -1;
948         Net_players[net_player_num].s_info.accum_buttons = 0;
949
950         // zero out this players ping times data
951         multi_ping_reset(&Net_players[net_player_num].s_info.ping);
952
953         // zero out his object update and control info sequencing data
954         Net_players[net_player_num].client_cinfo_seq = 0;
955         Net_players[net_player_num].client_server_seq = 0;              
956         
957         // timestamp his last_full_update_time
958         Net_players[net_player_num].s_info.last_full_update_time = timestamp(0);
959
960         // nil his file xfer handle
961         Net_players[net_player_num].s_info.xfer_handle = -1;
962
963         // nil his data rate timestamp stuff
964         Net_players[net_player_num].s_info.rate_stamp = -1;
965         Net_players[net_player_num].s_info.rate_bytes = 0;
966
967         // nil packet buffer stuff
968         Net_players[net_player_num].s_info.unreliable_buffer_size = 0;
969         Net_players[net_player_num].s_info.reliable_buffer_size = 0;
970         
971         // various ack handles  
972         SDL_strlcpy(pl->callsign, name, sizeof(pl->callsign));
973         pilot_set_short_callsign(pl, SHORT_CALLSIGN_PIXEL_W);   // calculate the short callsign 
974         pl->flags |= PLAYER_FLAGS_STRUCTURE_IN_USE;
975         pl->objnum = -1;
976
977         // if we're the standalone server and this is the first guy to join, mark him as the host
978         // and give him all host priveleges
979         if((Game_mode & GM_STANDALONE_SERVER) && (current_player_count == 0)){
980                 Net_players[net_player_num].flags |= NETINFO_FLAG_GAME_HOST;
981         }
982         
983         Net_players[net_player_num].player_id = id;
984
985         Net_player->sv_bytes_sent = 0;
986         Net_player->sv_last_pl = -1;
987         Net_player->cl_bytes_recvd = 0;
988         Net_player->cl_last_pl = -1;
989
990         // add to the escort list
991         if(MULTI_IN_MISSION){
992                 hud_escort_add_player(id);
993         }
994
995         return 1;
996 }
997
998 // next function makes a player object an ai object (also decrementing the num_players in the
999 // netgame).  It appropiately sets the object flags and other interesting AI information which
1000 // ought to get set in order to make this new ai object behave correctly.
1001 void multi_make_player_ai( object *pobj )
1002 {
1003
1004         SDL_assert ( pobj != NULL );
1005
1006         if ( pobj->type != OBJ_SHIP )
1007                 return;
1008
1009         pobj->flags &= ~(OF_PLAYER_SHIP);
1010         obj_set_flags( pobj, pobj->flags | OF_COULD_BE_PLAYER );
1011
1012         // target_objnum must be -1 or else new AI ship will fire on whatever this player
1013         // had targeted.
1014         set_target_objnum( &(Ai_info[Ships[pobj->instance].ai_index]), -1 );
1015
1016 }
1017
1018 // delete_player takes an index into the Net_players array to delete.  Deletion of a player might happen
1019 // because of the player leaving the game on his own, or no net activity from the player after X seconds
1020 void delete_player(int player_num,int kicked_reason)
1021 {                       
1022         char notify_string[256] = "";
1023         int idx;
1024         
1025         if(!MULTI_CONNECTED(Net_players[player_num])){
1026                 return;
1027         }
1028
1029         // NETLOG
1030         ml_printf(NOX("Deleting player %s"), Net_players[player_num].player->callsign);
1031         
1032         psnet_rel_close_socket( &(Net_players[player_num].reliable_socket) );                                   // close out the reliable socket        
1033
1034         // if this guy was ingame joining, the remove my netgame flag so others may join
1035         if ( Net_players[player_num].flags & NETINFO_FLAG_INGAME_JOIN ) {
1036                 Netgame.flags &= ~NG_FLAG_INGAME_JOINING;
1037                 Netgame.flags &= ~NG_FLAG_INGAME_JOINING_CRITICAL;
1038         }
1039         
1040         Net_players[player_num].flags &= ~NETINFO_FLAG_CONNECTED;                                                       // person not connected anymore
1041         Net_players[player_num].player->flags &= ~(PLAYER_FLAGS_STRUCTURE_IN_USE);    // free up his player structure
1042
1043         Net_players[player_num].s_info.reliable_connect_time = -1;
1044
1045         // add to the escort list
1046         hud_escort_remove_player(Net_players[player_num].player_id);
1047
1048         // is this guy the server
1049         if(Net_players[player_num].flags & NETINFO_FLAG_AM_MASTER){
1050                 // if the server leaves in the debriefing state, we should still wait until the player selects accept before we quit
1051                 if ((gameseq_get_state() != GS_STATE_DEBRIEF) && (gameseq_get_state() != GS_STATE_MULTI_DOGFIGHT_DEBRIEF)){
1052                         multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_SERVER_LEFT);
1053                 }               
1054         }
1055         // if he was just the host      
1056         else if(Net_players[player_num].flags & NETINFO_FLAG_GAME_HOST){
1057                 Net_players[player_num].flags &= ~(NETINFO_FLAG_GAME_HOST);
1058         
1059                 // am I the server
1060                 if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){
1061                         // are we a standalone server and in a mission?
1062                         if((Game_mode & GM_STANDALONE_SERVER) && MULTI_IN_MISSION){                     
1063                                 // choose a new host                    
1064                                 int found_new_host = 0;
1065                                 for(idx=0; idx<MAX_PLAYERS; idx++){
1066                                         if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx])){
1067                                                 // make this guy the host
1068                                                 Net_players[idx].flags |= NETINFO_FLAG_GAME_HOST;
1069
1070                                                 // send a packet
1071                                                 send_host_captain_change_packet(Net_players[idx].player_id, 0);
1072
1073                                                 found_new_host = 1;
1074                                                 break;
1075                                         }
1076                                 }
1077                                 // end the game         
1078                                 if(!found_new_host){
1079                                         multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
1080                                 }                        
1081                         } else {
1082                                 multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_HOST_LEFT);
1083                         }
1084                 } 
1085         }
1086
1087         // if we're the server of the game, notify everyone else that this guy has left
1088         // if he's marked as being kicked, then other players know about it already, so don't send again
1089         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
1090                 if(Net_players[player_num].flags & NETINFO_FLAG_KICKED){
1091                         char str[512];
1092                         memset(str, 0, 512);
1093                         multi_kick_get_text(&Net_players[player_num], Net_players[player_num].s_info.kick_reason, str, sizeof(str));
1094                         multi_display_chat_msg(str, player_num, 0);                                                      
1095                 } else {
1096                         send_leave_game_packet(Net_players[player_num].player_id, kicked_reason);
1097                 }
1098         }
1099         
1100         // if this guy is an observer, we have to make sure we delete his observer object (only if we're the server however)
1101         if( (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Net_players[player_num].flags & NETINFO_FLAG_OBSERVER) ) {
1102                 if ( Net_players[player_num].player->objnum != -1 ){
1103                         obj_delete(Net_players[player_num].player->objnum);                     // maybe change this to set flag instead                
1104                 }
1105         } else {
1106                 // otherwise mark it so that he can return to it later if possible
1107                 if ( (Net_players[player_num].player->objnum >= 0) && (Net_players[player_num].player->objnum < MAX_OBJECTS) && (Objects[Net_players[player_num].player->objnum].type == OBJ_SHIP) && (Objects[Net_players[player_num].player->objnum].instance >= 0) && (Objects[Net_players[player_num].player->objnum].instance < MAX_SHIPS)) {
1108                         multi_make_player_ai( &Objects[Net_players[player_num].player->objnum] );
1109                 } else {
1110                         multi_respawn_player_leave(&Net_players[player_num]);
1111                 }
1112         }
1113
1114         // if we're in the team select, and we're the host, we have to make sure all team select data is correctly updated                      
1115         // MWA 7/28/98.  Don't do this for a standalone server.  Since he doesn't go through the team selection
1116         // screens, his data structures are not 100% accurate.  Doing so on a standalone resulted in the wrong
1117         // ships getting marked as COULD_BE_PLAYER.  On the standalone, these flags will get properly set
1118         // in the multi_make_player_ai code above.
1119         if( (Netgame.game_state == NETGAME_STATE_BRIEFING) && !(Game_mode & GM_STANDALONE_SERVER) ) {
1120                 multi_ts_handle_player_drop();                  
1121         }                                                               
1122
1123         if (gameseq_get_state() == GS_STATE_DEBRIEF){
1124                 debrief_handle_player_drop();
1125         }
1126
1127         // handle any specific dropping conditions
1128         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
1129                 multi_team_handle_drop();
1130         }       
1131         multi_data_handle_drop(player_num);     
1132
1133         // tell the pinfo popup that a player has left
1134         multi_pinfo_notify_drop(&Net_players[player_num]);
1135
1136         // tell the datarate stuff that the player has dropped
1137         multi_rate_reset(player_num);
1138
1139         // display a message that this guy has left
1140         if(Net_players[player_num].player->callsign){
1141                 SDL_snprintf(notify_string,sizeof(notify_string),XSTR("<%s has left>",901),Net_players[player_num].player->callsign);
1142                 multi_display_chat_msg(notify_string,0,0);
1143         }
1144         
1145         // standalone gui type stuff
1146         if (Game_mode & GM_STANDALONE_SERVER) {
1147                 std_remove_player(&Net_players[player_num]);
1148                 std_connect_set_connect_count();
1149         }
1150
1151         // blast this memory clean
1152         memset(&Net_players[player_num], 0, sizeof(net_player));
1153         Net_players[player_num].reliable_socket = INVALID_SOCKET;
1154
1155         extern int Multi_client_update_times[MAX_PLAYERS];
1156         Multi_client_update_times[player_num] = -1;
1157 }
1158
1159 #define INACTIVE_LIMIT_NORMAL (15 * F1_0)
1160 #define INACTIVE_LIMIT_WAIT   (20 * F1_0)
1161
1162 // -------------------------------------------------------------------------------------------------
1163 //      multi_cull_zombies() will check if there has been any net players or observers that have been inactive for
1164 // INACTIVE_LIMIT milliseconds since last check.  If so, they are taken out of the net game.
1165 //
1166 //
1167
1168 void multi_cull_zombies()
1169 {
1170 #if 0
1171         fix current_time;
1172         int inactive_limit;
1173         int i;
1174
1175         if(gameseq_get_state() == GS_STATE_MULTI_WAIT)
1176                 inactive_limit = INACTIVE_LIMIT_WAIT;
1177         else
1178                 inactive_limit = INACTIVE_LIMIT_NORMAL;
1179
1180         current_time = timer_get_fixed_seconds();
1181
1182         for (i = 0; i < MAX_PLAYERS; i++) {
1183                 if ( !MULTI_CONNECTED(&Net_players[i])){
1184                         continue;
1185                 }
1186
1187                 // server will(should) cull out players based on their sockets dying.
1188                 if ( Net_players[i].flags & NETINFO_FLAG_MASTER ){
1189                         continue;
1190                 }
1191
1192                 if ( (current_time - Net_players[i].last_heard_time) > inactive_limit) {
1193                         HUD_printf(XSTR("Dumping %s after prolonged inactivity",902),Net_players[i].player->callsign);
1194                         nprintf(("Network", "Assuming %s is a zombie, removing from game\n", Net_players[i].player->callsign));
1195
1196                         multi_kick_player(i,0);                 
1197                 }
1198         }
1199 #endif
1200 }
1201
1202 // -------------------------------------------------------------------------------------------------
1203 // netmisc_calc_checksum() calculates the checksum of a block of memory.
1204 //
1205 //
1206 ushort netmisc_calc_checksum( void * vptr, int len )
1207 {
1208         ubyte * ptr = (ubyte *)vptr;
1209         unsigned int sum1,sum2;
1210
1211         sum1 = sum2 = 0;
1212
1213         while(len--)    {
1214                 sum1 += *ptr++;
1215                 if (sum1 >= 255 ) sum1 -= 255;
1216                 sum2 += sum1;
1217         }
1218         sum2 %= 255;
1219         
1220         return (unsigned short)((sum1<<8)+ sum2);
1221 }
1222
1223
1224 // -------------------------------------------------------------------------------------------------
1225 // fill_net_addr() calculates the checksum of a block of memory.
1226 //
1227 //
1228
1229 void fill_net_addr(net_addr_t* addr, ubyte* address, ubyte* net_id, ushort port)
1230 {
1231         SDL_assert(addr != NULL);
1232         SDL_assert(address != NULL);
1233         SDL_assert(net_id != NULL);
1234
1235         addr->type = Multi_options_g.protocol;
1236         memset( addr->addr, 0x00, 6);
1237         memcpy( addr->addr, address, ADDRESS_LENGTH);
1238         memcpy( addr->net_id, net_id, 4);
1239         addr->port = port;
1240 }
1241
1242
1243
1244 // -------------------------------------------------------------------------------------------------
1245 // get_text_address()
1246 //
1247 //
1248
1249 char* get_text_address( char * text, const int max_textlen, ubyte * address )
1250 {
1251
1252         in_addr temp_addr;
1253
1254         switch ( Multi_options_g.protocol ) {
1255                 case NET_IPX:
1256                         SDL_strlcpy( text, XSTR("[ipx address here]",903), max_textlen );       // TODO: find equiv to inet_ntoa() for IPX
1257                         SDL_snprintf(text, max_textlen, "%x %x %x %x %x %x",    address[0],
1258                                                                                                                         address[1],
1259                                                                                                                         address[2],
1260                                                                                                                         address[3],
1261                                                                                                                         address[4],
1262                                                                                                                         address[5]);
1263
1264                         break;
1265
1266                 case NET_TCP:
1267                         memcpy(&temp_addr.s_addr, address, 4);
1268                         SDL_strlcpy( text, inet_ntoa(temp_addr), max_textlen );
1269                         break;
1270
1271                 default:
1272                         SDL_assert(0);
1273                         break;
1274
1275         } // end switch
1276
1277         return text;
1278 }
1279
1280 // non-16byte version of matrix packing
1281 // return size of packed matrix
1282 void multi_pack_orient_matrix(ubyte *data,matrix *m)
1283 {       
1284         data[16] = 0;
1285         float x1, y1, x2, y2;
1286
1287         if(m->v.rvec.xyz.z < 0) data[16] |= (1<<0);     // X
1288         if(m->v.uvec.xyz.z < 0) data[16] |= (1<<1);     // Y
1289         if(m->v.fvec.xyz.z < 0) data[16] |= (1<<2);     // V
1290         if(m->v.fvec.xyz.x < 0) data[16] |= (1<<3);     // Z
1291         if(m->v.fvec.xyz.y < 0) data[16] |= (1<<4);     // W
1292
1293         x1 = INTEL_FLOAT(m->v.rvec.xyz.x);
1294         y1 = INTEL_FLOAT(m->v.rvec.xyz.y);
1295         x2 = INTEL_FLOAT(m->v.uvec.xyz.x);
1296         y2 = INTEL_FLOAT(m->v.uvec.xyz.y);
1297
1298         memcpy(&data[0], &x1, 4);       // a
1299         memcpy(&data[4], &y1, 4);       // b
1300         memcpy(&data[8], &x2, 4);       // c
1301         memcpy(&data[12], &y2, 4);      // d
1302 }
1303
1304 // return bytes processed
1305 // non-16 byte version of unpack matrix code
1306 void multi_unpack_orient_matrix(ubyte *data,matrix *m)
1307 {
1308         float x1, y1, x2, y2;
1309
1310         memcpy(&x1, &data[0], 4);
1311         memcpy(&y1, &data[4], 4);
1312         memcpy(&x2, &data[8], 4);
1313         memcpy(&y2, &data[12],4);
1314
1315         m->v.rvec.xyz.x = INTEL_FLOAT(x1);
1316         m->v.rvec.xyz.y = INTEL_FLOAT(y1);
1317         m->v.uvec.xyz.x = INTEL_FLOAT(x2);
1318         m->v.uvec.xyz.y = INTEL_FLOAT(y2);
1319         
1320         m->v.rvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.x * m->v.rvec.xyz.x) - (m->v.rvec.xyz.y * m->v.rvec.xyz.y))); // X
1321         m->v.uvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.uvec.xyz.x * m->v.uvec.xyz.x) - (m->v.uvec.xyz.y * m->v.uvec.xyz.y))); // Y
1322         m->v.fvec.xyz.z = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.z * m->v.rvec.xyz.z) - (m->v.uvec.xyz.z * m->v.uvec.xyz.z))); // V
1323         m->v.fvec.xyz.x = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.x * m->v.rvec.xyz.x) - (m->v.uvec.xyz.x * m->v.uvec.xyz.x))); // Z
1324         m->v.fvec.xyz.y = fl_sqrt(fl_abs(1 - (m->v.rvec.xyz.y * m->v.rvec.xyz.y) - (m->v.uvec.xyz.y * m->v.uvec.xyz.y))); // W
1325
1326         m->v.rvec.xyz.z *= (data[16] & (1<<0)) ? -1.0f : 1.0f;
1327         m->v.uvec.xyz.z *= (data[16] & (1<<1)) ? -1.0f : 1.0f;
1328         m->v.fvec.xyz.z *= (data[16] & (1<<2)) ? -1.0f : 1.0f;
1329         m->v.fvec.xyz.x *= (data[16] & (1<<3)) ? -1.0f : 1.0f;
1330         m->v.fvec.xyz.y *= (data[16] & (1<<4)) ? -1.0f : 1.0f;
1331 }
1332                               
1333 void multi_do_client_warp(float flFrametime)
1334 {
1335    ship_obj *moveup;
1336         
1337    moveup = GET_FIRST(&Ship_obj_list);
1338         while(moveup!=END_OF_LIST(&Ship_obj_list)){
1339                 // do all _necessary_ ship warp in (arrival) processing
1340                 if ( Ships[Objects[moveup->objnum].instance].flags & SF_ARRIVING )      
1341                         shipfx_warpin_frame( &Objects[moveup->objnum], flFrametime );
1342                 moveup = GET_NEXT(moveup);
1343         }       
1344 }       
1345
1346 // ------------------------------------------------------------------------------------
1347 // ship status change stuff
1348
1349 int lookup_ship_status(net_player *p,int unique_id,int remove)
1350 {
1351         int idx;
1352         
1353         for(idx=0;idx<p->s_info.num_last_buttons;idx++){
1354                 if(p->s_info.last_buttons_id[idx] == unique_id){
1355                         if(remove){
1356                                 remove_ship_status_item(p,idx);
1357                                 p->s_info.num_last_buttons--;
1358                         }
1359                         return 1;
1360                 }
1361         }
1362         return 0;
1363 }
1364
1365 void remove_ship_status_item(net_player *p,int id)
1366 {
1367         int idx;
1368         for(idx=id;idx<BUTTON_INFO_SAVE_COUNT-1;idx++){
1369                 p->s_info.last_buttons[idx] = p->s_info.last_buttons[idx+1];
1370                 p->s_info.last_buttons_id[idx] = p->s_info.last_buttons_id[idx+1];
1371                 p->s_info.last_buttons_time[idx] = p->s_info.last_buttons_time[idx+1];
1372         }
1373 }
1374
1375 // 
1376 void add_net_button_info(net_player *p,button_info *bi,int unique_id)
1377 {
1378    int lookup,idx;
1379         fix earliest;
1380
1381         // if the list is full, put it in the oldest slot since it's probably a lost packet anyway
1382    if(p->s_info.num_last_buttons < BUTTON_INFO_SAVE_COUNT-1){
1383                 p->s_info.last_buttons[p->s_info.num_last_buttons] = *bi;
1384                 p->s_info.last_buttons_id[p->s_info.num_last_buttons] = unique_id;
1385                 p->s_info.last_buttons_time[p->s_info.num_last_buttons] = timer_get_fixed_seconds();
1386                 p->s_info.num_last_buttons++;
1387         } else {
1388                 earliest = 0;
1389       lookup = -1;
1390                 for(idx=0;idx<BUTTON_INFO_SAVE_COUNT;idx++){
1391                         if((p->s_info.last_buttons_time[idx] < earliest) || (earliest == 0)){
1392                                 earliest = p->s_info.last_buttons_time[idx];
1393                                 lookup = idx;
1394                         }
1395                 }
1396                 if(lookup != -1){
1397                         p->s_info.last_buttons[lookup] = *bi;
1398                         p->s_info.last_buttons_id[lookup] = unique_id;
1399                         p->s_info.last_buttons_time[lookup] = timer_get_fixed_seconds();
1400                 }
1401         }               
1402 }
1403
1404 extern int button_function_critical(int n,net_player *p = NULL);
1405 void multi_apply_ship_status(net_player *p,button_info *bi,int locally)
1406 {
1407         int i, j;
1408         Multi_button_info_ok=1;
1409         for ( i = 0; i < NUM_BUTTON_FIELDS; i++ ) {
1410                 if ( bi->status[i] == 0 )
1411                         continue;
1412                 // at least one bit is set in the status integer
1413                 for ( j = 0; j < 32; j++ ) {
1414
1415                         // check if the bit is set. If button_function returns 1 (implying the action was taken), then unset the bit
1416                         if ( bi->status[i] & (1<<j) ) {
1417             if(locally){
1418                                         if(button_function_critical(32*i + j,NULL))   // will apply to this console
1419                                                 bi->status[i] &= ~(1<<j);
1420                                 } else {
1421                                         if(button_function_critical(32*i + j,p))      // will only apply to a net-player
1422                                                 bi->status[i] &= ~(1<<j);
1423                                 }
1424                         }
1425                 }
1426         }
1427         Multi_button_info_ok=0;
1428 }
1429
1430 // send 10x a second MAX
1431 #define MULTI_SHIP_STATUS_TIME                  350
1432 int Multi_ship_status_stamp = -1;
1433 button_info Multi_ship_status_bi;
1434
1435 void multi_maybe_send_ship_status()
1436 {
1437         int idx;
1438         button_info *bi = &Player->bi;
1439
1440         // strip out noncritical button presses
1441         button_strip_noncritical_keys(bi);
1442
1443         // xor all fields into the accum button info
1444         for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){               
1445                 Multi_ship_status_bi.status[idx] |= bi->status[idx];            
1446         }
1447
1448         // check timestamp
1449         if((Multi_ship_status_stamp < 0) || timestamp_elapsed_safe(Multi_ship_status_stamp, MULTI_SHIP_STATUS_TIME*2)){
1450                 int should_send = 0;
1451                 for(idx=0; idx<NUM_BUTTON_FIELDS; idx++){                       
1452                         // we have at least something to send
1453                         if(Multi_ship_status_bi.status[idx] != 0){
1454                                 should_send = 1;                        
1455                         }               
1456                 }
1457
1458                 // do we have something to send
1459                 if(should_send){
1460                         // add_net_button_info(Net_player, &Multi_ship_status_bi, Multi_button_info_id);
1461                         send_ship_status_packet(Net_player, &Multi_ship_status_bi, Multi_button_info_id++);
1462                 }
1463
1464                 // zero it out
1465                 memset(&Multi_ship_status_bi, 0, sizeof(button_info));
1466
1467                 // reset timestamp
1468                 Multi_ship_status_stamp = timestamp(MULTI_SHIP_STATUS_TIME);
1469         }
1470 }
1471
1472 void multi_subsys_update_all()
1473 {
1474         /*
1475         int idx;
1476         SDL_assert(Net_player->flags & NETINFO_FLAG_AM_MASTER);
1477         for(idx=0;idx<MAX_PLAYERS;idx++){
1478                 if((Net_players[idx].flags & NETINFO_FLAG_CONNECTED) && !psnet_same(&My_addr,&Net_players[idx].addr) && !(Net_players[idx].flags & NETINFO_FLAG_OBSERVER))
1479                         send_subsys_update_packet(&Net_players[idx]);
1480         }
1481         */
1482 }
1483
1484 int multi_find_player_by_callsign(const char *callsign)
1485 {
1486         int idx;
1487         for(idx=0;idx<MAX_PLAYERS;idx++){
1488                 if(MULTI_CONNECTED(Net_players[idx]) && (strcmp(callsign,Net_players[idx].player->callsign)==0)){
1489                         return idx;
1490                 }
1491         }
1492
1493         return -1;
1494 }
1495
1496 // if Game_current_mission_filename is a builtin multiplayer mission
1497 int multi_is_builtin_mission()
1498 {
1499         // int idx;
1500         char name[512];
1501
1502         // get the full filename
1503         memset(name,0,512);
1504         SDL_strlcpy(name, Game_current_mission_filename, sizeof(name));
1505         cf_add_ext(name, FS_MISSION_FILE_EXT);
1506
1507         // if this mission is builtin   
1508         if(game_find_builtin_mission(name) != NULL){
1509                 return 1;
1510         }
1511
1512         // not builtin
1513         return 0;
1514 }
1515
1516 // verify that the player has a valid mission file and do 1 of 3 things
1517 void server_verify_filesig(short player_id, ushort sum_sig, int length_sig)
1518 {       
1519 #if defined(MULTIPLAYER_BETA_BUILD) || defined(FS2_DEMO)
1520         net_player *pl;
1521    int player;
1522
1523         player = find_player_id(player_id);
1524         SDL_assert(player >= 0);
1525         if(player < 0){
1526                 return;
1527         }
1528         pl = &Net_players[player];
1529
1530         // all missions should be builtin, so if we don't have a match, kick the player
1531         if((sum_sig != Multi_current_file_checksum) || (length_sig != Multi_current_file_length)){
1532                 multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
1533         } else {
1534                 pl->flags |= NETINFO_FLAG_MISSION_OK;
1535         }
1536 #else
1537         net_player *pl;
1538    int player;
1539         int ok; 
1540         int is_builtin;
1541    
1542         player = find_player_id(player_id);
1543         SDL_assert(player >= 0);
1544         if(player < 0){
1545                 return;
1546         }
1547         pl = &Net_players[player];
1548
1549         // if the current mission is a builtin mission, check stuff out
1550         is_builtin = multi_is_builtin_mission();
1551                 
1552         if(is_builtin){
1553                 // if the player doesn't have it, kick him
1554                 if((sum_sig == 0xffff) && (length_sig == -1)){
1555                         multi_kick_player(player, 0, KICK_REASON_CANT_XFER);
1556                 } else {
1557                         pl->flags |= NETINFO_FLAG_MISSION_OK;
1558                 }
1559
1560                 // done
1561                 return;
1562         }
1563
1564         if( (length_sig != Multi_current_file_length) || (sum_sig != Multi_current_file_checksum)){
1565                 ok = 0;
1566         } else {
1567                 ok = 1; 
1568         }
1569
1570    // in an ingame join situation
1571         if(pl->flags & NETINFO_FLAG_INGAME_JOIN){               
1572                 if(!ok){
1573                         // if the netgame settings allow in-mission file xfers
1574                         if(Netgame.options.flags & MSO_FLAG_INGAME_XFER){
1575                                 pl->s_info.ingame_join_flags |= INGAME_JOIN_FLAG_FILE_XFER;
1576                                 pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
1577                         }
1578                         // otherwise send him a nak and tell him to get the hell away 
1579                         else {
1580                                 send_ingame_nak(ACK_FILE_ACCEPTED,pl);
1581                         }
1582                 } else {
1583                         pl->flags |= NETINFO_FLAG_MISSION_OK;
1584                 }
1585         }
1586         // in a normal join situation
1587         else {
1588                 // if the file does not check out, send it to him
1589                 if(!ok){                        
1590                         pl->s_info.xfer_handle = multi_xfer_send_file(pl->reliable_socket, Netgame.mission_name, CF_TYPE_MISSIONS);
1591                 }
1592                 // otherwise mark him as having a valid mission
1593                 else {
1594                         pl->flags |= NETINFO_FLAG_MISSION_OK;                   
1595                 }
1596         }
1597 #endif
1598 }
1599
1600 // check to see if every client has NETINFO_FLAG_MISSION_OK
1601 int server_all_filesigs_ok()
1602 {
1603         int idx;
1604         int ok = 1;
1605         
1606         for(idx=0;idx<MAX_PLAYERS;idx++){
1607                 if(MULTI_CONNECTED(Net_players[idx]) && !(Net_players[idx].flags & NETINFO_FLAG_MISSION_OK)){
1608                         ok = 0;
1609                         break;
1610                 }
1611         }
1612
1613         return ok;
1614 }
1615
1616 void multi_untag_player_ships()
1617 {
1618         ship_obj *moveup;
1619
1620         moveup = GET_FIRST(&Ship_obj_list);
1621         while(moveup != END_OF_LIST(&Ship_obj_list)){
1622                 if(Objects[moveup->objnum].flags & OF_PLAYER_SHIP){
1623                         Objects[moveup->objnum].flags &= ~(OF_PLAYER_SHIP);
1624                         obj_set_flags( &Objects[moveup->objnum], Objects[moveup->objnum].flags | OF_COULD_BE_PLAYER );
1625                 }
1626                 moveup = GET_NEXT(moveup);
1627         }
1628 }
1629
1630 // broadcast alltime stats to everyone in the game
1631 void multi_broadcast_stats(int stats_code)
1632 {
1633         int idx;
1634
1635         // broadcast everyone's stats to everyone else
1636         for(idx=0;idx<MAX_PLAYERS;idx++){
1637                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){                 
1638                         send_player_stats_block_packet(&Net_players[idx], stats_code);
1639                 }
1640         }                       
1641 }
1642
1643 // check to see if all players other than the local player are in a given NETPLAYER_ state
1644 // this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
1645 int multi_netplayer_state_check(int state,int ignore_standalone)
1646 {
1647         int idx;        
1648         for(idx=0;idx<MAX_PLAYERS;idx++){
1649                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1650                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1651                                 continue;
1652                         }
1653
1654                         if(Net_players[idx].state != state){
1655                                 return 0;
1656                         }
1657                 }
1658         }
1659         return 1;
1660 }
1661
1662 int multi_netplayer_state_check2(int state, int state2, int ignore_standalone)
1663 {
1664         int idx;        
1665         for(idx=0;idx<MAX_PLAYERS;idx++){
1666                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1667                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1668                                 continue;
1669                         }
1670
1671                         if((Net_players[idx].state != state) && (Net_players[idx].state != state2)){
1672                                 return 0;
1673                         }
1674                 }
1675         }
1676         return 1;
1677 }
1678
1679 int multi_netplayer_state_check3(int state, int state2, int state3, int ignore_standalone)
1680 {
1681         int idx;        
1682         for(idx=0;idx<MAX_PLAYERS;idx++){
1683                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1684                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1685                                 continue;
1686                         }
1687
1688                         if((Net_players[idx].state != state) && (Net_players[idx].state != state2) && (Net_players[idx].state != state3)){
1689                                 return 0;
1690                         }
1691                 }
1692         }
1693         return 1;
1694 }
1695
1696 // check to see if all players other than the local player are in a given NETPLAYER_ state
1697 // this is _EXTREMELY_ useful when doing network sequencing with the reliable sockets
1698 int multi_netplayer_flag_check(int flags,int ignore_standalone)
1699 {
1700         int idx;        
1701         for(idx=0;idx<MAX_PLAYERS;idx++){
1702                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player->player_id != Net_players[idx].player_id)){
1703                         if(ignore_standalone && ((Net_players[idx].flags & NETINFO_FLAG_AM_MASTER) && !(Net_players[idx].flags & NETINFO_FLAG_GAME_HOST)) ){
1704                                 continue;
1705                         }
1706
1707                         if(!(Net_players[idx].flags & flags)){
1708                                 return 0;
1709                         }
1710                 }
1711         }
1712         return 1;
1713 }
1714
1715 // function which gets called from psnet_* code to evaluate an error received on a reliable
1716 // socket.  In general, we only want to do drastic measures if the error indicates that the client
1717 // is no longer there.
1718 void multi_eval_socket_error(PSNET_SOCKET sock, int error)
1719 {
1720         if ( error == WSAENOTSOCK ){
1721                 nprintf(("Network","Socket connection terminated and/or nonexistent, bailing..\n"));
1722
1723                 // mwa -- don't go back to main menu.  You don't want host to do this.  Maybe we can ignore it
1724                 // because of a leaving player.
1725                 return;
1726                 //gameseq_post_event(GS_EVENT_MAIN_MENU);
1727                 // Int3();                                                      // get allender -- something happened to socket connection!!!
1728         }
1729
1730         if ( (error != WSAECONNRESET) && (error != WSAECONNABORTED) && (error != WSAESHUTDOWN) ) {
1731                 nprintf(("Network", "Error %d received on reliable socket -- ignoring\n", error));
1732                 return;
1733         }
1734
1735         if(error == WSAESHUTDOWN){
1736                 nprintf(("Network","Received WSAESHUTDOWN on client socket. Cool.\n"));
1737         }
1738
1739         // mwa -- always return for now because debugging with the stuff below is a real pain.
1740         // in essence, you can't do it!
1741         //return;
1742
1743         if( Net_player->flags & NETINFO_FLAG_AM_MASTER ) {
1744                 int idx;
1745
1746                 nprintf(("Network", "pitching player because drop on reliable socket\n"));
1747                 // find the netplayer whose socket we have an error on.  Dump the player when we find him.
1748                 // NOTE : make sure not to ban him
1749                 for(idx=0;idx<MAX_PLAYERS;idx++){
1750                         if(Net_players[idx].reliable_socket == sock){
1751                                 delete_player(idx);
1752                                 return;
1753                         }
1754                 }
1755         } else {
1756                 nprintf(("Network", "Communications to server lost -- quitting game\n"));
1757                 multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_CONTACT_LOST);
1758         }
1759 }
1760
1761 // send a repair info packet with code == code to a player if his object is the one being acted upon
1762 // dest_objp is the player object (or possible player object).  source_objp is the object pointer
1763 // of the repair ship that is the source of the action.  code means what is happening -- queueing up
1764 // for repair, getting repaired, aborted, complete, etc. 
1765 void multi_maybe_send_repair_info(object *dest_objp, object *source_objp, int code )
1766 {
1767         // only send information on player objects
1768         if ( !MULTIPLAYER_MASTER )
1769                 return;
1770         
1771         SDL_assert( dest_objp->type == OBJ_SHIP );
1772         SDL_assert( dest_objp != source_objp );
1773
1774         send_repair_info_packet( dest_objp, source_objp, code );
1775 }
1776
1777 int multi_is_valid_unknown_packet(ubyte type){
1778         return (type == GAME_QUERY) || (type == JOIN) || (type == PING) || (type == PONG) || (type == GAME_INFO)
1779                 || (type == ACCEPT) || (type == GAME_ACTIVE) || (type == INGAME_NAK) || (type == DENY)
1780                 || (type == UPDATE_DESCRIPT) || (type == ACCEPT_PLAYER_DATA) ? 1 : 0;   
1781 }
1782
1783 void multi_create_standalone_object()
1784 {
1785         // now create a bullshit ship for the standalone
1786         matrix m = IDENTITY_MATRIX;
1787         vector v;
1788         int objnum, pobj_num;
1789
1790         vm_vec_zero(&v);
1791         objnum = observer_create(&m,&v);
1792         Player_obj = &Objects[objnum];
1793         obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
1794         //obj_set_flags(Player_obj, Player_obj->flags | OF_SHOULD_BE_DEAD);
1795         obj_set_flags(Player_obj, Player_obj->flags & (~OF_PLAYER_SHIP));
1796         Net_player->player->objnum = objnum;
1797
1798         // create the default player ship object and use that as my default virtual "ship", and make it "invisible"
1799         pobj_num = parse_create_object(&Player_start_pobject);
1800         SDL_assert(pobj_num != -1);
1801         obj_set_flags(&Objects[pobj_num],OF_PLAYER_SHIP);
1802         Objects[pobj_num].net_signature = STANDALONE_SHIP_SIG;
1803         Player_ship = &Ships[Objects[pobj_num].instance];
1804
1805         // make ship hidden from sensors so that this observer cannot target it.  Observers really have two ships
1806         // one observer, and one "Player_ship".  Observer needs to ignore the Player_ship.
1807         Player_ship->flags |= SF_HIDDEN_FROM_SENSORS;
1808         SDL_strlcpy(Player_ship->ship_name, XSTR("Standalone Ship",904), sizeof(Player_ship->ship_name));
1809         Player_ai = &Ai_info[Ships[Objects[pobj_num].instance].ai_index];               
1810
1811 }
1812
1813 int multi_message_should_broadcast(int type)
1814 {
1815         return (type == MESSAGE_ARRIVE_ENEMY) || (type == MESSAGE_BETA_ARRIVED) || 
1816                     (type == MESSAGE_GAMMA_ARRIVED) || (type == MESSAGE_HELP) || (type == MESSAGE_REINFORCEMENTS) ? 1 : 0;
1817 }
1818
1819 // active game list handling functions
1820 active_game *multi_new_active_game( void )
1821 {
1822         active_game *new_game;
1823
1824         new_game = (active_game *)malloc(sizeof(active_game));
1825         if ( new_game == NULL ) {
1826                 nprintf(("Network", "Cannot allocate space for new active game structure\n"));
1827                 return NULL;
1828         }       
1829
1830         if ( Active_game_head != NULL ) {
1831                 new_game->next = Active_game_head->next;
1832                 new_game->next->prev = new_game;
1833                 Active_game_head->next = new_game;
1834                 new_game->prev = Active_game_head;
1835         } else {
1836                 Active_game_head = new_game;
1837                 Active_game_head->next = Active_game_head->prev = Active_game_head;
1838         }
1839
1840         Active_game_count++;
1841
1842         // notify the join game screen of this new item
1843         multi_join_notify_new_game();
1844                 
1845         return new_game;
1846 }
1847
1848 active_game *multi_update_active_games(active_game *ag)
1849 {
1850         active_game *gp = NULL;
1851         active_game *stop = NULL;               
1852
1853         // see if we have a game from this address already -- if not, create one.  In either case, get a pointer
1854         // to an active_game structure
1855         if ( Active_game_head != NULL ) {       // no games on list at all
1856                 int on_list;
1857
1858                 gp = Active_game_head;
1859                 stop = Active_game_head;
1860
1861                 on_list = 0;
1862                 do {
1863                         if ( psnet_same(&gp->server_addr, &ag->server_addr) /*&& (gp->game.security == game->security)*/ ) {
1864                                 on_list = 1;
1865                                 break;
1866                         }
1867                         gp = gp->next;
1868                 } while (gp != stop);
1869
1870                 // insert in the list
1871                 if (!on_list){
1872                         gp = multi_new_active_game();
1873                         // gp->ping_time = -1.0f;                       
1874
1875                         // copy in the game information
1876                         memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr_t));
1877                         SDL_strlcpy(gp->name, ag->name, sizeof(gp->name));
1878                         SDL_strlcpy(gp->mission_name, ag->mission_name, sizeof(gp->mission_name));
1879                         SDL_strlcpy(gp->title, ag->title, sizeof(gp->title));
1880                         gp->num_players = ag->num_players;
1881                         gp->flags = ag->flags;
1882                         
1883                         // ping him
1884                         /*
1885                         gp->ping_start = timer_get_fixed_seconds();
1886                         gp->ping_end = -1;
1887                         send_ping(&gp->server_addr);                    
1888                         */
1889                         multi_ping_reset(&gp->ping);
1890                         multi_ping_send(&gp->server_addr,&gp->ping);
1891                 }
1892                 // otherwise update the netgame info we have for this guy
1893                 else {                          
1894                         memset(gp->name,0,MAX_GAMENAME_LEN+1);
1895                         SDL_strlcpy(gp->name, ag->name, sizeof(gp->name));
1896                         memset(gp->mission_name,0,NAME_LENGTH+1);
1897                         SDL_strlcpy(gp->mission_name, ag->mission_name, sizeof(gp->mission_name));
1898                         memset(gp->title,0,NAME_LENGTH+1);
1899                         SDL_strlcpy(gp->title, ag->title, sizeof(gp->title));
1900                         gp->num_players = ag->num_players;
1901                         gp->flags = ag->flags;                  
1902                 }
1903         } else {
1904                 gp = multi_new_active_game();
1905                 // gp->ping_time = -1.0f;               
1906
1907                 // copy in the game information 
1908                 memcpy(&gp->server_addr,&ag->server_addr,sizeof(net_addr_t));
1909                 SDL_strlcpy(gp->name, ag->name, sizeof(gp->name));
1910                 SDL_strlcpy(gp->mission_name, ag->mission_name, sizeof(gp->mission_name));
1911                 SDL_strlcpy(gp->title, ag->title, sizeof(gp->title));
1912                 gp->num_players = ag->num_players;
1913                 gp->flags = ag->flags;
1914                 
1915                 // ping him
1916                 // gp->ping_start = timer_get_fixed_seconds();
1917                 // gp->ping_end = -1;
1918                 // send_ping(&gp->server_addr);
1919                 multi_ping_reset(&gp->ping);
1920                 multi_ping_send(&gp->server_addr,&gp->ping);
1921         }               
1922
1923         // don't do anything if we don't have a game entry
1924         if(gp == NULL){
1925                 return NULL;
1926         }
1927         
1928         // update the last time we heard from him
1929         if((Multi_options_g.protocol == NET_TCP) && (Net_player->p_info.options.flags & MLO_FLAG_LOCAL_BROADCAST)){
1930                 gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT_LOCAL);
1931         } else {
1932                 gp->heard_from_timer = timestamp(MULTI_JOIN_SERVER_TIMEOUT);
1933         }
1934
1935         return gp;
1936 }
1937
1938 void multi_free_active_games()
1939 {
1940         active_game *moveup,*backup;    
1941
1942         moveup = Active_game_head;
1943         backup = NULL;
1944         if(moveup != NULL){
1945                 do {                    
1946                         backup = moveup;
1947                         moveup = moveup->next;
1948                         
1949                         free(backup);
1950                         backup = NULL;
1951                 } while(moveup != Active_game_head);
1952                 Active_game_head = NULL;
1953         }       
1954         Active_game_count = 0;
1955 }
1956
1957 server_item *multi_new_server_item( void )
1958 {
1959         server_item *new_game;
1960
1961         new_game = (server_item *)malloc(sizeof(server_item));
1962         if ( new_game == NULL ) {
1963                 nprintf(("Network", "Cannot allocate space for new server_item structure\n"));
1964                 return NULL;
1965         }
1966
1967         if ( Game_server_head != NULL ) {
1968                 new_game->next = Game_server_head->next;
1969                 new_game->next->prev = new_game;
1970                 Game_server_head->next = new_game;
1971                 new_game->prev = Game_server_head;
1972         } else {
1973                 Game_server_head = new_game;
1974                 Game_server_head->next = Game_server_head->prev = Game_server_head;
1975         }
1976                 
1977         return new_game;
1978 }
1979
1980 void multi_free_server_list()
1981 {
1982         server_item *moveup,*backup;    
1983
1984         moveup = Game_server_head;
1985         backup = NULL;
1986         if(moveup != NULL){
1987                 do {                    
1988                         backup = moveup;
1989                         moveup = moveup->next;
1990                         
1991                         free(backup);
1992                         backup = NULL;
1993                 } while(moveup != Game_server_head);
1994                 Game_server_head = NULL;
1995         }       
1996 }
1997
1998 int multi_num_players()
1999 {
2000         int idx,count;
2001
2002         // count the players who are actively connected
2003         count = 0;
2004         for(idx=0;idx<MAX_PLAYERS;idx++){
2005                 // count all connected players except the standalone server (if any)
2006                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx])){                 
2007                         count++;
2008                 }
2009         }
2010
2011         return count;
2012 }
2013
2014 int multi_num_observers()
2015 {
2016         int idx,count;
2017
2018         // count the players who are actively connected
2019         count = 0;
2020         for(idx=0;idx<MAX_PLAYERS;idx++){
2021                 // count all connected players except the standalone server (if any)
2022                 if(MULTI_CONNECTED(Net_players[idx]) && MULTI_PERM_OBSERVER(Net_players[idx])){
2023                         count++;
2024                 }
2025         }
2026
2027         return count;
2028
2029 }
2030
2031 int multi_num_connections()
2032 {
2033         int idx,count;
2034
2035         // count the players who are actively connected
2036         count = 0;
2037         for(idx=0;idx<MAX_PLAYERS;idx++){
2038                 // count all connected players except the standalone server (if any)
2039                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx])){
2040                         count++;
2041                 }
2042         }
2043
2044         return count;
2045 }
2046
2047 int multi_can_message(net_player *p)
2048 {
2049         int max_rank;
2050         ship *sp;
2051
2052         // if the player is an observer of any kind, he cannot message
2053         if(p->flags & NETINFO_FLAG_OBSERVER){
2054                 return 0;
2055         }
2056
2057         switch(Netgame.options.squad_set){
2058         // only those of the highest rank can message
2059         case MSO_SQUAD_RANK:
2060                 max_rank = multi_get_highest_rank();
2061                 if(p->player->stats.rank < max_rank){
2062                         return 0;
2063                 }
2064                 break;
2065
2066         // only wing/team leaders can message
2067         case MSO_SQUAD_LEADER:
2068                 // if the player has an invalid object #
2069                 if(p->player->objnum < 0){
2070                         return 0;
2071                 }
2072
2073                 // check to see if he's a wingleader
2074                 sp = &Ships[Objects[p->player->objnum].instance];               
2075                 if(SDL_strcasecmp(sp->ship_name,NOX("alpha 1")) && SDL_strcasecmp(sp->ship_name,NOX("beta 1")) && SDL_strcasecmp(sp->ship_name,NOX("gamma 1")) && SDL_strcasecmp(sp->ship_name,NOX("zeta 1")) ){
2076                         return 0;
2077                 }       
2078                 break;
2079
2080         // anyone can end message
2081         case MSO_SQUAD_ANY:
2082                 break;
2083
2084         // only the host can message
2085         case MSO_SQUAD_HOST:
2086                 if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
2087                         return 0;
2088                 }
2089                 break;
2090         }       
2091         
2092         return 1;
2093 }
2094
2095 int multi_can_end_mission(net_player *p)
2096 {
2097         int max_rank;
2098         ship *sp;       
2099
2100         // the host can _always_ unpause a game
2101         if(p->flags & NETINFO_FLAG_GAME_HOST){
2102                 return 1;
2103         }
2104
2105         switch(Netgame.options.endgame_set){
2106         // only those of the highest rank can end the mission
2107         case MSO_END_RANK:
2108                 max_rank = multi_get_highest_rank();
2109                 if(p->player->stats.rank < max_rank){
2110                         return 0;
2111                 }
2112                 break;
2113
2114         // only wing/team leaders can end the mission
2115         case MSO_END_LEADER:
2116                 // if the player has an invalid object #
2117                 if(p->player->objnum < 0){
2118                         return 0;
2119                 }
2120
2121                 // check to see if he's a wingleader
2122                 sp = &Ships[Objects[p->player->objnum].instance];
2123                 if(SDL_strcasecmp(sp->ship_name,NOX("alpha 1")) && SDL_strcasecmp(sp->ship_name,NOX("beta 1")) && SDL_strcasecmp(sp->ship_name,NOX("gamma 1")) && SDL_strcasecmp(sp->ship_name,NOX("zeta 1")) ){
2124                         return 0;
2125                 }       
2126                 break;
2127
2128         // anyone can end the mission
2129         case MSO_END_ANY:
2130                 break;
2131
2132         // only the host can end the mission
2133         case MSO_END_HOST:
2134                 if(!(p->flags & NETINFO_FLAG_GAME_HOST)){
2135                         return 0;
2136                 }
2137                 break;
2138         }       
2139         
2140         return 1;
2141 }
2142
2143 int multi_eval_join_request(join_request *jr,net_addr_t *addr)
2144 {       
2145         int team0_avail,team1_avail;
2146
2147         // if the server versions are incompatible
2148         if(jr->version < MULTI_FS_SERVER_COMPATIBLE_VERSION){
2149                 return JOIN_DENY_JR_BAD_VERSION;
2150         }
2151
2152         // check to make sure we are otherwise in a state to accept
2153         if(Netgame.game_state != NETGAME_STATE_FORMING){
2154                 return JOIN_DENY_JR_STATE;
2155         }
2156         
2157         // the standalone has some oddball situations which we must handle seperately
2158         if(Game_mode & GM_STANDALONE_SERVER){           
2159                 // if this is the first connection, he will be the host so we must always accept him
2160                 if(multi_num_players() == 0){
2161                         // check to see if this is a tracker game, and if so make sure this is a valid MT player        
2162                         // we probably eventually want to make sure he's not passing us a fake tracker id#
2163                         if (MULTI_IS_TRACKER_GAME) {
2164                                 if(jr->tracker_id < 0){
2165                                         return JOIN_DENY_JR_TRACKER_INVAL;
2166                                 }                       
2167                         }                       
2168
2169                         // if we're password protected          
2170                         if(std_is_host_passwd() && strcmp(jr->passwd, Multi_options_g.std_passwd)){
2171                                 return JOIN_DENY_JR_PASSWD;
2172                         }
2173                                 
2174                         // don't allow the host to join as an observer
2175                         if(jr->flags & JOIN_FLAG_AS_OBSERVER){
2176                                 return JOIN_DENY_JR_NOOBS;
2177                         } else {
2178                                 return -1;
2179                         }
2180                 }               
2181         }
2182
2183         // first off check to see if we're violating any of our max players/observers/connections boundaries    
2184                 // if we've already got the full 16 (MAX_PLAYERS) connections - yow
2185         if( (multi_num_connections() >= MULTI_MAX_CONNECTIONS) ||                       
2186                 // if we're full of observers and this guy wants to be an observer
2187                 ((multi_num_observers() >= MAX_OBSERVERS) && (jr->flags & JOIN_FLAG_AS_OBSERVER)) ||
2188                 // if we're up to MULTI_MAX_PLAYERS-1 and we're on the standalone
2189                 ((multi_num_players() >= (MULTI_MAX_PLAYERS - 1)) && (Game_mode & GM_STANDALONE_SERVER)) ||
2190                 // if we're up to MULTI_MAX_PLAYERS
2191                 (multi_num_players() >= MULTI_MAX_PLAYERS) ||
2192                 // if the max players for a standalone was set
2193                 ((Multi_options_g.std_max_players != -1) && (multi_num_players() >= Multi_options_g.std_max_players)) ){
2194
2195                 // we're full buddy - sorry
2196                 return JOIN_DENY_JR_FULL;
2197         }
2198         
2199         // check to see if this is a tracker game, and if so make sure this is a valid MT player        
2200         // we probably eventually want to make sure he's not passing us a fake tracker id#
2201         if (MULTI_IS_TRACKER_GAME) {
2202                 if(jr->tracker_id < 0){
2203                         return JOIN_DENY_JR_TRACKER_INVAL;
2204                 }                       
2205         }
2206
2207         // check to see if the player is trying to ingame join in a closed game
2208         if(MULTI_IN_MISSION && (Netgame.mode == NG_MODE_CLOSED)){
2209                 return JOIN_DENY_JR_CLOSED;
2210         }       
2211
2212         // check to see if the player has passed a valid password in a password protected game
2213         if((Netgame.mode == NG_MODE_PASSWORD) && strcmp(Netgame.passwd,jr->passwd)){
2214                 return JOIN_DENY_JR_PASSWD;
2215         }
2216
2217         // check to see if the netgame is forming and is temporarily marked as closed
2218         if((Netgame.game_state == NETGAME_STATE_FORMING) && (Netgame.flags & NG_FLAG_TEMP_CLOSED)){
2219                 return JOIN_DENY_JR_TEMP_CLOSED;
2220         }       
2221
2222         // check to make sure he meets the rank requirement
2223         if((Netgame.mode == NG_MODE_RANK_ABOVE) && (jr->player_rank < Netgame.rank_base)){
2224                 return JOIN_DENY_JR_RANK_LOW;
2225         }
2226
2227         // check to make sure he meets the rank requirement
2228         if((Netgame.mode == NG_MODE_RANK_BELOW) && (jr->player_rank > Netgame.rank_base)){
2229                 return JOIN_DENY_JR_RANK_HIGH;
2230         }       
2231
2232         // can't ingame join a non-dogfight game
2233         if((Netgame.game_state != NETGAME_STATE_FORMING) && !(Netgame.type_flags & NG_TYPE_DOGFIGHT)){
2234                 return JOIN_DENY_JR_TYPE;
2235         }       
2236
2237         // if the player was banned by the standalone
2238         if((Game_mode & GM_STANDALONE_SERVER) && std_player_is_banned(jr->callsign)){
2239                 return JOIN_DENY_JR_BANNED;
2240         }
2241
2242         // if the game is in-mission, make sure there are ships available
2243         if(MULTI_IN_MISSION && !(jr->flags & JOIN_FLAG_AS_OBSERVER)){
2244                 team0_avail = 0;
2245                 team1_avail = 0;
2246                 multi_player_ships_available(&team0_avail,&team1_avail);
2247
2248                 // if there are no ships available on either team
2249                 if((team0_avail == 0) && (team1_avail == 0)){
2250                         return JOIN_DENY_JR_FULL;
2251                 }
2252         }
2253
2254         // if my ingame joining flag is set, then deny since we only allow one ingame joiner at a time
2255         if ( Netgame.flags & NG_FLAG_INGAME_JOINING ){
2256                 return JOIN_DENY_JR_INGAME_JOIN;
2257         }
2258
2259         // check to make sure the game is not full (of observers, or players, as appropriate)
2260         if((jr->flags & JOIN_FLAG_AS_OBSERVER)){
2261                 if((multi_num_observers() + 1) > Netgame.options.max_observers){
2262                         return JOIN_DENY_JR_FULL;
2263                 }
2264         } 
2265
2266         // if the netgame is restricted or is team vs. team
2267         if((Netgame.mode == NG_MODE_RESTRICTED) || (Netgame.type_flags & NG_TYPE_TEAM)){
2268                 // ingame, we must query the host to see if this guy is accepted
2269                 if(MULTI_IN_MISSION){
2270                         return JOIN_QUERY_RESTRICTED;
2271                 }               
2272         }               
2273         
2274         // check to make sure this player hasn't been kick/banned
2275         if(multi_kick_is_banned(addr)){
2276                 return JOIN_DENY_JR_BANNED;
2277         }
2278
2279         // check to make sure this player doesn't already exist
2280         if ( find_player(addr) >= 0 ) {
2281                 return JOIN_DENY_JR_DUP;
2282         }
2283
2284         return -1;
2285 }
2286
2287 // called by any machine (client, host, server, standalone, etc), to begin warping out all player objects
2288 void multi_warpout_all_players()
2289 {
2290         int idx;
2291
2292         // i'f i'm already marked as warping out, don't do this again
2293         if(Net_player->flags & NETINFO_FLAG_WARPING_OUT){
2294                 return;
2295         }
2296
2297         // stop my afterburners
2298         if((Player_obj != NULL) && (Player_obj->type == OBJ_SHIP) && !(Game_mode & GM_STANDALONE_SERVER)){
2299                 afterburners_stop( Player_obj, 1 );
2300         }
2301
2302         // traverse through each player
2303         for(idx=0;idx<MAX_PLAYERS;idx++) {
2304                 object *objp;
2305
2306                 // only warpout player _ships_ which are not mine
2307                 if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != &Net_players[idx]) && (Objects[Net_players[idx].player->objnum].type == OBJ_SHIP)){
2308
2309                         objp = &Objects[Net_players[idx].player->objnum];
2310
2311                         obj_set_flags( objp, objp->flags & (~OF_COLLIDES) );
2312                         shipfx_warpout_start( objp );
2313                 }
2314         }
2315
2316         // now, mark ourselves as needing to warp out
2317         Net_player->flags |= NETINFO_FLAG_WARPING_OUT;
2318         
2319         // if we're an observer, or we're respawning, or we can't warp out. so just jump into the debrief state
2320         if((Net_player->flags & NETINFO_FLAG_OBSERVER) || (Net_player->flags & NETINFO_FLAG_RESPAWNING) ||
2321                 (Net_player->flags & NETINFO_FLAG_OBSERVER) || ((Player_obj->type == OBJ_SHIP) && (Player_ship->flags & SF_CANNOT_WARP)) ){             
2322
2323                 if(Netgame.type_flags & NG_TYPE_DOGFIGHT){
2324                         gameseq_post_event(GS_EVENT_MULTI_DOGFIGHT_DEBRIEF);
2325                 } else {
2326                         gameseq_post_event(GS_EVENT_DEBRIEF);           
2327                 }
2328         }
2329         // if we're a ship, then begin the warpout process
2330         else {
2331                 // turn off collision detection for my ship
2332                 obj_set_flags(Player_obj, Player_obj->flags & (~OF_COLLIDES) );
2333                 gameseq_post_event(GS_EVENT_PLAYER_WARPOUT_START_FORCED);                               
2334         }
2335 }
2336
2337 // determine the highest rank of any of the players in the game
2338 int multi_get_highest_rank()
2339 {
2340         int idx;
2341         int max_rank = -1;
2342         
2343         // go through all the players
2344         for(idx=0;idx<MAX_PLAYERS;idx++){
2345                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_PERM_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.rank > max_rank)){
2346                         max_rank = Net_players[idx].player->stats.rank;
2347                 }
2348         }
2349
2350         // return what we found
2351         return max_rank;                        
2352 }
2353
2354 // called on the machine of the player who hit alt+j
2355 void multi_handle_end_mission_request()
2356 {
2357         int idx;
2358         
2359         // all clients should send the request to the server. no exceptions
2360         if(!(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
2361                 send_endgame_packet();
2362         }
2363         // the server of the game does some further processing
2364         else {
2365                 ml_string("Server received endgame request, proceeding...");                    
2366
2367                 // first we should toss all ingame joiners
2368                 for(idx=0;idx<MAX_PLAYERS;idx++){
2369                         if(MULTI_CONNECTED(Net_players[idx]) && (Net_players[idx].flags & NETINFO_FLAG_INGAME_JOIN)){
2370                                 multi_kick_player(idx,0,KICK_REASON_INGAME_ENDED);
2371                         }
2372                 }               
2373                                 
2374                 // send the endgame packet to all clients, who will act on it immediately
2375                 send_endgame_packet();                  
2376                 Netgame.game_state = NETGAME_STATE_ENDGAME;             
2377                 send_netgame_update_packet();                                   
2378                 
2379                 if(Game_mode & GM_STANDALONE_SERVER){                                   
2380                         // move to the standalone postgame (which is where we'll handle stats packets, etc)
2381                         gameseq_post_event(GS_EVENT_STANDALONE_POSTGAME);
2382                 }
2383
2384                 // begin the warpout process for all players and myself
2385                 multi_warpout_all_players();
2386         } 
2387 }
2388
2389 // called to handle any special cases where a player is in some submemu when the game is ended 
2390 void multi_handle_state_special()
2391 {
2392         int stack_depth,current_depth;  
2393         
2394         // first off - kill any active popups
2395         popup_kill_any_active();
2396
2397         // kill any popupdeads
2398         if(popupdead_is_active()){
2399                 popupdead_close();
2400         }
2401
2402         // kill off the pilot info popup if its active
2403         if(multi_pinfo_popup_active()){
2404                 multi_pinfo_popup_kill();
2405         }
2406
2407         // now do any special processing for being in states other then the gameplay states
2408         stack_depth = gameseq_get_depth();
2409         
2410         // if we're not pushed on top of any states, do any special state case handling here
2411         if(stack_depth == 0){           
2412                 // currently there are no special cases, so return
2413                 return;
2414         } 
2415         // if we are pushed on any states, post events to pop them off one by one
2416         else {
2417                 current_depth = stack_depth;
2418                 do {            
2419                         switch(gameseq_get_state(stack_depth - current_depth)){                         
2420                         // the hotkey screen
2421                         case GS_STATE_HOTKEY_SCREEN :           
2422                                 mission_hotkey_exit();
2423                                 Game_do_state_should_skip = 1;
2424                                 break;
2425                         // the options menu
2426                         case GS_STATE_OPTIONS_MENU:             
2427                                 options_cancel_exit();
2428                                 Game_do_state_should_skip = 1;
2429                                 break;
2430                         // the hud config (1 deeper in the options menu)
2431                         case GS_STATE_HUD_CONFIG:
2432                                 hud_config_cancel();                    
2433                                 Game_do_state_should_skip = 1;
2434                                 break;
2435                         // controls config (1 deeper than the options menu)
2436                         case GS_STATE_CONTROL_CONFIG:
2437                                 control_config_cancel_exit();   
2438                                 Game_do_state_should_skip = 1;
2439                                 break;
2440                         // mission goals screen
2441                         case GS_STATE_SHOW_GOALS:
2442                                 mission_goal_exit();
2443                                 Game_do_state_should_skip = 1;
2444                                 break;                  
2445                         // mission log scrollback
2446                         case GS_STATE_MISSION_LOG_SCROLLBACK:
2447                                 hud_scrollback_exit();
2448                                 Game_do_state_should_skip = 1;
2449                                 break;
2450                         // pause screen
2451                         case GS_STATE_MULTI_PAUSED:
2452                                 gameseq_pop_state();
2453                                 Game_do_state_should_skip = 1;
2454                                 break;
2455                         }
2456
2457                         // next pushed state
2458                         current_depth--;
2459                 } while(current_depth > 0);     
2460         }
2461 }
2462
2463 // called by the file xfer subsytem when we start receiving a file
2464 void multi_file_xfer_notify(int handle)
2465 {
2466         char *filename;
2467         int cf_type;
2468         int is_mission = 0;     
2469
2470         // get the filename of the file we are receiving
2471         filename = NULL;
2472         filename = multi_xfer_get_filename(handle);
2473
2474         // something is messed up
2475         if(filename == NULL){
2476                 return;
2477         }
2478
2479         // convert the filename to all lowercase
2480         SDL_strlwr(filename);
2481
2482         // if this is a mission file
2483         is_mission = (strstr(filename, FS_MISSION_FILE_EXT) != NULL);
2484         
2485         // determine where its going to go
2486         if(is_mission){
2487                 cf_type = Net_player->p_info.options.flags & MLO_FLAG_XFER_MULTIDATA ? CF_TYPE_MULTI_CACHE : CF_TYPE_MISSIONS;
2488         } else {
2489                 cf_type = CF_TYPE_MULTI_CACHE;
2490         }
2491
2492         // QUICK FIX
2493         // check to see if the file is read-only                        
2494         if((strlen(filename) > 0) && !cf_access(filename, cf_type, 00) && (cf_access(filename, cf_type, 02) == -1)){    
2495                 multi_xfer_xor_flags(handle, MULTI_XFER_FLAG_REJECT);
2496
2497                 Net_player->flags &= ~(NETINFO_FLAG_DO_NETWORKING);
2498                 popup(PF_USE_AFFIRMATIVE_ICON, 1, XSTR("&Ok", 713), XSTR("An outdated copy of this file exists, but it cannot be overwritten by the server because it is set to be read-only. Change the permissions on this file next time.", 714));           
2499                 multi_quit_game(PROMPT_NONE);           
2500                 return;
2501         }       
2502
2503         // if the incoming filename is a freespace file, set my netplayer state to be "file xfer"
2504         if(is_mission){
2505                 // we'd better not be xferring a file right now
2506                 SDL_assert(Net_player->s_info.xfer_handle == -1);
2507
2508                 // force into the multidata directory
2509                 multi_xfer_handle_force_dir(handle, cf_type);           
2510         
2511                 // set my xfer handle
2512                 Net_player->s_info.xfer_handle = handle;
2513                 
2514                 Net_player->state = NETPLAYER_STATE_MISSION_XFER;
2515                 send_netplayer_update_packet();
2516         }
2517         // otherwise always hand it off to the multi_data system
2518         else {
2519                 multi_data_handle_incoming(handle);             
2520         }
2521 }
2522
2523 // return the lag/disconnected status of the game
2524 #define MULTI_LAG_VAL           400
2525 int multi_query_lag_status()
2526 {
2527         // -1 == not lagged, 0 == lagged, 1 == disconnected
2528
2529         // if I'm the server of the game, I can't be lagged
2530         if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
2531                 return -1;
2532         }
2533         
2534         // if we've been disconnected for some reason or another
2535         if(multi_client_server_dead()){
2536                 return 1;
2537         }
2538
2539         // if our ping time to the server is over a certain time
2540         if(Netgame.server->s_info.ping.ping_avg >= MULTI_LAG_VAL){
2541                 return 0;
2542         } 
2543
2544         // not lagged
2545         return -1;
2546 }
2547
2548 // process a valid join request
2549 void multi_process_valid_join_request(join_request *jr, net_addr_t *who_from, int ingame_join_team)
2550 {
2551         int net_player_num,player_num;
2552         short id_num;
2553         
2554         // create netplayer and player objects for this guy
2555         net_player_num = multi_find_open_netplayer_slot();
2556         player_num = multi_find_open_player_slot();
2557         id_num = multi_get_new_id();
2558         SDL_assert((net_player_num != -1) && (player_num != -1));                       
2559
2560         // if he is requesting to join as an observer
2561         if(jr->flags & JOIN_FLAG_AS_OBSERVER){                  
2562                 // create the (permanently) observer player
2563                 if(!multi_obs_create_player(net_player_num, jr->callsign, who_from, &Players[player_num])){
2564                         Int3();
2565                 }
2566
2567                 // copy his pilot image filename
2568                 if(strlen(jr->image_filename) > 0){
2569                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, jr->image_filename, MAX_FILENAME_LEN);
2570                 } else {
2571                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, "", MAX_FILENAME_LEN);
2572                 }
2573
2574                 // copy his pilot squad filename
2575 #ifndef MAKE_FS1
2576                 Net_players[net_player_num].player->insignia_texture = -1;
2577                 player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);                
2578 #endif
2579
2580                 // clear his multi_data info
2581                 multi_data_handle_join(net_player_num);
2582
2583                 // set some extra flags for him as appropriate
2584                 if(MULTI_IN_MISSION){
2585                         Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;                  
2586                 }
2587
2588                 Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;            
2589                 Net_players[net_player_num].player_id = id_num;
2590                 Net_players[net_player_num].tracker_player_id = jr->tracker_id;
2591
2592                 // store pxo info
2593 #ifndef MAKE_FS1
2594                 if(strlen(jr->pxo_squad_name) > 0){
2595                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name, LOGIN_LEN);
2596                 } else {
2597                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, "", LOGIN_LEN);
2598                 }               
2599 #endif
2600
2601                 // if he's using hacked data
2602                 if(jr->flags & JOIN_FLAG_HAXOR){
2603                         Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
2604                 }
2605
2606                 // set his reliable connect time
2607                 Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
2608
2609                 // send the accept packet here
2610                 send_accept_packet(net_player_num, (Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN) ? ACCEPT_OBSERVER | ACCEPT_INGAME : ACCEPT_OBSERVER);
2611         } else {
2612                 // create the player object     
2613                 if(!multi_create_player( net_player_num, &Players[player_num], jr->callsign, who_from, -1, id_num )){
2614                         Int3();
2615                 }
2616                 
2617                 // copy his pilot image filename
2618                 if(strlen(jr->image_filename) > 0){
2619                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, jr->image_filename, MAX_FILENAME_LEN);
2620                 } else {
2621                         SDL_strlcpy(Net_players[net_player_num].player->image_filename, "", MAX_FILENAME_LEN);
2622                 }
2623
2624                 // copy his pilot squad filename                
2625 #ifndef MAKE_FS1
2626                 Net_players[net_player_num].player->insignia_texture = -1;
2627                 player_set_squad_bitmap(Net_players[net_player_num].player, jr->squad_filename);                                
2628 #endif
2629
2630                 // clear his multi_data info
2631                 multi_data_handle_join(net_player_num);
2632
2633                 // mark him as being connected
2634                 Net_players[net_player_num].flags |= NETINFO_FLAG_CONNECTED;
2635                                                 
2636                 // set his tracker id correctly
2637                 Net_players[net_player_num].tracker_player_id = jr->tracker_id;                         
2638
2639                 // set his player id#
2640                 Net_players[net_player_num].player_id = id_num;
2641
2642                 // store pxo info
2643 #ifndef MAKE_FS1
2644                 if(strlen(jr->pxo_squad_name) > 0){
2645                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, jr->pxo_squad_name, LOGIN_LEN);
2646                 } else {
2647                         SDL_strlcpy(Net_players[net_player_num].p_info.pxo_squad_name, "", LOGIN_LEN);
2648                 }               
2649 #endif
2650
2651                 // if he's using hacked data
2652                 if(jr->flags & JOIN_FLAG_HAXOR){
2653                         Net_players[net_player_num].flags |= NETINFO_FLAG_HAXOR;
2654                 }
2655                 
2656                 // flag him appropriately if he's doing an ingame join
2657                 if(MULTI_IN_MISSION){
2658                         Int3();
2659                         Net_players[net_player_num].flags |= NETINFO_FLAG_INGAME_JOIN;
2660                         Net_players[net_player_num].s_info.ingame_join_flags = 0;
2661                 }               
2662
2663                 // set his reliable connect time
2664                 Net_players[net_player_num].s_info.reliable_connect_time = time(NULL);
2665
2666                 // if he's joining as a host (on the standalone)
2667                 if(Net_players[net_player_num].flags & NETINFO_FLAG_GAME_HOST){
2668                         send_accept_packet(net_player_num, ACCEPT_HOST);
2669
2670                         Netgame.host = &Net_players[net_player_num];
2671
2672                         // set the game and player states appropriately
2673                         Netgame.game_state = NETGAME_STATE_STD_HOST_SETUP;                      
2674                 }
2675                 // if he's joining ingame
2676                 else if(Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN){
2677                         // if we're in team vs. team mode
2678                         if(Netgame.type_flags & NG_TYPE_TEAM){
2679                                 SDL_assert(ingame_join_team != -1);
2680
2681                                 Net_players[net_player_num].p_info.team = ingame_join_team;
2682                         }
2683
2684                         send_accept_packet(net_player_num, ACCEPT_INGAME, ingame_join_team);
2685
2686                         // set his last full update time for updating him on ingame join ships
2687                         Net_players[net_player_num].s_info.last_full_update_time = timestamp(INGAME_SHIP_UPDATE_TIME);
2688                 } 
2689                 // if he's joining as an otherwise ordinary client
2690                 else {
2691                         send_accept_packet(net_player_num, ACCEPT_CLIENT);
2692                 }
2693         }
2694
2695         // set my ingame joining flag if the new guy is joining ingame
2696         if ( Net_players[net_player_num].flags & NETINFO_FLAG_INGAME_JOIN ){
2697                 Int3();
2698                 Netgame.flags |= NG_FLAG_INGAME_JOINING;
2699         }       
2700         
2701         // copy in his options
2702         memcpy(&Net_players[net_player_num].p_info.options, &jr->player_options, sizeof(multi_local_options));
2703
2704         // if on the standalone, then do any necessary gui updating
2705         if(Game_mode & GM_STANDALONE_SERVER) {          
2706                 std_add_player(&Net_players[net_player_num]);
2707                 std_connect_set_connect_count();
2708                 std_connect_set_host_connect_status();
2709         } else {
2710                 // let the create game screen know someone has joined
2711                 if(gameseq_get_state() == GS_STATE_MULTI_HOST_SETUP){
2712                         multi_create_handle_join(&Net_players[net_player_num]);
2713                 }
2714         }
2715
2716         extern int Multi_client_update_times[MAX_PLAYERS];
2717         Multi_client_update_times[net_player_num] = -1;
2718
2719         // notify datarate
2720         multi_rate_reset(net_player_num);
2721 }
2722
2723 // if a player is trying to join a restricted game, evaluate the keypress (accept or not, etc)
2724 int multi_process_restricted_keys(int k)
2725 {       
2726         int key1=-1,key2=-1;    //JAS: Get rid of optimized warning
2727         int team_val;
2728         
2729         // if the query timestamp is not set, don't do anything
2730         if(Multi_restr_query_timestamp == -1){
2731                 return 0;
2732         }
2733
2734         // determine what keys to look for based upon the mode we're in
2735         switch(Multi_join_restr_mode){
2736         // normal restricted join, Y or N
2737         case MULTI_JOIN_RESTR_MODE_1:
2738                 key1 = SDLK_y;
2739                 key2 = SDLK_n;
2740                 break;
2741
2742         // team vs team, team 0 only has ships
2743         case MULTI_JOIN_RESTR_MODE_2:
2744                 key1 = SDLK_y;
2745                 key2 = SDLK_n;
2746                 break;
2747
2748         // team vs team, team 1 only has ships          
2749         case MULTI_JOIN_RESTR_MODE_3:
2750                 key1 = SDLK_y;
2751                 key2 = SDLK_n;
2752                 break;
2753
2754         // team vs team, both teams have ships
2755         case MULTI_JOIN_RESTR_MODE_4:
2756                 key1 = SDLK_1;
2757                 key2 = SDLK_2;
2758                 break;
2759         
2760         // illegal mode
2761         default :
2762                 Int3();
2763         }       
2764
2765         // check the keypress
2766         if((k == key1) || (k == key2)){
2767                 // unset the timestamp
2768                 Multi_restr_query_timestamp = -1;                       
2769
2770                 // MWA -- 5/26/98.  Next line commented out.  It should be cleared when the ingame joiner
2771                 // actually gets into the mission
2772                 //Netgame.flags &= ~(NG_FLAG_INGAME_JOINING);
2773
2774                 // determine which team to put him on (if any)
2775                 switch(Multi_join_restr_mode){
2776                 // normal restricted join, Y or N
2777                 case MULTI_JOIN_RESTR_MODE_1:
2778                         team_val = (k == key1) ? 0 : -1;
2779                         break;
2780
2781                 // team vs team, team 0 only has ships
2782                 case MULTI_JOIN_RESTR_MODE_2:
2783                         team_val = (k == key1) ? 0 : -1;                        
2784                         break;
2785
2786                 // team vs team, team 1 only has ships          
2787                 case MULTI_JOIN_RESTR_MODE_3:
2788                         team_val = (k == key1) ? 1 : -1;                        
2789                         break;
2790
2791                 // team vs team, both teams have ships
2792                 case MULTI_JOIN_RESTR_MODE_4:
2793                         team_val = (k == key1) ? 0 : 1;                 
2794                         break;
2795         
2796                 // illegal mode
2797                 default :
2798                         team_val = -1;  // JAS: Get rid of optimized warning
2799                         Int3();
2800                 }                               
2801
2802                 // perform the proper response  
2803                 if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
2804                         if(team_val >= 0){                      
2805                                 multi_process_valid_join_request(&Multi_restr_join_request,&Multi_restr_addr,team_val);                 
2806                         }
2807                 }
2808                 // otherwise tell the standalone to accept him
2809                 else {
2810                         if(team_val >= 0){
2811                                 send_host_restr_packet("null",1,team_val);
2812                         } else {
2813                                 send_host_restr_packet("null",2,-1);
2814                         }
2815                 }
2816
2817                 // processed a key
2818                 return 1;
2819         }
2820         
2821         // didn't process any keys
2822         return 0;
2823 }
2824
2825 // determine the status of available player ships (use team_0 for non team vs. team situations)
2826 void multi_player_ships_available(int *team_0,int *team_1)
2827 {
2828         ship_obj *moveup;
2829         int mp_team_num;
2830         
2831         *team_0 = 0;
2832         *team_1 = 0;
2833         
2834         moveup = GET_FIRST(&Ship_obj_list);
2835         while(moveup!=END_OF_LIST(&Ship_obj_list)){
2836                 // if this ship is flagged as OF_COULD_BE_PLAYER
2837                 if(Objects[moveup->objnum].flags & OF_COULD_BE_PLAYER){
2838                         // get the team # for this ship
2839                         mp_team_num = multi_ts_get_team(Ships[Objects[moveup->objnum].instance].ship_name);
2840                         if(mp_team_num == 0){
2841                                 (*team_0)++;
2842                         } else if(mp_team_num == 1){
2843                                 (*team_1)++;
2844                         }
2845                 }
2846                 
2847                 moveup = GET_NEXT(moveup);
2848         }       
2849 }
2850
2851 // server should update the player's bank/link status with the data in the passed ship
2852 void multi_server_update_player_weapons(net_player *pl,ship *shipp)
2853 {
2854         // don't process when the ship is dying.
2855         if ( (shipp->flags & SF_DYING) || NETPLAYER_IS_DEAD(pl) )
2856                 return;
2857
2858         // primary bank status
2859         pl->s_info.cur_primary_bank = (char)shipp->weapons.current_primary_bank;
2860
2861         // primary link status
2862         pl->s_info.cur_link_status &= ~(1<<0);
2863         if(shipp->flags & SF_PRIMARY_LINKED){
2864                 pl->s_info.cur_link_status |= (1<<0);
2865         }
2866
2867         // secondary bank status
2868         if ( shipp->weapons.current_secondary_bank < 0 ) {
2869                 nprintf(("Network", "bashing %s's current sbank to 0\n", shipp->ship_name));
2870                 shipp->weapons.current_secondary_bank = 0;
2871         }
2872         pl->s_info.cur_secondary_bank = (char)shipp->weapons.current_secondary_bank;
2873
2874         // secondary link status
2875         pl->s_info.cur_link_status &= ~(1<<1);
2876         if(shipp->flags & SF_SECONDARY_DUAL_FIRE){
2877                 pl->s_info.cur_link_status |= (1<<1);
2878         }
2879
2880         // ets values
2881         pl->s_info.ship_ets = 0x0000;
2882         // shield ets           
2883         pl->s_info.ship_ets |= ((ushort)shipp->shield_recharge_index << 8);
2884         // weapon ets
2885         pl->s_info.ship_ets |= ((ushort)shipp->weapon_recharge_index << 4);
2886         // engine ets
2887         pl->s_info.ship_ets |= ((ushort)shipp->engine_recharge_index);
2888
2889         SDL_assert( pl->s_info.ship_ets != 0 );
2890 }
2891
2892 // flush the multidata cache directory
2893 void multi_flush_multidata_cache()
2894 {
2895         nprintf(("Network","FLUSHING MULTIDATA CACHE\n"));
2896         
2897         // call the cfile function to flush the directory
2898         cfile_flush_dir(CF_TYPE_MULTI_CACHE);
2899 }
2900
2901 // flush all data from a previous mission before starting the next
2902 void multi_flush_mission_stuff()
2903 {
2904         int idx;
2905         
2906         for(idx=0;idx<MAX_PLAYERS;idx++){
2907                 if(MULTI_CONNECTED(Net_players[idx])){                  
2908                         // unset all unneeded status bits
2909                         Net_players[idx].flags &= ~(NETINFO_FLAG_MISSION_OK | NETINFO_FLAG_RESPAWNING | NETINFO_FLAG_WARPING_OUT);
2910                         
2911                         // server is always "mission ok"
2912                         if(Net_players[idx].flags & NETINFO_FLAG_AM_MASTER){
2913                                 Net_players[idx].flags |= NETINFO_FLAG_MISSION_OK;
2914                         }
2915
2916                         // if this guy is a non-permanent observer, unset the appropriate flags
2917                         if(MULTI_TEMP_OBSERVER(Net_players[idx])){
2918                                 Net_players[idx].flags &= ~(NETINFO_FLAG_OBSERVER | NETINFO_FLAG_OBS_PLAYER);
2919                         }
2920
2921                         // misc
2922                         multi_ping_reset(&Net_players[idx].s_info.ping);                                
2923                         Net_players[idx].s_info.num_last_buttons = 0;
2924                         Net_players[idx].s_info.wing_index_backup = 0;
2925                         Net_players[idx].s_info.wing_index = 0;
2926                         Net_players[idx].p_info.ship_class = -1;
2927                         Net_players[idx].p_info.ship_index = -1;
2928                         Net_players[idx].s_info.xfer_handle = -1;
2929
2930                         // ack handles
2931                         Net_players[idx].s_info.wing_index_backup = 0;
2932                                 
2933                         // objnum 
2934                         Players[idx].objnum = -1;
2935                 }
2936         }       
2937
2938         // reset netgame stuff
2939         Netgame.flags &= ~(NG_FLAG_TEMP_CLOSED);                
2940
2941         multi_xfer_reset();
2942
2943         // standalone servers should clear their goal trees now
2944         if(Game_mode & GM_STANDALONE_SERVER){
2945                 std_multi_setup_goal_tree();
2946         }
2947         
2948         // object signatures
2949         // this will eventually get reset to Netgame.security the next time an object gets its signature assigned.
2950         // We do this to resynchronize the host/server and all clients
2951         Next_ship_signature = SHIP_SIG_MIN;
2952         Next_asteroid_signature = ASTEROID_SIG_MIN;
2953         Next_non_perm_signature = NPERM_SIG_MIN;
2954
2955         // everyone will need to either reload the current mission, leave, or load the next mission, so in any case
2956         Multi_mission_loaded = 0;
2957 }
2958
2959 // should we ignore all controls and keypresses because of some multiplayer 
2960 int multi_ignore_controls(int key)
2961 {               
2962         // if the multiplayer text messaging system is active, don't return any keys    
2963         if((key > 0) && multi_msg_text_process(key)){
2964                 return 1;
2965         }
2966
2967         // if the host of the game is being prompted to accept or deny a player in a restricted game
2968         if((key > 0) && multi_process_restricted_keys(key)){
2969                 return 1;
2970         }
2971         
2972         // if we're in text messaging mode, ignore controls
2973         if(multi_msg_text_mode()){
2974                 return 1;
2975         }       
2976
2977         // if the pause system wants to eat keys for a while
2978         if(multi_pause_eat_keys()){
2979                 return 1;
2980         }
2981
2982         // multiplayer didn't eat the key
2983         return 0;
2984 }
2985
2986 // if the kill limit has been reached by any given player
2987 int multi_kill_limit_reached()
2988 {
2989         int idx;
2990
2991         // is the kill limit <= 0 ?
2992         // if so, consider it as _no_ kill limit
2993         if(Netgame.options.kill_limit <= 0){
2994                 return 0;
2995         }
2996         
2997         // look through all active, non-observer players
2998         for(idx=0;idx<MAX_PLAYERS;idx++){
2999                 if(MULTI_CONNECTED(Net_players[idx]) && !MULTI_STANDALONE(Net_players[idx]) && !MULTI_OBSERVER(Net_players[idx]) && (Net_players[idx].player->stats.m_kill_count_ok >= Netgame.options.kill_limit)){
3000                         // someone reached the limit
3001                         return 1;
3002                 }
3003         }
3004
3005         // limit has not been reached yet
3006         return 0;
3007 }
3008
3009 // display a chat message (write to the correct spot - hud, standalone gui, chatbox, etc)
3010 void multi_display_chat_msg(const char *msg, int player_index, int add_id)
3011 {
3012         // if i'm a standalone, always add to the gui
3013         if(Game_mode & GM_STANDALONE_SERVER){
3014                 std_add_chat_text(msg,player_index,add_id);
3015                 return;
3016         }
3017         
3018         // in gameplay
3019         if(Game_mode & GM_IN_MISSION){                                  
3020                 // if we're paused, send it to the chatbox
3021                 if(Multi_pause_status){
3022                         chatbox_add_line(msg, player_index, add_id);
3023                 }
3024                 // otherwise print to the HUD
3025                 else {
3026                         multi_msg_display_mission_text(msg, player_index);
3027                 }
3028         }
3029         // otherwise add it to the chatbox
3030         else {
3031                 chatbox_add_line(msg, player_index, add_id);
3032         }               
3033 }
3034
3035 // fill in Current_file_checksum and Current_file_length
3036 void multi_get_mission_checksum(const char *filename)
3037 {
3038         CFILE *in;
3039
3040         Multi_current_file_checksum = 0xffff;
3041         Multi_current_file_length = -1;
3042
3043         // get the filename
3044         in = cfopen(filename,"rb");
3045         if(in != NULL){
3046                 // get the length of the file
3047                 Multi_current_file_length = cfilelength(in);
3048                 cfclose(in);
3049
3050                 in = cfopen(filename,"rb");
3051                 if(in != NULL){
3052                         // get the checksum of the file
3053                         cf_chksum_short(in,&Multi_current_file_checksum);
3054
3055                         // close the file
3056                         cfclose(in);
3057                         in = NULL;
3058                 }
3059                 // if the file doesn't exist, setup some special values, so the server recognizes this
3060                 else {
3061                         Multi_current_file_checksum = 0xffff;
3062                         Multi_current_file_length = -1;
3063                 }
3064         } else {
3065                 // don't transfew builtin missions
3066                 if(multi_is_builtin_mission()){ 
3067                         multi_quit_game(PROMPT_ALL, MULTI_END_NOTIFY_KICKED_CANT_XFER);
3068                 }
3069         }
3070         nprintf(("Network","NET FILE CHECKSUM : %d %d\n",Multi_current_file_checksum,Multi_current_file_length));
3071 }
3072
3073 char multi_unit_to_char(float unit)
3074 {
3075         char ret;
3076         
3077         if(unit > 1.0f){
3078                 Int3();
3079                 unit = 1.0f;
3080         }
3081         if(unit < -1.0f){
3082                 Int3();
3083                 unit = -1.0f;
3084         }
3085
3086         ret = (char)(unit * 127.0f);
3087         return ret;
3088 }
3089
3090 float multi_char_to_unit(float val)
3091 {
3092         float ret;
3093
3094         ret = (float)val / 127.0f;
3095         if(ret > 1.0f){
3096                 Int3();
3097                 ret = 1.0f;
3098         }
3099         if(ret < -1.0f){
3100                 Int3();
3101                 ret = -1.0f;
3102         }
3103
3104         return ret;
3105 }
3106
3107 // if we should render our ping time to the server in a multiplayer game
3108 int multi_show_ingame_ping()
3109 {
3110         // always show it for now
3111         return 1;
3112 }
3113
3114 int multi_get_connection_speed()
3115 {
3116         int cspeed;
3117         const char *connection_speed;
3118
3119         // 'Fast' should be a safe default in 2015
3120         connection_speed = os_config_read_string("Network", "ConnectionSpeed", "Fast");
3121
3122         if ( !SDL_strcasecmp(connection_speed, NOX("Slow")) ) {
3123                 cspeed = CONNECTION_SPEED_288;
3124         } else if ( !SDL_strcasecmp(connection_speed, NOX("56K")) ) {
3125                 cspeed = CONNECTION_SPEED_56K;
3126         } else if ( !SDL_strcasecmp(connection_speed, NOX("ISDN")) ) {
3127                 cspeed = CONNECTION_SPEED_SISDN;
3128         } else if ( !SDL_strcasecmp(connection_speed, NOX("Cable")) ) {
3129                 cspeed = CONNECTION_SPEED_CABLE;
3130         } else if ( !SDL_strcasecmp(connection_speed, NOX("Fast")) ) {
3131                 cspeed = CONNECTION_SPEED_T1;
3132         } else {
3133                 cspeed = CONNECTION_SPEED_NONE;
3134         }
3135
3136         return cspeed;
3137 }
3138
3139 // return a MVALID_STATUS_* define based upon the passed string
3140 int multi_string_to_status(char *valid_string)
3141 {
3142         return MVALID_STATUS_UNKNOWN;   
3143 }
3144
3145 // if we're in tracker mode, do a validation update on all known missions
3146 void multi_update_valid_missions()
3147 {
3148         char next_filename[MAX_FILENAME_LEN+1]; 
3149         char next_line[512];
3150         char status_string[50];
3151         char temp[256];
3152         char *tok;
3153         CFILE *in;
3154         int idx, file_index;    
3155         int was_cancelled;
3156
3157         // if we're a standalone, show a dialog saying "validating missions"
3158         if(Game_mode & GM_STANDALONE_SERVER){
3159                 std_create_gen_dialog("Validating missions");
3160                 std_gen_set_text("Querying:",1);
3161         }
3162
3163         // mark all missions on our list as being MVALID_STATUS_UNKNOWN
3164         for(idx=0; idx<Multi_create_mission_count; idx++){
3165                 Multi_create_mission_list[idx].valid_status = MVALID_STATUS_UNKNOWN;
3166         }
3167         
3168         // attempt to open the valid mission config file
3169         in = cfopen(MULTI_VALID_MISSION_FILE, "rt", CFILE_NORMAL, CF_TYPE_DATA);
3170         if(in != NULL){         
3171                 // read in all listed missions
3172                 while(!cfeof(in)){
3173                         // read in a line
3174                         memset(next_line, 0, 512);
3175                         cfgets(next_line, 512, in);
3176                         drop_trailing_white_space(next_line);
3177                         drop_leading_white_space(next_line);
3178
3179                         // read in a filename
3180                         memset(next_filename, 0, MAX_FILENAME_LEN+1);
3181                         memset(temp, 0, 256);
3182                         tok = strtok(next_line, " ");
3183                         if(tok == NULL){
3184                                 continue;
3185                         }                       
3186                         SDL_strlcpy(temp, tok, sizeof(temp));
3187                         drop_trailing_white_space(temp);
3188                         drop_leading_white_space(temp);
3189                         SDL_strlcpy(next_filename, temp, sizeof(next_filename));
3190                         
3191                         // read in the status string
3192                         memset(status_string, 0, 50);
3193                         memset(temp, 0, 256);
3194                         tok = strtok(NULL," \n");
3195                         if(tok == NULL){
3196                                 continue;
3197                         }
3198                         SDL_strlcpy(temp, tok, sizeof(temp));
3199                         drop_trailing_white_space(temp);
3200                         drop_leading_white_space(temp);
3201                         SDL_strlcpy(status_string, temp, sizeof(status_string));
3202
3203                         // try and find the file
3204                         file_index = multi_create_lookup_mission(next_filename);
3205                         if(file_index >= 0){
3206                                 Multi_create_mission_list[file_index].valid_status = (char)multi_string_to_status(status_string);
3207                         }
3208                 }
3209
3210                 // close the infile
3211                 cfclose(in);
3212                 in = NULL;      
3213         }       
3214
3215         // now poll for all unknown missions
3216         was_cancelled = 0;
3217
3218         // if the operation was cancelled, don't write anything new
3219         if(was_cancelled){
3220                 // if we're a standalone, kill the validate dialog
3221                 if(Game_mode & GM_STANDALONE_SERVER){
3222                         std_destroy_gen_dialog();
3223                 }
3224
3225                 return;
3226         }
3227
3228         // now rewrite the outfile with the new mission info
3229         in = cfopen(MULTI_VALID_MISSION_FILE, "wt", CFILE_NORMAL, CF_TYPE_DATA);
3230         if(in == NULL){
3231                 // if we're a standalone, kill the validate dialog
3232                 if(Game_mode & GM_STANDALONE_SERVER){
3233                         std_destroy_gen_dialog();
3234                 }
3235
3236                 return;
3237         }
3238         for(idx=0; idx<Multi_create_mission_count; idx++){
3239                 switch(Multi_create_mission_list[idx].valid_status){
3240                 case MVALID_STATUS_VALID:
3241                         cfputs(Multi_create_mission_list[idx].filename, in);
3242                         cfputs(NOX("   valid"), in);
3243                         cfputs(NOX("\n"), in);
3244                         break;
3245
3246                 case MVALID_STATUS_INVALID:
3247                         cfputs(Multi_create_mission_list[idx].filename, in);
3248                         cfputs(NOX("   invalid"), in);
3249                         cfputs(NOX("\n"), in);
3250                         break;
3251                 }
3252         }
3253
3254         // close the outfile
3255         cfclose(in);
3256         in = NULL;
3257
3258         // if we're a standalone, kill the validate dialog
3259         if(Game_mode & GM_STANDALONE_SERVER){
3260                 std_destroy_gen_dialog();
3261         }
3262 }
3263
3264 // get a new id# for a player
3265 short multi_get_new_id()
3266 {
3267         if(Multi_id_num > 20000){
3268                 Multi_id_num = 0;
3269         } 
3270
3271         return Multi_id_num++;
3272 }
3273
3274
3275 // ------------------------------------
3276
3277 //XSTR:OFF
3278 DCF(multi,"changes multiplayer settings")
3279 {
3280         if(Dc_command){
3281                 dc_get_arg(ARG_STRING);
3282                 
3283                 if(strcmp(Dc_arg, "kick")==0){                          // kick a player
3284                         multi_dcf_kick();
3285 #ifndef NDEBUG
3286                 } else if(strcmp(Dc_arg, "stats")==0) {
3287                         // multi_toggle_stats();
3288                 } else if(strcmp(Dc_arg, "show_stats")==0) {
3289                         // multi_show_basic_stats(0);
3290                 } else if(strcmp(Dc_arg, "dump_stats")==0) {
3291                         // multi_show_basic_stats(1);
3292 #endif
3293                 } else if(strcmp(Dc_arg, "voice")==0){                          // settings for multiplayer voice
3294                         multi_voice_dcf();
3295                 } else if(strcmp(Dc_arg, "respawn_chump")==0){  // set a really large # of respawns
3296                         if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){                       
3297                                 Netgame.respawn = 9999;
3298                                 Netgame.options.respawn = 9999;                         
3299
3300                                 // if i'm the server, send a netgame update
3301                                 if(Net_player->flags & NETINFO_FLAG_AM_MASTER){
3302                                         send_netgame_update_packet();
3303                                 } 
3304                         }
3305                 } else if(strcmp(Dc_arg, "ss_leaders")==0){             // only host or team captains can modify ships
3306                         if((Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_GAME_HOST)){                       
3307                                 Netgame.options.flags |= MSO_FLAG_SS_LEADERS;
3308                                 multi_options_update_netgame();
3309                         }
3310                 } else if(strcmp(Dc_arg, "make_players")==0){
3311 #ifndef NDEBUG
3312                         multi_make_fake_players(MAX_PLAYERS);
3313 #endif
3314                 } else if(strcmp(Dc_arg, "givecd")==0){
3315                         extern int Multi_has_cd;
3316                         Multi_has_cd = 1;
3317                 /*
3318                 } else if(strcmp(Dc_arg, "oo")==0){
3319                         int new_flags = -1;
3320
3321                         dc_get_arg(ARG_INT);
3322                         if(Dc_arg_type & ARG_INT){
3323                                 new_flags = Dc_arg_int;
3324                         }
3325
3326                         dc_printf("Interesting flags\nPos : %d\nVelocity : %d\nDesired vel : %d\nOrient : %d\nRotvel : %d\nDesired rotvel %d\n",
3327                                                  1<<0, 1<<7, 1<<8, 1<<1, 1<<9, 1<<10);
3328                 */
3329                 } else if(strcmp(Dc_arg, "oo_sort")==0){                        
3330                         extern int OO_sort;
3331
3332                         OO_sort = !OO_sort;
3333                         if(OO_sort){
3334                                 dc_printf("Network object sorting ENABLED\n");
3335                         } else {
3336                                 dc_printf("Network object sorting DISABLED\n");
3337                         }
3338                 }
3339         }
3340 }
3341
3342 //XSTR:ON
3343
3344 // PXO crc checking stuff
3345 #ifndef NDEBUG
3346
3347 void multi_spew_pxo_checksums(int max_files, char *outfile)
3348 {
3349         char **file_names;
3350         char full_name[MAX_FILENAME_LEN+1];
3351         char wild_card[6];
3352         int count, idx;
3353         uint checksum;
3354         FILE *out;
3355
3356         // allocate filename space      
3357         file_names = (char**)malloc(sizeof(char*) * max_files);
3358         if(file_names != NULL){
3359                 SDL_snprintf(wild_card, sizeof(wild_card), "*%s", FS_MISSION_FILE_EXT);
3360                 count = cf_get_file_list(max_files, file_names, CF_TYPE_MISSIONS, wild_card);   
3361         
3362                 // open the outfile
3363                 out = fopen(outfile, "wt");
3364                 if(out == NULL){
3365                         return;
3366                 }
3367                 
3368                 // do all the checksums
3369                 for(idx=0; idx<count; idx++){
3370                         memset(full_name, 0, MAX_FILENAME_LEN+1);                       
3371                         SDL_strlcpy(full_name, cf_add_ext(file_names[idx], FS_MISSION_FILE_EXT), sizeof(full_name));
3372
3373                         if(cf_chksum_long(full_name, &checksum)){
3374                                 fprintf(out, "%s        :       %d\n", full_name, (int)checksum);
3375                         }
3376                 }
3377
3378                 fclose(out);
3379                 free(file_names);
3380         }
3381 }
3382
3383 DCF(pxospew,"spew PXO 32 bit checksums for all visible mission files")
3384 {
3385         int max_files;
3386
3387         dc_get_arg(ARG_INT);
3388         if(Dc_arg_type & ARG_INT){
3389                 max_files = Dc_arg_int; 
3390
3391                 dc_get_arg(ARG_STRING);
3392                 if(Dc_arg_type & ARG_STRING){
3393                         multi_spew_pxo_checksums(max_files, Dc_arg);
3394                 }
3395         }
3396 }
3397
3398 #endif
3399
3400 // make a bunch of fake players - don't rely on this to be very safe - its mostly used for interface testing
3401 #ifndef NDEBUG
3402 void multi_make_fake_players(int count)
3403 {
3404         int idx;
3405         
3406         for(idx=0;idx<count;idx++){
3407                 if(!MULTI_CONNECTED(Net_players[idx])){
3408                         Net_players[idx].player = &Players[idx];
3409                         SDL_snprintf(Net_players[idx].player->callsign, CALLSIGN_LEN, "Player %d", idx);
3410                         Net_players[idx].flags |= NETINFO_FLAG_CONNECTED;
3411                 }
3412         }
3413 }
3414 #endif
3415
3416 // ---------------------------------------------------------------------------------------------------------------------
3417 // PACK UNPACK STUFF
3418 //
3419
3420 #ifndef PLAT_UNIX
3421 #pragma optimize("", off)
3422 #endif
3423
3424 typedef struct bitbuffer {
3425         ubyte           mask;
3426    int          rack;
3427         ubyte           *data;
3428         ubyte           *org_data;
3429 } bitbuffer;
3430
3431 void bitbuffer_init( bitbuffer *bitbuf, ubyte *data )
3432 {
3433         bitbuf->rack = 0;       
3434         bitbuf->mask = 0x80;
3435         bitbuf->data = data;
3436         bitbuf->org_data = data;
3437 }
3438
3439 int bitbuffer_write_flush( bitbuffer *bitbuf )
3440 {
3441         // Flush to next byte
3442         if ( bitbuf->mask != 0x80 )     {
3443         *bitbuf->data++ = (ubyte)bitbuf->rack;
3444         }
3445         return bitbuf->data-bitbuf->org_data;
3446 }
3447
3448 int bitbuffer_read_flush( bitbuffer *bitbuf )
3449 {
3450         return bitbuf->data-bitbuf->org_data;
3451 }
3452
3453 void bitbuffer_put( bitbuffer *bitbuf, uint data, int bit_count ) 
3454 {
3455         uint mask;
3456
3457         mask = 1L << ( bit_count - 1 );
3458         while ( mask != 0) {
3459                 if ( mask & data )      {
3460                         bitbuf->rack |= bitbuf->mask;
3461                 }
3462                 bitbuf->mask >>= 1;
3463                 if ( bitbuf->mask == 0 ) {
3464                         *bitbuf->data++=(ubyte)bitbuf->rack;
3465                         bitbuf->rack = 0;
3466                         bitbuf->mask = 0x80;
3467                 }
3468                 mask >>= 1;
3469         }
3470 }
3471
3472 uint bitbuffer_get_unsigned( bitbuffer *bitbuf, int bit_count ) 
3473 {
3474         uint mask;
3475         uint return_value;
3476
3477         mask = 1L << ( bit_count - 1 );
3478         return_value = 0;
3479
3480         while ( mask != 0)      {
3481                 if ( bitbuf->mask == 0x80 ) {
3482                         bitbuf->rack = *bitbuf->data++;
3483                 }
3484                 if ( bitbuf->rack & bitbuf->mask )      {
3485                         return_value |= mask;
3486                 }
3487                 mask >>= 1;
3488                 bitbuf->mask >>= 1;
3489                 if ( bitbuf->mask == 0 )        {
3490                         bitbuf->mask = 0x80;
3491                 }
3492         }
3493
3494         return return_value;
3495 }
3496
3497 int bitbuffer_get_signed( bitbuffer *bitbuf, int bit_count ) 
3498 {
3499         uint mask;
3500         uint return_value;
3501
3502         mask = 1L << ( bit_count - 1 );
3503         return_value = 0;
3504
3505         while ( mask != 0)      {
3506                 if ( bitbuf->mask == 0x80 ) {
3507                         bitbuf->rack = *bitbuf->data++;
3508                 }
3509                 if ( bitbuf->rack & bitbuf->mask )      {
3510                         return_value |= mask;
3511                 }
3512                 mask >>= 1;
3513                 bitbuf->mask >>= 1;
3514                 if ( bitbuf->mask == 0 )        {
3515                         bitbuf->mask = 0x80;
3516                 }
3517         }
3518
3519         // sign extend return value
3520         return_value <<= (32-bit_count);
3521         
3522         return ((int)return_value)>>(32-bit_count);
3523 }
3524         
3525
3526
3527 // Packs/unpacks an object position.
3528 // Returns number of bytes read or written.
3529 // #define OO_POS_RET_SIZE                                                      9
3530 int multi_pack_unpack_position( int write, ubyte *data, vector *pos)
3531 {
3532         bitbuffer buf;
3533
3534         bitbuffer_init(&buf,data);
3535
3536         int a, b, c;
3537
3538         if ( write )    {
3539                 // Output pos
3540
3541                 a = fl2i(pos->xyz.x*105.0f+0.5f); 
3542                 b = fl2i(pos->xyz.y*105.0f+0.5f);
3543                 c = fl2i(pos->xyz.z*105.0f+0.5f);
3544                 CAP(a,-8388608,8388607);
3545                 CAP(b,-8388608,8388607);
3546                 CAP(c,-8388608,8388607);
3547                 
3548                 bitbuffer_put( &buf, (uint)a, 24 );
3549                 bitbuffer_put( &buf, (uint)b, 24 );
3550                 bitbuffer_put( &buf, (uint)c, 24 );
3551
3552
3553                 return bitbuffer_write_flush(&buf);
3554
3555         } else {
3556
3557                 // unpack pos
3558                 a = bitbuffer_get_signed(&buf,24);
3559                 b = bitbuffer_get_signed(&buf,24);
3560                 c = bitbuffer_get_signed(&buf,24);
3561
3562                 pos->xyz.x = i2fl(a)/105.0f;
3563                 pos->xyz.y = i2fl(b)/105.0f;
3564                 pos->xyz.z = i2fl(c)/105.0f;
3565
3566                 return bitbuffer_read_flush(&buf);
3567         }
3568 }
3569
3570 int degenerate_count = 0;
3571 int non_degenerate_count = 0;
3572
3573 /*
3574 hack = ((ushort)orient->v.fvec.xyz.x * 32767);
3575                         memcpy(&hack, &orient->v.fvec.xyz.x, 4);
3576                         bitbuffer_put( &buf, hack, 32  );
3577                         memcpy(&hack, &orient->v.fvec.xyz.y, 4);
3578                         bitbuffer_put( &buf, hack, 32  );
3579                         memcpy(&hack, &orient->v.fvec.xyz.z, 4);
3580                         bitbuffer_put( &buf, hack, 32  );
3581
3582                         memcpy(&hack, &orient->v.uvec.xyz.x, 4);
3583                         bitbuffer_put( &buf, hack, 32  );
3584                         memcpy(&hack, &orient->v.uvec.xyz.y, 4);
3585                         bitbuffer_put( &buf, hack, 32  );
3586                         memcpy(&hack, &orient->v.uvec.xyz.z, 4);
3587                         bitbuffer_put( &buf, hack, 32  );
3588
3589                         memcpy(&hack, &orient->v.rvec.xyz.x, 4);
3590                         bitbuffer_put( &buf, hack, 32  );
3591                         memcpy(&hack, &orient->v.rvec.xyz.y, 4);
3592                         bitbuffer_put( &buf, hack, 32  );
3593                         memcpy(&hack, &orient->v.rvec.xyz.z, 4);
3594                         bitbuffer_put( &buf, hack, 32  );*/
3595
3596 /*
3597 hack = bitbuffer_get_unsigned(&buf, 32);
3598                         memcpy(&orient->v.fvec.xyz.x, &hack, 4);
3599                         hack = bitbuffer_get_unsigned(&buf, 32);
3600                         memcpy(&orient->v.fvec.xyz.y, &hack, 4);
3601                         hack = bitbuffer_get_unsigned(&buf, 32);
3602                         memcpy(&orient->v.fvec.xyz.z, &hack, 4);
3603
3604                         hack = bitbuffer_get_unsigned(&buf, 32);
3605                         memcpy(&orient->v.uvec.xyz.x, &hack, 4);
3606                         hack = bitbuffer_get_unsigned(&buf, 32);
3607                         memcpy(&orient->v.uvec.xyz.y, &hack, 4);
3608                         hack = bitbuffer_get_unsigned(&buf, 32);
3609                         memcpy(&orient->v.uvec.xyz.z, &hack, 4);
3610
3611                         hack = bitbuffer_get_unsigned(&buf, 32);
3612                         memcpy(&orient->v.rvec.xyz.x, &hack, 4);
3613                         hack = bitbuffer_get_unsigned(&buf, 32);
3614                         memcpy(&orient->v.rvec.xyz.y, &hack, 4);
3615                         hack = bitbuffer_get_unsigned(&buf, 32);
3616                         memcpy(&orient->v.rvec.xyz.z, &hack, 4);*/
3617
3618 // Packs/unpacks an orientation matrix.
3619 // Returns number of bytes read or written.
3620 // #define OO_ORIENT_RET_SIZE                                           6
3621 int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
3622 {
3623         bitbuffer buf;
3624
3625         bitbuffer_init(&buf, data + 1);
3626
3627         vector rot_axis;        
3628         float theta;
3629         int a, b, c, d;
3630         angles ang;     
3631         ubyte flag = 0x00;      
3632
3633         #define D_SCALE 32768.0f
3634         #define D_MAX_RANGE 32767
3635         #define D_MIN_RANGE -32768
3636
3637         #define N_SCALE 2048.0f
3638         #define N_MAX_RANGE 2047
3639         #define N_MIN_RANGE -2048
3640
3641         if ( write )    {                       
3642                 // degenerate case - send the whole orient matrix
3643                 vm_extract_angles_matrix(&ang, orient); 
3644                 if((ang.h > 3.130) && (ang.h < 3.150)){
3645                         degenerate_count++;
3646
3647                         flag = 0xff;
3648                         
3649                         // stuff it     
3650                         a = fl2i(orient->v.fvec.xyz.x * D_SCALE);
3651                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3652                         bitbuffer_put( &buf, a, 16  );
3653                         a = fl2i(orient->v.fvec.xyz.y * D_SCALE);
3654                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3655                         bitbuffer_put( &buf, a, 16  );
3656                         a = fl2i(orient->v.fvec.xyz.z * D_SCALE);
3657                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3658                         bitbuffer_put( &buf, a, 16  );
3659
3660                         a = fl2i(orient->v.uvec.xyz.x * D_SCALE);
3661                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3662                         bitbuffer_put( &buf, a, 16  );
3663                         a = fl2i(orient->v.uvec.xyz.y * D_SCALE);
3664                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3665                         bitbuffer_put( &buf, a, 16  );
3666                         a = fl2i(orient->v.uvec.xyz.z * D_SCALE);
3667                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3668                         bitbuffer_put( &buf, a, 16  );
3669
3670                         a = fl2i(orient->v.rvec.xyz.x * D_SCALE);
3671                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3672                         bitbuffer_put( &buf, a, 16  );
3673                         a = fl2i(orient->v.rvec.xyz.y * D_SCALE);
3674                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3675                         bitbuffer_put( &buf, a, 16  );
3676                         a = fl2i(orient->v.rvec.xyz.z * D_SCALE);
3677                         CAP(a, D_MIN_RANGE, D_MAX_RANGE);                       
3678                         bitbuffer_put( &buf, a, 16  );
3679                 } else {
3680                         non_degenerate_count++;
3681                                 
3682                         vm_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);             
3683                         // Have theta, which is an angle between 0 and PI.
3684                         // Convert it to be between -1.0f and 1.0f
3685                         theta = theta*2.0f/PI-1.0f;                     
3686
3687                         // -1 to 1
3688                         a = fl2i(rot_axis.xyz.x*N_SCALE); 
3689                         b = fl2i(rot_axis.xyz.y*N_SCALE);
3690                         c = fl2i(rot_axis.xyz.z*N_SCALE);
3691                         d = fl2i(theta*N_SCALE);
3692
3693                         CAP(a, N_MIN_RANGE, N_MAX_RANGE);
3694                         CAP(b, N_MIN_RANGE, N_MAX_RANGE);
3695                         CAP(c, N_MIN_RANGE, N_MAX_RANGE);
3696                         CAP(d, N_MIN_RANGE, N_MAX_RANGE);
3697                                         
3698                         bitbuffer_put( &buf, (uint)a, 12 );
3699                         bitbuffer_put( &buf, (uint)b, 12 );
3700                         bitbuffer_put( &buf, (uint)c, 12 );
3701                         bitbuffer_put( &buf, (uint)d, 12 );
3702                 }
3703
3704                 // flag for degenerate case
3705                 data[0] = flag;
3706
3707                 return bitbuffer_write_flush(&buf) + 1;
3708         } else {
3709                 flag = data[0];
3710
3711                 // degenerate
3712                 if(flag){
3713                         a = bitbuffer_get_signed(&buf, 16);
3714                         orient->v.fvec.xyz.x = i2fl(a) / D_SCALE;                       
3715                         a = bitbuffer_get_signed(&buf, 16);
3716                         orient->v.fvec.xyz.y = i2fl(a) / D_SCALE;                       
3717                         a = bitbuffer_get_signed(&buf, 16);
3718                         orient->v.fvec.xyz.z = i2fl(a) / D_SCALE;                       
3719
3720                         a = bitbuffer_get_signed(&buf, 16);
3721                         orient->v.uvec.xyz.x = i2fl(a) / D_SCALE;                       
3722                         a = bitbuffer_get_signed(&buf, 16);
3723                         orient->v.uvec.xyz.y = i2fl(a) / D_SCALE;                       
3724                         a = bitbuffer_get_signed(&buf, 16);
3725                         orient->v.uvec.xyz.z = i2fl(a) / D_SCALE;                       
3726
3727                         a = bitbuffer_get_signed(&buf, 16);
3728                         orient->v.rvec.xyz.x = i2fl(a) / D_SCALE;                       
3729                         a = bitbuffer_get_signed(&buf, 16);
3730                         orient->v.rvec.xyz.y = i2fl(a) / D_SCALE;                       
3731                         a = bitbuffer_get_signed(&buf, 16);
3732                         orient->v.rvec.xyz.z = i2fl(a) / D_SCALE;                       
3733                 } else {
3734                         a = bitbuffer_get_signed(&buf,12);
3735                         b = bitbuffer_get_signed(&buf,12);
3736                         c = bitbuffer_get_signed(&buf,12);
3737                         d = bitbuffer_get_signed(&buf,12);
3738
3739                         // special case         
3740                         rot_axis.xyz.x = i2fl(a)/N_SCALE;
3741                         rot_axis.xyz.y = i2fl(b)/N_SCALE;
3742                         rot_axis.xyz.z = i2fl(c)/N_SCALE;
3743                         theta = i2fl(d)/N_SCALE;
3744                                 
3745                         // Convert theta back to range 0-PI
3746                         theta = (theta+1.0f)*PI/2.0f;
3747                                 
3748                         vm_quaternion_rotate(orient, theta, &rot_axis);         
3749
3750                         vm_orthogonalize_matrix(orient);                
3751                 }
3752
3753                 return bitbuffer_read_flush(&buf) + 1;
3754         }
3755 }
3756
3757
3758 // Packs/unpacks an orientation matrix.
3759 // Returns number of bytes read or written.
3760 // #define OO_ORIENT_RET_SIZE                                           6
3761 /*
3762 int multi_pack_unpack_orient( int write, ubyte *data, matrix *orient)
3763 {
3764         bitbuffer buf;
3765
3766         bitbuffer_init(&buf,data);
3767
3768         vector rot_axis;        
3769         float theta;
3770         int a, b, c, d;
3771
3772         if ( write )    {
3773
3774                 // if our heading is 3.14 radians
3775                 //angles ang;
3776                 //vm_extract_angles_matrix(&a, orient);
3777                 //if((ang.h > 3.1300) && (ang.h < 3.1500)){                     
3778                 //} else {
3779
3780                         util_matrix_to_rot_axis_and_angle(orient, &theta, &rot_axis);           
3781                         // Have theta, which is an angle between 0 and PI.
3782                         // Convert it to be between -1.0f and 1.0f
3783                         theta = theta*2.0f/PI-1.0f;
3784
3785                         #define SCALE 2048.0f
3786
3787                         #define MAX_RANGE 2047
3788                         #define MIN_RANGE -2048
3789
3790                         // -1 to 1
3791                         a = fl2i(rot_axis.xyz.x*SCALE); 
3792                         b = fl2i(rot_axis.xyz.y*SCALE);
3793                         c = fl2i(rot_axis.xyz.z*SCALE);
3794                         d = fl2i(theta*SCALE);
3795
3796                         CAP(a,MIN_RANGE,MAX_RANGE);
3797                         CAP(b,MIN_RANGE,MAX_RANGE);
3798                         CAP(c,MIN_RANGE,MAX_RANGE);
3799                         CAP(d,MIN_RANGE,MAX_RANGE);
3800                 //}
3801                 
3802                 bitbuffer_put( &buf, (uint)a, 12 );
3803                 bitbuffer_put( &buf, (uint)b, 12 );
3804                 bitbuffer_put( &buf, (uint)c, 12 );
3805                 bitbuffer_put( &buf, (uint)d, 12 );
3806
3807                 return bitbuffer_write_flush(&buf);
3808
3809         } else {
3810
3811                 a = bitbuffer_get_signed(&buf,12);
3812                 b = bitbuffer_get_signed(&buf,12);
3813                 c = bitbuffer_get_signed(&buf,12);
3814                 d = bitbuffer_get_signed(&buf,12);
3815
3816                 // special case         
3817                 rot_axis.xyz.x = i2fl(a)/SCALE;
3818                 rot_axis.xyz.y = i2fl(b)/SCALE;
3819                 rot_axis.xyz.z = i2fl(c)/SCALE;
3820                 theta = i2fl(d)/SCALE;
3821                         
3822                 // Convert theta back to range 0-PI
3823                 theta = (theta+1.0f)*PI/2.0f;
3824                         
3825                 vm_quaternion_rotate(orient, theta, &rot_axis);         
3826
3827                 vm_orthogonalize_matrix(orient);                
3828
3829                 return bitbuffer_read_flush(&buf);
3830         }
3831 }
3832 */
3833
3834 // Packs/unpacks velocity
3835 // Returns number of bytes read or written.
3836 // #define OO_VEL_RET_SIZE                                                      4
3837 int multi_pack_unpack_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
3838 {
3839         bitbuffer buf;
3840
3841         bitbuffer_init(&buf,data);
3842
3843         int a, b, c;
3844         float r, u, f;
3845
3846         if ( write )    {
3847                 // output velocity
3848                 r = vm_vec_dot( &orient->v.rvec, &pi->vel );
3849                 u = vm_vec_dot( &orient->v.uvec, &pi->vel );
3850                 f = vm_vec_dot( &orient->v.fvec, &pi->vel );
3851
3852                 a = fl2i(r * 0.5f); 
3853                 b = fl2i(u * 0.5f);
3854                 c = fl2i(f * 0.5f);
3855                 CAP(a,-512,511);
3856                 CAP(b,-512,511);
3857                 CAP(c,-512,511);
3858                 bitbuffer_put( &buf, (uint)a, 10 );
3859                 bitbuffer_put( &buf, (uint)b, 10 );
3860                 bitbuffer_put( &buf, (uint)c, 10 );
3861
3862                 return bitbuffer_write_flush(&buf);
3863         } else {
3864                 // unpack velocity
3865                 float r, u, f;
3866                 a = bitbuffer_get_signed(&buf,10);
3867                 b = bitbuffer_get_signed(&buf,10);
3868                 c = bitbuffer_get_signed(&buf,10);
3869                 r = i2fl(a)/0.5f;
3870                 u = i2fl(b)/0.5f;
3871                 f = i2fl(c)/0.5f;
3872
3873                 // Convert into world coordinates
3874                 vm_vec_zero(&pi->vel);
3875                 vm_vec_scale_add2( &pi->vel, &orient->v.rvec, r );
3876                 vm_vec_scale_add2( &pi->vel, &orient->v.uvec, u );
3877                 vm_vec_scale_add2( &pi->vel, &orient->v.fvec, f );
3878
3879                 return bitbuffer_read_flush(&buf);
3880         }
3881 }
3882
3883 // Packs/unpacks desired_velocity
3884 // Returns number of bytes read or written.
3885 // #define OO_DESIRED_VEL_RET_SIZE                              3
3886 int multi_pack_unpack_desired_vel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
3887 {
3888         bitbuffer buf;
3889
3890         bitbuffer_init(&buf,data);
3891
3892         int a;
3893         vector  max_vel;
3894         float r,u,f;
3895         int fields = 0;
3896
3897         max_vel.xyz.x = max( sip->max_vel.xyz.x, sip->afterburner_max_vel.xyz.x );
3898         max_vel.xyz.y = max( sip->max_vel.xyz.y, sip->afterburner_max_vel.xyz.y );
3899         max_vel.xyz.z = max( sip->max_vel.xyz.z, sip->afterburner_max_vel.xyz.z );      
3900
3901         if ( write )    {
3902                 // Find desired vel in local coordinates
3903                 // Velocity can be from -1024 to 1024
3904
3905                 // bitfields for each value             
3906                 if(max_vel.xyz.x > 0.0f){
3907                         fields |= (1<<0);
3908                 }
3909                 if(max_vel.xyz.y > 0.0f){
3910                         fields |= (1<<1);
3911                 }
3912                 if(max_vel.xyz.z > 0.0f){
3913                         fields |= (1<<2);
3914                 }               
3915                 // fields = sip - Ship_info;
3916                 bitbuffer_put(&buf, (uint)fields, 8);
3917
3918                 r = vm_vec_dot( &orient->v.rvec, &pi->desired_vel );
3919                 u = vm_vec_dot( &orient->v.uvec, &pi->desired_vel );
3920                 f = vm_vec_dot( &orient->v.fvec, &pi->desired_vel );
3921
3922                 if ( max_vel.xyz.x > 0.0f )     {
3923                         r = r / max_vel.xyz.x;
3924                         a = fl2i( r * 128.0f );
3925                         CAP(a,-128, 127 );                      
3926                         bitbuffer_put( &buf, (uint)a, 8 );                      
3927                 } 
3928
3929                 if ( max_vel.xyz.y > 0.0f )     {
3930                         u = u / max_vel.xyz.y;
3931                         a = fl2i( u * 128.0f );
3932                         CAP(a,-128, 127 );
3933                         bitbuffer_put( &buf, (uint)a, 8 );
3934                 } 
3935
3936                 if ( max_vel.xyz.z > 0.0f )     {
3937                         f = f / max_vel.xyz.z;
3938                         a = fl2i( f * 128.0f );
3939                         CAP(a,-128, 127 );
3940                         bitbuffer_put( &buf, (uint)a, 8 );
3941                 }
3942
3943                 return bitbuffer_write_flush(&buf);
3944         } else {
3945
3946                 // Find desired vel in local coordinates
3947                 // Velocity can be from -1024 to 1024
3948
3949                 // get the fields bitbuffer
3950                 fields = bitbuffer_get_signed(&buf, 8);
3951                 
3952                 if ( fields & (1<<0) )  {
3953                         a = bitbuffer_get_signed(&buf,8);
3954                         r = i2fl(a)/128.0f;
3955                 } else {
3956                         r = 0.0f;
3957                 }
3958                 
3959                 if ( fields & (1<<1) )  {
3960                         a = bitbuffer_get_signed(&buf,8);
3961                         u = i2fl(a)/128.0f;
3962                 } else {
3963                         u = 0.0f;
3964                 }
3965                 
3966                 if ( fields & (1<<2) )  {
3967                         a = bitbuffer_get_signed(&buf,8);
3968                         f = i2fl(a)/128.0f;
3969                 } else {
3970                         f = 0.0f;
3971                 }               
3972                 
3973                 // Convert into world coordinates
3974                 vm_vec_zero(&pi->vel);
3975                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.rvec, r*max_vel.xyz.x );
3976                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.uvec, u*max_vel.xyz.y );
3977                 vm_vec_scale_add2( &pi->desired_vel, &orient->v.fvec, f*max_vel.xyz.z );
3978
3979                 return bitbuffer_read_flush(&buf);
3980         }
3981 }
3982
3983 // Packs/unpacks rotational velocity
3984 // Returns number of bytes read or written.
3985 // #define OO_ROTVEL_RET_SIZE                                           4
3986 int multi_pack_unpack_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi)
3987 {
3988         bitbuffer buf;
3989
3990         bitbuffer_init(&buf,data);
3991
3992         int a, b, c;
3993
3994         if ( write )    {
3995                 // output rotational velocity
3996                 a = fl2i(pi->rotvel.xyz.x*32.0f); 
3997                 b = fl2i(pi->rotvel.xyz.y*32.0f);
3998                 c = fl2i(pi->rotvel.xyz.z*32.0f);
3999                 CAP(a,-512,511);
4000                 CAP(b,-512,511);
4001                 CAP(c,-512,511);
4002                 bitbuffer_put( &buf, (uint)a, 10 );
4003                 bitbuffer_put( &buf, (uint)b, 10 );
4004                 bitbuffer_put( &buf, (uint)c, 10 );
4005
4006
4007                 return bitbuffer_write_flush(&buf);
4008
4009         } else {
4010
4011                 // unpack rotational velocity
4012                 a = bitbuffer_get_signed(&buf,10);
4013                 b = bitbuffer_get_signed(&buf,10);
4014                 c = bitbuffer_get_signed(&buf,10);
4015                 pi->rotvel.xyz.x = i2fl(a)/32.0f;
4016                 pi->rotvel.xyz.y = i2fl(b)/32.0f;
4017                 pi->rotvel.xyz.z = i2fl(c)/32.0f;
4018
4019                 return bitbuffer_read_flush(&buf);
4020         }
4021 }
4022
4023 // Packs/unpacks desired rotvel
4024 // Returns number of bytes read or written.
4025 // #define OO_DESIRED_ROTVEL_RET_SIZE                   3
4026 int multi_pack_unpack_desired_rotvel( int write, ubyte *data, matrix *orient, vector *pos, physics_info *pi, ship_info *sip)
4027 {
4028         bitbuffer buf;
4029         int fields = 0;
4030
4031         bitbuffer_init(&buf,data);
4032
4033         int a;
4034         float r,u,f;
4035
4036         if ( write )    {
4037                 // use ship_info values for max_rotvel instead of taking it from physics info
4038
4039                 // bitfields for each value
4040                 if(sip->max_rotvel.xyz.x > 0.0f){
4041                         fields |= (1<<0);
4042                 }
4043                 if(sip->max_rotvel.xyz.y > 0.0f){
4044                         fields |= (1<<1);
4045                 }
4046                 if(sip->max_rotvel.xyz.z > 0.0f){
4047                         fields |= (1<<2);
4048
4049                 }
4050                 bitbuffer_put(&buf, (uint)fields, 8);
4051
4052                 // output desired rotational velocity as a percent of max               
4053                 if ( sip->max_rotvel.xyz.x > 0.0f )     {               
4054                         a = fl2i( pi->desired_rotvel.xyz.x*128.0f / sip->max_rotvel.xyz.x );
4055                         CAP(a,-128, 127 );
4056                         bitbuffer_put( &buf, (uint)a, 8 );
4057                 } 
4058
4059                 if ( sip->max_rotvel.xyz.y > 0.0f )     {               
4060                         a = fl2i( pi->desired_rotvel.xyz.y*128.0f / sip->max_rotvel.xyz.y );
4061                         CAP(a,-128, 127 );
4062                         bitbuffer_put( &buf, (uint)a, 8 );
4063                 } 
4064
4065                 if ( sip->max_rotvel.xyz.z > 0.0f )     {               
4066                         a = fl2i( pi->desired_rotvel.xyz.z*128.0f / sip->max_rotvel.xyz.z );
4067                         CAP(a,-128, 127 );
4068                         bitbuffer_put( &buf, (uint)a, 8 );
4069                 } 
4070
4071                 return bitbuffer_write_flush(&buf);
4072         } else {
4073                 fields = bitbuffer_get_signed(&buf, 8);
4074
4075                 // unpack desired rotational velocity
4076                 if ( fields & (1<<0) )  {               
4077                         a = bitbuffer_get_signed(&buf,8);
4078                         r = i2fl(a)/128.0f;
4079                 } else {
4080                         r = 0.0f;
4081                 }
4082                 if ( fields & (1<<1) )  {               
4083                         a = bitbuffer_get_signed(&buf,8);
4084                         u = i2fl(a)/128.0f;
4085                 } else {
4086                         u = 0.0f;
4087                 }
4088                 if ( fields & (1<<2) )  {               
4089                         a = bitbuffer_get_signed(&buf,8);
4090                         f = i2fl(a)/128.0f;
4091                 } else {
4092                         f = 0.0f;
4093                 }
4094                 pi->desired_rotvel.xyz.x = r*sip->max_rotvel.xyz.x;
4095                 pi->desired_rotvel.xyz.y = u*sip->max_rotvel.xyz.y;
4096                 pi->desired_rotvel.xyz.z = f*sip->max_rotvel.xyz.z;
4097
4098                 return bitbuffer_read_flush(&buf);
4099         }
4100 }
4101
4102 #ifndef PLAT_UNIX
4103 #pragma optimize("", on)
4104 #endif