]> icculus.org git repositories - btb/d2x.git/blob - main/network.c
more header fixes
[btb/d2x.git] / main / network.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 /*
15  *
16  * Routines for managing network play.
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include <conf.h>
22 #endif
23
24 #define PATCH12
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29
30 #include "strutil.h"
31 #include "args.h"
32 #include "timer.h"
33 #include "mono.h"
34 #include "ipx.h"
35 #include "key.h"
36 #include "inferno.h"
37 #include "error.h"
38 #include "byteswap.h"
39 #include "cfile.h"
40
41 #ifdef MACINTOSH
42 #include <Events.h>
43 #include <Errors.h>     // for appletalk networking errors
44 #include "appltalk.h"
45 #endif
46
47
48 #define LHX(x)          ((x)*(MenuHires?2:1))
49 #define LHY(y)          ((y)*(MenuHires?2.4:1))
50
51 /* the following are the possible packet identificators.
52  * they are stored in the "type" field of the packet structs.
53  * they are offset 4 bytes from the beginning of the raw IPX data
54  * because of the "driver's" ipx_packetnum (see linuxnet.c).
55  */
56 #define PID_LITE_INFO       43 // 0x2B lite game info
57 #define PID_SEND_ALL_GAMEINFO 44 // 0x2C plz send more than lite only
58 #define PID_PLAYERSINFO     45 // 0x2D here's my name & personal data
59 #define PID_REQUEST         46 // 0x2E may i join, plz send sync
60 #define PID_SYNC            47 // 0x2F master says: enter mine now!
61 #define PID_PDATA           48 // 0x30
62 #define PID_ADDPLAYER       49
63
64 #define PID_DUMP            51 // 0x33 you can't join this game
65 #define PID_ENDLEVEL        52
66
67 #define PID_QUIT_JOINING    54
68 #define PID_OBJECT_DATA     55 // array of bots, players, powerups, ...
69 #define PID_GAME_LIST       56 // 0x38 give me the list of your games
70 #define PID_GAME_INFO       57 // 0x39 here's a game i've started
71 #define PID_PING_SEND       58
72 #define PID_PING_RETURN     59
73 #define PID_GAME_UPDATE     60 // inform about new player/team change
74 #define PID_ENDLEVEL_SHORT  61
75 #define PID_NAKED_PDATA     62
76 #define PID_GAME_PLAYERS    63
77 #define PID_NAMES_RETURN    64 // 0x40
78
79
80 #define NETGAME_ANARCHY         0
81 #define NETGAME_TEAM_ANARCHY    1
82 #define NETGAME_ROBOT_ANARCHY   2
83 #define NETGAME_COOPERATIVE     3
84 #define NETGAME_CAPTURE_FLAG    4
85 #define NETGAME_HOARD           5
86 #define NETGAME_TEAM_HOARD      6
87
88 /* The following are values for NetSecurityFlag */
89 #define NETSECURITY_OFF                 0
90 #define NETSECURITY_WAIT_FOR_PLAYERS    1
91 #define NETSECURITY_WAIT_FOR_GAMEINFO   2
92 #define NETSECURITY_WAIT_FOR_SYNC       3
93 /* The NetSecurityNum and the "Security" field of the network structs
94  * identifies a netgame. It is a random number chosen by the network master
95  * (the one that did "start netgame").
96  */
97
98 // MWA -- these structures are aligned -- please save me sanity and
99 // headaches by keeping alignment if these are changed!!!!  Contact
100 // me for info.
101
102 typedef struct endlevel_info {
103         ubyte                               type;
104         ubyte                               player_num;
105         sbyte                               connected;
106         ubyte                               seconds_left;
107         short                              kill_matrix[MAX_PLAYERS][MAX_PLAYERS];
108         short                               kills;
109         short                               killed;
110 } endlevel_info;
111
112 typedef struct endlevel_info_short {
113         ubyte                               type;
114         ubyte                               player_num;
115         sbyte                               connected;
116         ubyte                               seconds_left;
117 } endlevel_info_short;
118
119 // WARNING!!! This is the top part of netgame_info...if that struct changes,
120 //      this struct much change as well.  ie...they are aligned and the join system will
121 // not work without it.
122
123 // MWA  if this structure changes -- please make appropriate changes to receive_netgame_info
124 // code for macintosh in netmisc.c
125
126 typedef struct lite_info {
127         ubyte                           type;
128         int                             Security;
129         char                            game_name[NETGAME_NAME_LEN+1];
130         char                            mission_title[MISSION_NAME_LEN+1];
131         char                            mission_name[9];
132         int                             levelnum;
133         ubyte                           gamemode;
134         ubyte                           RefusePlayers;
135         ubyte                           difficulty;
136         ubyte                           game_status;
137         ubyte                           numplayers;
138         ubyte                           max_numplayers;
139         ubyte                           numconnected;
140         ubyte                           game_flags;
141         ubyte                           protocol_version;
142         ubyte                           version_major;
143         ubyte                           version_minor;
144         ubyte                           team_vector;
145 } __pack__ lite_info;
146
147 // IF YOU CHANGE THE SIZE OF ANY OF THE FOLLOWING STRUCTURES
148 // MAKE THE MACINTOSH DEFINES BE THE SAME SIZE AS THE PC OR
149 // I WILL HAVE TO HURT YOU VERY BADLY!!!  -- MWA
150
151 #ifdef MACINTOSH
152 #define NETGAME_INFO_SIZE       ( Network_game_type == IPX_GAME?355:sizeof(netgame_info) )
153 #define ALLNETPLAYERSINFO_SIZE  ( Network_game_type == IPX_GAME?317:sizeof(AllNetPlayers_info) )
154 #define LITE_INFO_SIZE          ( Network_game_type == IPX_GAME?72:sizeof(lite_info) )
155 #define SEQUENCE_PACKET_SIZE    ( Network_game_type == IPX_GAME?34:sizeof(sequence_packet) )
156 #define FRAME_INFO_SIZE         ( Network_game_type == IPX_GAME?541:sizeof(frame_info) )
157 #define IPX_SHORT_INFO_SIZE     ( 490 )
158 #else
159 #define NETGAME_INFO_SIZE       sizeof(netgame_info)
160 #define ALLNETPLAYERSINFO_SIZE  sizeof(AllNetPlayers_info)
161 #define LITE_INFO_SIZE          sizeof(lite_info)
162 #define SEQUENCE_PACKET_SIZE    sizeof(sequence_packet)
163 #define FRAME_INFO_SIZE         sizeof(frame_info)
164 #define IPX_SHORT_INFO_SIZE     sizeof(short_frame_info)
165 #endif
166
167 #define MAX_ACTIVE_NETGAMES     12
168
169 netgame_info Active_games[MAX_ACTIVE_NETGAMES];
170 AllNetPlayers_info ActiveNetPlayers[MAX_ACTIVE_NETGAMES];
171 AllNetPlayers_info *TempPlayersInfo,TempPlayersBase;
172 int NamesInfoSecurity=-1;
173
174 // MWAnetgame_info *TempNetInfo; 
175 netgame_info TempNetInfo;
176
177 extern void multi_send_drop_marker (int player,vms_vector position,char messagenum,char text[]);
178 extern void multi_send_kill_goal_counts();
179 extern int newmenu_dotiny( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem) );
180
181 void network_process_naked_pdata (char *,int);
182 extern void multi_send_robot_controls(char);
183
184 void network_flush();
185 void network_listen();
186 void network_update_netgame();
187 void network_check_for_old_version(char pnum);
188 void network_send_objects();
189 void network_send_rejoin_sync(int player_num);
190 void network_send_game_info(sequence_packet *their);
191 void network_send_endlevel_short_sub(int from_player_num, int to_player);
192 void network_read_sync_packet(netgame_info * sp, int rsinit);
193 int  network_wait_for_playerinfo();
194 void network_process_pdata(char *data);
195 void network_read_object_packet(ubyte *data );
196 void network_read_endlevel_packet(ubyte *data );
197 void network_read_endlevel_short_packet(ubyte *data );
198 void network_ping(ubyte flat, int pnum);
199 void network_handle_ping_return(ubyte pnum);
200 void network_process_names_return(ubyte *data);
201 void network_send_player_names(sequence_packet *their);
202 int  network_choose_connect();
203 void network_more_game_options();
204 void network_count_powerups_in_mine();
205 int  network_wait_for_all_info(int choice);
206 void network_AdjustMaxDataSize();
207 void network_do_big_wait(int choice);
208 void network_send_extras();
209 void network_read_pdata_packet(frame_info *pd);
210 void network_read_pdata_short_packet(short_frame_info *pd);
211
212 void ClipRank(ubyte *rank);
213 void DoRefuseStuff(sequence_packet *their);
214 int  GetNewPlayerNumber(sequence_packet *their);
215 void SetAllAllowablesTo(int on);
216
217 int num_active_games = 0;
218 int PacketsPerSec=10;
219 int MaxXDataSize=NET_XDATA_SIZE;
220
221 int     Netlife_kills=0, Netlife_killed=0;
222
223 int     Network_debug=0;
224 int     Network_active=0;
225
226 int     Network_status = 0;
227 int     Network_games_changed = 0;
228
229 int     Network_socket = 0;
230 int     Network_allow_socket_changes = 1;
231
232 int     NetSecurityFlag=NETSECURITY_OFF;
233 int     NetSecurityNum=0;
234 int     Network_sending_extras=0;
235 int     VerifyPlayerJoined=-1;
236 int     Player_joining_extras=-1;  // This is so we know who to send 'latecomer' packets to.
237                                                                                           // We could just send updates to everyone but that kills the sender!   
238
239 // For rejoin object syncing
240
241 int     Network_rejoined = 0;       // Did WE rejoin this game?
242 int     Network_new_game = 0;            // Is this the first level of a new game?
243 int     Network_send_objects = 0;  // Are we in the process of sending objects to a player?
244 int     Network_send_objnum = -1;   // What object are we sending next?
245 int     Network_player_added = 0;   // Is this a new player or a returning player?
246 int     Network_send_object_mode = 0; // What type of objects are we sending, static or dynamic?
247 sequence_packet Network_player_rejoining; // Who is rejoining now?
248
249 fix     LastPacketTime[MAX_PLAYERS]; // For timeouts of idle/crashed players
250
251 int     PacketUrgent = 0;
252 int     NetGameType=0;
253 int     TotalMissedPackets=0,TotalPacketsGot=0;
254
255 frame_info      MySyncPack,UrgentSyncPack;
256 ubyte           MySyncPackInitialized = 0;              // Set to 1 if the MySyncPack is zeroed.
257 ushort          my_segments_checksum = 0;
258
259 sequence_packet My_Seq;
260 char WantPlayersInfo=0;
261 char WaitingForPlayerInfo=0;
262
263 char *RankStrings[]={"(unpatched) ","Cadet ","Ensign ","Lieutenant ","Lt.Commander ",
264                      "Commander ","Captain ","Vice Admiral ","Admiral ","Demigod "};
265
266 extern obj_position Player_init[MAX_PLAYERS];
267
268 extern int force_cockpit_redraw;
269
270 // reasons for a packet with type PID_DUMP
271 #define DUMP_CLOSED     0 // no new players allowed after game started
272 #define DUMP_FULL       1 // player cound maxed out
273 #define DUMP_ENDLEVEL   2
274 #define DUMP_DORK       3
275 #define DUMP_ABORTED    4
276 #define DUMP_CONNECTED  5 // never used
277 #define DUMP_LEVEL      6
278 #define DUMP_KICKED     7 // never used
279
280 extern ubyte Version_major,Version_minor;
281 extern ubyte SurfingNet;
282 extern char MaxPowerupsAllowed[MAX_POWERUP_TYPES];
283 extern char PowerupsInMine[MAX_POWERUP_TYPES];
284
285 extern void multi_send_stolen_items();
286
287 int network_wait_for_snyc();
288 extern void multi_send_wall_status (int,ubyte,ubyte,ubyte);
289 extern void multi_send_wall_status_specific (int,int,ubyte,ubyte,ubyte);
290
291 extern void game_disable_cheats();
292
293 char IWasKicked=0;
294 #ifdef NETPROFILING
295 FILE *SendLogFile,*RecieveLogFile;
296 int TTSent[100],TTRecv[100];
297 #endif
298
299 extern int Final_boss_is_dead;
300
301 // following is network stuff for appletalk
302
303 void network_dump_appletalk_player(ubyte node, ushort net, ubyte socket, int why);
304
305 #define NETWORK_OEM 0x10
306
307 #ifdef MACINTOSH
308
309 int Network_game_type;                                  // used to tell IPX vs. appletalk games
310
311 #define MAX_ZONES               255
312 #define MAX_ZONE_LENGTH         33
313 #define DEFAULT_ZONE_NAME       "\p*"
314 #define MAX_REGISTER_TRIES      5                                       // maximum time we will try and register a netgame
315 char Network_zone_name[MAX_ZONE_LENGTH];                // zone name game being played in for appletalk
316 char Zone_names[MAX_ZONES][MAX_ZONE_LENGTH];    // total list of zones that we can see
317 ubyte appletalk_use_broadcast = 0;
318 ubyte Network_game_validated = 0;               // validates a game before being able to join
319 ubyte Network_game_validate_choice = 0;
320 ubyte Network_appletalk_type = 0;               // type of appletalk network game is being played on
321
322 #define ETHERTALK_TYPE  0
323 #define LOCALTALK_TYPE  1
324 #define OTHERTALK_TYPE  2
325
326
327 void network_release_registered_game(void);
328
329 #endif
330
331 void
332 network_init(void)
333 {
334   
335         // So you want to play a netgame, eh?  Let's a get a few things
336         // straight
337
338    int t;
339         int save_pnum = Player_num;
340
341         game_disable_cheats();
342    IWasKicked=0;
343    Final_boss_is_dead=0;
344    NamesInfoSecurity=-1;
345
346
347    #ifdef NETPROFILING
348            OpenSendLog();
349                 OpenRecieveLog(); 
350         #endif
351         
352         for (t=0;t<MAX_POWERUP_TYPES;t++)
353                 {
354                         MaxPowerupsAllowed[t]=0;
355                         PowerupsInMine[t]=0;
356                 }
357
358    TotalMissedPackets=0; TotalPacketsGot=0;
359
360         memset(&Netgame, 0, sizeof(netgame_info));
361         memset(&NetPlayers,0,sizeof(AllNetPlayers_info));
362         memset(&My_Seq, 0, sizeof(sequence_packet));
363         My_Seq.type = PID_REQUEST;
364         memcpy(My_Seq.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
365
366         My_Seq.player.version_major=Version_major;
367         My_Seq.player.version_minor=Version_minor;
368    My_Seq.player.rank=GetMyNetRanking();        
369  
370         if (Network_game_type == IPX_GAME) {
371                 memcpy(My_Seq.player.network.ipx.node, ipx_get_my_local_address(), 6);
372                 memcpy(My_Seq.player.network.ipx.server, ipx_get_my_server_address(), 4 );
373         #ifdef MACINTOSH
374         } else {
375                 My_Seq.player.network.appletalk.node = appletalk_get_my_node();
376                 My_Seq.player.network.appletalk.net = appletalk_get_my_net();
377                 My_Seq.player.network.appletalk.socket = appletalk_get_my_socket();
378         #endif
379         }
380 #ifdef MACINTOSH
381         My_Seq.player.computer_type = MAC;
382 #else
383         My_Seq.player.computer_type = DOS;
384 #endif
385
386         for (Player_num = 0; Player_num < MAX_NUM_NET_PLAYERS; Player_num++)
387                 init_player_stats_game();
388
389         Player_num = save_pnum;         
390         multi_new_game();
391         Network_new_game = 1;
392         Control_center_destroyed = 0;
393         network_flush();
394
395         Netgame.PacketsPerSec=10;
396
397    if ((t=FindArg("-packets")))
398     {
399      Netgame.PacketsPerSec=atoi(Args[t+1]);
400      if (Netgame.PacketsPerSec<1)
401       Netgame.PacketsPerSec=1;
402      else if (Netgame.PacketsPerSec>20)
403       Netgame.PacketsPerSec=20;
404      mprintf ((0,"Will send %d packets per second",Netgame.PacketsPerSec));
405     }
406    if (FindArg("-shortpackets"))
407     {
408      Netgame.ShortPackets=1;
409      mprintf ((0,"Will send short packets.\n"));
410     }
411 }
412
413 int
414 network_i_am_master(void)
415 {
416         // I am the lowest numbered player in this game?
417
418         int i;
419
420         if (!(Game_mode & GM_NETWORK))
421                 return (Player_num == 0);
422
423         for (i = 0; i < Player_num; i++)
424                 if (Players[i].connected)
425                         return 0;
426         return 1;
427 }
428
429 int network_who_is_master(void)
430 {
431         // Who is the master of this game?
432
433         int i;
434
435         if (!(Game_mode & GM_NETWORK))
436                 return (Player_num == 0);
437
438         for (i = 0; i < N_players; i++)
439                 if (Players[i].connected)
440                         return i;
441         return Player_num;
442 }
443 int network_how_many_connected()
444  {
445   int num=0,i;
446  
447         for (i = 0; i < N_players; i++)
448                 if (Players[i].connected)
449                         num++;
450    return (num);
451  }
452
453 #define ENDLEVEL_SEND_INTERVAL  (F1_0*2)
454 #define ENDLEVEL_IDLE_TIME      (F1_0*20)
455 /*
456 void
457 network_endlevel_poll( int nitems, newmenu_item * menus, int * key, int citem )
458 {
459         // Polling loop for End-of-level menu
460
461         static fix t1 = 0;
462         int i = 0;
463         int num_ready = 0;
464         int num_escaped = 0;
465         int goto_secret = 0;
466
467         int previous_state[MAX_NUM_NET_PLAYERS];
468         int previous_seconds_left;
469
470         menus = menus;
471         citem = citem;
472         nitems = nitems;
473         key = key;
474
475         // Send our endlevel packet at regular intervals
476
477         if (timer_get_approx_seconds() > (t1+ENDLEVEL_SEND_INTERVAL))
478         {
479                 network_send_endlevel_packet();
480                 t1 = timer_get_approx_seconds();
481         }
482
483         for (i = 0; i < N_players; i++)
484                 previous_state[i] = Players[i].connected;
485
486         previous_seconds_left = Countdown_seconds_left;
487
488         network_listen();
489
490         for (i = 0; i < N_players; i++)
491         {
492                 if (Players[i].connected == 1)
493                 {
494                         // Check timeout for idle players
495                         if (timer_get_approx_seconds() > LastPacketTime[i]+ENDLEVEL_IDLE_TIME)
496                         {
497                                 mprintf((0, "idle timeout for player %d.\n", i));
498                                 Players[i].connected = 0;
499                                 network_send_endlevel_sub(i);
500                         }                               
501                 }
502
503                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
504                         num_ready++;
505                 if (Players[i].connected != 1)
506                         num_escaped++;
507                 if (Players[i].connected == 4)
508                         goto_secret = 1;
509         }
510
511         if (num_escaped == N_players) // All players are out of the mine
512         {
513                 Countdown_seconds_left = -1;
514         }
515
516
517         if (num_ready == N_players) // All players have checked in or are disconnected
518         {
519                 if (goto_secret)
520                         *key = -3;
521                 else
522                         *key = -2;
523         }
524 } */
525   
526 void 
527 network_endlevel_poll2( int nitems, newmenu_item * menus, int * key, int citem )
528 {
529         // Polling loop for End-of-level menu
530
531         static fix t1 = 0;
532         int i = 0;
533         int num_ready = 0;
534         int goto_secret = 0;
535
536         // Send our endlevel packet at regular intervals
537
538         if (timer_get_approx_seconds() > (t1+ENDLEVEL_SEND_INTERVAL))
539         {
540                 network_send_endlevel_packet();
541                 t1 = timer_get_approx_seconds();
542         }
543
544 //   mprintf ((0,"Trying to listen!\n"));
545         network_listen();
546
547         for (i = 0; i < N_players; i++)
548         {
549                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
550                         num_ready++;
551                 if (Players[i].connected == 4)
552                         goto_secret = 1;                                        
553         }
554
555         if (num_ready == N_players) // All players have checked in or are disconnected
556         {
557                 if (goto_secret)
558                         *key = -3;
559                 else
560                         *key = -2;
561         }
562 }
563
564
565 extern fix StartAbortMenuTime;
566
567 void 
568 network_endlevel_poll3( int nitems, newmenu_item * menus, int * key, int citem )
569 {
570         // Polling loop for End-of-level menu
571
572    int num_ready=0,i;
573
574         if (timer_get_approx_seconds() > (StartAbortMenuTime+(F1_0 * 8)))
575     *key=-2;
576
577
578         network_listen();
579
580
581         for (i = 0; i < N_players; i++)
582                 if ((Players[i].connected != 1) && (Players[i].connected != 5) && (Players[i].connected != 6))
583                         num_ready++;
584
585         if (num_ready == N_players) // All players have checked in or are disconnected
586                         *key = -2;
587
588 }
589
590
591 int
592 network_endlevel(int *secret)
593 {
594         // Do whatever needs to be done between levels
595
596    int i;
597
598    *secret=0;
599
600         //network_flush();
601
602         Network_status = NETSTAT_ENDLEVEL; // We are between levels
603
604         network_listen();
605
606         network_send_endlevel_packet();
607
608         for (i=0; i<N_players; i++) 
609         {
610                 LastPacketTime[i] = timer_get_approx_seconds();
611         }
612    
613         network_send_endlevel_packet();
614         network_send_endlevel_packet();
615         MySyncPackInitialized = 0;
616
617         network_update_netgame();
618
619         return(0);
620 }
621
622 int 
623 can_join_netgame(netgame_info *game,AllNetPlayers_info *people)
624 {
625         // Can this player rejoin a netgame in progress?
626
627         int i, num_players;
628
629         if (game->game_status == NETSTAT_STARTING)
630      return 1;
631
632         if (game->game_status != NETSTAT_PLAYING)
633     {
634       mprintf ((0,"Error: Can't join because game_status !=NETSTAT_PLAYING\n"));
635                 return 0;
636     }
637
638    if (game->version_major==0 && Version_major>0)
639     {
640            mprintf ((0,"Error:Can't join because version majors don't match!\n"));
641                 return (0);
642     }
643
644         if (game->version_major>0 && Version_major==0)
645     {
646            mprintf ((0,"Error:Can't join because version majors2 don't match!\n"));
647                 return (0);
648     }
649
650         // Game is in progress, figure out if this guy can re-join it
651
652         num_players = game->numplayers;
653
654         if (!(game->game_flags & NETGAME_FLAG_CLOSED)) {
655                 // Look for player that is not connected
656                 
657                 if (game->numconnected==game->max_numplayers)
658                  return (2);
659
660 //      mprintf ((0,"Refuse = %d\n",game->RefusePlayers));
661                 
662                 if (game->RefusePlayers)
663                  return (3);
664                 
665                 if (game->numplayers < game->max_numplayers)
666                         return 1;
667
668                 if (game->numconnected<num_players)
669                         return 1;
670                      
671         }
672
673         if (people==NULL)
674     {
675       mprintf ((0,"Error! Can't join because people==NULL!\n"));
676                 return 0;
677     }
678         
679         // Search to see if we were already in this closed netgame in progress
680
681         for (i = 0; i < num_players; i++) {
682                 if (Network_game_type == IPX_GAME) {
683                         if ( (!stricmp(Players[Player_num].callsign, people->players[i].callsign)) &&
684                                   (!memcmp(My_Seq.player.network.ipx.node, people->players[i].network.ipx.node, 6)) &&
685                                   (!memcmp(My_Seq.player.network.ipx.server, people->players[i].network.ipx.server, 4)) )
686                                 break;
687                 } else {
688                         if ( (!stricmp(Players[Player_num].callsign, people->players[i].callsign)) &&
689                                   (My_Seq.player.network.appletalk.node == people->players[i].network.appletalk.node) &&
690                                   (My_Seq.player.network.appletalk.net == people->players[i].network.appletalk.net) )
691                                 break;
692                 }
693         }
694
695         if (i != num_players)
696                 return 1;
697  
698    mprintf ((0,"Error: Can't join because at end of list!\n"));
699         return 0;
700 }
701
702 void
703 network_disconnect_player(int playernum)
704 {
705         // A player has disconnected from the net game, take whatever steps are
706         // necessary 
707
708         if (playernum == Player_num) 
709         {
710                 Int3(); // Weird, see Rob
711                 return;
712         }
713
714         Players[playernum].connected = 0;
715    NetPlayers.players[playernum].connected = 0;
716    if (VerifyPlayerJoined==playernum)
717           VerifyPlayerJoined=-1;
718
719 //      create_player_appearance_effect(&Objects[Players[playernum].objnum]);
720         multi_make_player_ghost(playernum);
721
722         if (Newdemo_state == ND_STATE_RECORDING)
723                 newdemo_record_multi_disconnect(playernum);
724
725         multi_strip_robots(playernum);
726 }
727                 
728 void
729 network_new_player(sequence_packet *their)
730 {
731         int objnum;
732         int pnum;
733
734         pnum = their->player.connected;
735
736         Assert(pnum >= 0);
737         Assert(pnum < MaxNumNetPlayers);        
738         
739         objnum = Players[pnum].objnum;
740
741         if (Newdemo_state == ND_STATE_RECORDING) {
742                 int new_player;
743
744                 if (pnum == N_players)
745                         new_player = 1;
746                 else
747                         new_player = 0;
748                 newdemo_record_multi_connect(pnum, new_player, their->player.callsign);
749         }
750
751         memcpy(Players[pnum].callsign, their->player.callsign, CALLSIGN_LEN+1);
752         memcpy(NetPlayers.players[pnum].callsign, their->player.callsign, CALLSIGN_LEN+1);
753         
754
755    ClipRank (&their->player.rank);
756    NetPlayers.players[pnum].rank=their->player.rank;
757         NetPlayers.players[pnum].version_major=their->player.version_major;
758         NetPlayers.players[pnum].version_minor=their->player.version_minor;
759    network_check_for_old_version(pnum);
760
761         if (Network_game_type == IPX_GAME) {
762                 if ( (*(uint *)their->player.network.ipx.server) != 0 )
763                         ipx_get_local_target( their->player.network.ipx.server, their->player.network.ipx.node, Players[pnum].net_address );
764                 else
765                         memcpy(Players[pnum].net_address, their->player.network.ipx.node, 6);
766         
767                 memcpy(NetPlayers.players[pnum].network.ipx.node, their->player.network.ipx.node, 6);
768                 memcpy(NetPlayers.players[pnum].network.ipx.server, their->player.network.ipx.server, 4);
769         } else {
770                 NetPlayers.players[pnum].network.appletalk.node = their->player.network.appletalk.node;
771                 NetPlayers.players[pnum].network.appletalk.net = their->player.network.appletalk.net;
772                 NetPlayers.players[pnum].network.appletalk.socket = their->player.network.appletalk.socket;
773         }
774
775         Players[pnum].n_packets_got = 0;
776         Players[pnum].connected = 1;
777         Players[pnum].net_kills_total = 0;
778         Players[pnum].net_killed_total = 0;
779         memset(kill_matrix[pnum], 0, MAX_PLAYERS*sizeof(short)); 
780         Players[pnum].score = 0;
781         Players[pnum].flags = 0;
782         Players[pnum].KillGoalCount=0;
783
784         if (pnum == N_players)
785         {
786                 N_players++;
787                 Netgame.numplayers = N_players;
788         }
789
790         digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
791
792    ClipRank (&their->player.rank);
793    
794    if (FindArg("-norankings"))
795           HUD_init_message("'%s' %s\n",their->player.callsign, TXT_JOINING);
796    else   
797      HUD_init_message("%s'%s' %s\n",RankStrings[their->player.rank],their->player.callsign, TXT_JOINING);
798         
799         multi_make_ghost_player(pnum);
800
801         multi_send_score();
802         multi_sort_kill_list();
803
804 //      create_player_appearance_effect(&Objects[objnum]);
805 }
806
807 char RefuseThisPlayer=0,WaitForRefuseAnswer=0,RefuseTeam;
808 char RefusePlayerName[12];
809 fix RefuseTimeLimit=0;
810
811 void network_welcome_player(sequence_packet *their)
812 {
813         // Add a player to a game already in progress
814         ubyte local_address[6];
815         int player_num;
816         int i;
817
818    WaitForRefuseAnswer=0;
819
820         if (FindArg("-NoMatrixCheat"))
821         {
822                 if ((their->player.version_minor & 0x0F) < 3)
823                 {
824                                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_DORK);
825                                         return;
826                 }
827         }
828
829         if (HoardEquipped())
830         {
831    // If hoard game, and this guy isn't D2 Christmas (v1.2), dump him
832
833            if ((Game_mode & GM_HOARD) && ((their->player.version_minor & 0x0F)<2))
834                 {
835                         if (Network_game_type == IPX_GAME)
836                                 network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_DORK);
837                         #ifdef MACINTOSH
838                         else
839                                 network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_DORK);
840                         #endif
841                         return;
842                 }
843         }
844
845         // Don't accept new players if we're ending this level.  Its safe to
846         // ignore since they'll request again later
847
848         if ((Endlevel_sequence) || (Control_center_destroyed))
849         {
850                 mprintf((0, "Ignored request from new player to join during endgame.\n"));
851                 if (Network_game_type == IPX_GAME)
852                         network_dump_player(their->player.network.ipx.server,their->player.network.ipx.node, DUMP_ENDLEVEL);
853                 #ifdef MACINTOSH
854                 else
855                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_ENDLEVEL);
856                 #endif
857                 return; 
858         }
859
860         if (Network_send_objects || Network_sending_extras)
861         {
862                 // Ignore silently, we're already responding to someone and we can't
863                 // do more than one person at a time.  If we don't dump them they will
864                 // re-request in a few seconds.
865                 return;
866         }
867
868         if (their->player.connected != Current_level_num)
869         {
870                 mprintf((0, "Dumping player due to old level number.\n"));
871                 if (Network_game_type == IPX_GAME)
872                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_LEVEL);
873                 #ifdef MACINTOSH
874                 else
875                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_LEVEL);
876                 #endif
877                 return;
878         }
879
880         player_num = -1;
881         memset(&Network_player_rejoining, 0, sizeof(sequence_packet));
882         Network_player_added = 0;
883
884         if (Network_game_type == IPX_GAME) {
885                 if ( (*(uint *)their->player.network.ipx.server) != 0 )
886                         ipx_get_local_target( their->player.network.ipx.server, their->player.network.ipx.node, local_address );
887                 else
888                         memcpy(local_address, their->player.network.ipx.node, 6);
889         }
890
891         for (i = 0; i < N_players; i++)
892         {
893                 if ( (Network_game_type == IPX_GAME) && (!stricmp(Players[i].callsign, their->player.callsign )) && (!memcmp(Players[i].net_address,local_address, 6)) ) 
894                 {
895                         player_num = i;
896                         break;
897                 }
898 #ifdef MACINTOSH                // note link to above if
899                         else if ( (!stricmp(Players[i].callsign, their->player.callsign)) &&
900                                     (NetPlayers.players[i].network.appletalk.node == their->player.network.appletalk.node) &&
901                                         (NetPlayers.players[i].network.appletalk.net == their->player.network.appletalk.net)) {
902                         player_num = i;
903                         break;
904                 }
905 #endif
906         }
907
908         if (player_num == -1)
909         {
910                 // Player is new to this game
911
912                 if ( !(Netgame.game_flags & NETGAME_FLAG_CLOSED) && (N_players < MaxNumNetPlayers))
913                 {
914                         // Add player in an open slot, game not full yet
915
916                         player_num = N_players;
917                         Network_player_added = 1;
918                 }
919                 else if (Netgame.game_flags & NETGAME_FLAG_CLOSED)
920                 {
921                         // Slots are open but game is closed
922
923                         if (Network_game_type == IPX_GAME)
924                                 network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_CLOSED);
925                         #ifdef MACINTOSH
926                         else
927                                 network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_CLOSED);
928                         #endif
929                         return;
930                 }
931                 else
932                 {
933                         // Slots are full but game is open, see if anyone is
934                         // disconnected and replace the oldest player with this new one
935                 
936                         int oldest_player = -1;
937                         fix oldest_time = timer_get_approx_seconds();
938
939                         Assert(N_players == MaxNumNetPlayers);
940
941                         for (i = 0; i < N_players; i++)
942                         {
943                                 if ( (!Players[i].connected) && (LastPacketTime[i] < oldest_time))
944                                 {
945                                         oldest_time = LastPacketTime[i];
946                                         oldest_player = i;
947                                 }
948                         }
949
950                         if (oldest_player == -1)
951                         {
952                                 // Everyone is still connected 
953
954                                 if (Network_game_type == IPX_GAME)
955                                         network_dump_player(their->player.network.ipx.server, their->player.network.ipx.node, DUMP_FULL);
956                                 #ifdef MACINTOSH
957                                 else
958                                         network_dump_appletalk_player(their->player.network.appletalk.node, their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_FULL);
959                                 #endif
960                                 return;
961                         }
962                         else
963                         {       
964                                 // Found a slot!
965
966                                 player_num = oldest_player;
967                                 Network_player_added = 1;
968                         }
969                 }
970         }
971         else 
972         {
973                 // Player is reconnecting
974                 
975                 if (Players[player_num].connected)
976                 {
977                         mprintf((0, "Extra REQUEST from player ignored.\n"));
978                         return;
979                 }
980
981                 if (Newdemo_state == ND_STATE_RECORDING)
982                         newdemo_record_multi_reconnect(player_num);
983
984                 Network_player_added = 0;
985
986                 digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
987                 
988                 if (FindArg("-norankings"))
989                         HUD_init_message("'%s' %s", Players[player_num].callsign, TXT_REJOIN);
990                 else
991                         HUD_init_message("%s'%s' %s", RankStrings[NetPlayers.players[player_num].rank],Players[player_num].callsign, TXT_REJOIN);
992         }
993
994         Players[player_num].KillGoalCount=0;
995
996         // Send updated Objects data to the new/returning player
997
998         
999         Network_player_rejoining = *their;
1000         Network_player_rejoining.player.connected = player_num;
1001         Network_send_objects = 1;
1002         Network_send_objnum = -1;
1003
1004         network_send_objects();
1005 }
1006
1007 int network_objnum_is_past(int objnum)
1008 {
1009         // determine whether or not a given object number has already been sent
1010         // to a re-joining player.
1011         
1012         int player_num = Network_player_rejoining.player.connected;
1013         int obj_mode = !((object_owner[objnum] == -1) || (object_owner[objnum] == player_num));
1014
1015         if (!Network_send_objects)
1016                 return 0; // We're not sending objects to a new player
1017
1018         if (obj_mode > Network_send_object_mode)
1019                 return 0;
1020         else if (obj_mode < Network_send_object_mode)
1021                 return 1;
1022         else if (objnum < Network_send_objnum)
1023                 return 1;
1024         else
1025                 return 0;
1026 }
1027
1028 #define OBJ_PACKETS_PER_FRAME 1
1029 extern void multi_send_active_door(char);
1030 extern void multi_send_door_open_specific(int,int,int,ubyte);
1031
1032
1033 void network_send_door_updates(int pnum)
1034 {
1035         // Send door status when new player joins
1036         
1037         int i;
1038
1039 //   Assert (pnum>-1 && pnum<N_players);
1040
1041         for (i = 0; i < Num_walls; i++)
1042         {
1043       if ((Walls[i].type == WALL_DOOR) && ((Walls[i].state == WALL_DOOR_OPENING) || (Walls[i].state == WALL_DOOR_WAITING) || (Walls[i].state == WALL_DOOR_OPEN)))
1044                         multi_send_door_open_specific(pnum,Walls[i].segnum, Walls[i].sidenum,Walls[i].flags);
1045                 else if ((Walls[i].type == WALL_BLASTABLE) && (Walls[i].flags & WALL_BLASTED))
1046                         multi_send_door_open_specific(pnum,Walls[i].segnum, Walls[i].sidenum,Walls[i].flags);
1047                 else if ((Walls[i].type == WALL_BLASTABLE) && (Walls[i].hps != WALL_HPS))
1048                         multi_send_hostage_door_status(i);
1049                 else
1050                         multi_send_wall_status_specific(pnum,i,Walls[i].type,Walls[i].flags,Walls[i].state);
1051         }
1052 }
1053
1054 extern vms_vector MarkerPoint[];
1055 void network_send_markers()
1056  {
1057   // send marker positions/text to new player
1058
1059   
1060   int i;
1061
1062   for (i = 0; i < N_players; i++)
1063    {
1064     if (MarkerObject[(i*2)]!=-1)
1065      multi_send_drop_marker (i,MarkerPoint[(i*2)],0,MarkerMessage[i*2]);
1066     if (MarkerObject[(i*2)+1]!=-1)
1067      multi_send_drop_marker (i,MarkerPoint[(i*2)+1],1,MarkerMessage[(i*2)+1]);
1068    }
1069  }
1070
1071 void network_process_monitor_vector(int vector)
1072 {
1073         int i, j;
1074         int count = 0;
1075         segment *seg;
1076         
1077         for (i=0; i <= Highest_segment_index; i++)
1078         {
1079                 int tm, ec, bm;
1080                 seg = &Segments[i];
1081                 for (j = 0; j < 6; j++)
1082                 {
1083                         if ( ((tm = seg->sides[j].tmap_num2) != 0) &&
1084                                   ((ec = TmapInfo[tm&0x3fff].eclip_num) != -1) &&
1085                                   ((bm = Effects[ec].dest_bm_num) != -1) )
1086                         {
1087                                 if (vector & (1 << count))
1088                                 {
1089                                         seg->sides[j].tmap_num2 = bm | (tm&0xc000);
1090                                 //      mprintf((0, "Monitor %d blown up.\n", count));
1091                                 }
1092                                 //else
1093                                   //    mprintf((0, "Monitor %d intact.\n", count));
1094                                 count++;
1095                                 Assert(count < 32);
1096                         }
1097                 }
1098         }
1099 }
1100
1101 int network_create_monitor_vector(void)
1102 {
1103         int i, j, k;
1104         int num_blown_bitmaps = 0;
1105         int monitor_num = 0;
1106         #define NUM_BLOWN_BITMAPS 20
1107         int blown_bitmaps[NUM_BLOWN_BITMAPS];
1108         int vector = 0;
1109         segment *seg;
1110
1111         for (i=0; i < Num_effects; i++)
1112         {
1113                 if (Effects[i].dest_bm_num > 0) {
1114                         for (j = 0; j < num_blown_bitmaps; j++)
1115                                 if (blown_bitmaps[j] == Effects[i].dest_bm_num)
1116                                         break;
1117                         if (j == num_blown_bitmaps) {
1118                                 blown_bitmaps[num_blown_bitmaps++] = Effects[i].dest_bm_num;
1119                                 Assert(num_blown_bitmaps < NUM_BLOWN_BITMAPS);
1120                         }
1121                 }
1122         }               
1123                 
1124 //      for (i = 0; i < num_blown_bitmaps; i++)
1125 //              mprintf((0, "Blown bitmap #%d = %d.\n", i, blown_bitmaps[i]));
1126
1127         for (i=0; i <= Highest_segment_index; i++)
1128         {
1129                 int tm, ec;
1130                 seg = &Segments[i];
1131                 for (j = 0; j < 6; j++)
1132                 {
1133                         if ((tm = seg->sides[j].tmap_num2) != 0) 
1134                         {
1135                                 if ( ((ec = TmapInfo[tm&0x3fff].eclip_num) != -1) &&
1136                                           (Effects[ec].dest_bm_num != -1) )
1137                                 {
1138                                 //      mprintf((0, "Monitor %d intact.\n", monitor_num));
1139                                         monitor_num++;
1140                                         Assert(monitor_num < 32);
1141                                 }
1142                                 else
1143                                 {
1144                                         for (k = 0; k < num_blown_bitmaps; k++)
1145                                         {
1146                                                 if ((tm&0x3fff) == blown_bitmaps[k])
1147                                                 {
1148                                                         //mprintf((0, "Monitor %d destroyed.\n", monitor_num));
1149                                                         vector |= (1 << monitor_num);
1150                                                         monitor_num++;
1151                                                         Assert(monitor_num < 32);
1152                                                         break;
1153                                                 }
1154                                         }
1155                                 }
1156                         }
1157                 }
1158         }
1159   //    mprintf((0, "Final monitor vector %x.\n", vector));
1160         return(vector);
1161 }
1162
1163 void network_stop_resync(sequence_packet *their)
1164 {
1165         if (Network_game_type == IPX_GAME) {
1166                 if ( (!memcmp(Network_player_rejoining.player.network.ipx.node, their->player.network.ipx.node, 6)) &&
1167                           (!memcmp(Network_player_rejoining.player.network.ipx.server, their->player.network.ipx.server, 4)) &&
1168                      (!stricmp(Network_player_rejoining.player.callsign, their->player.callsign)) )
1169                 {
1170                         mprintf((0, "Aborting resync for player %s.\n", their->player.callsign));
1171                         Network_send_objects = 0;
1172                         Network_sending_extras=0;
1173                         Network_rejoined=0;
1174                         Player_joining_extras=-1;
1175                         Network_send_objnum = -1;
1176                 }
1177         } else {
1178                 if ( (Network_player_rejoining.player.network.appletalk.node == their->player.network.appletalk.node) &&
1179                          (Network_player_rejoining.player.network.appletalk.net == their->player.network.appletalk.net) &&
1180                          (!stricmp(Network_player_rejoining.player.callsign, their->player.callsign)) )
1181                 {
1182                         mprintf((0, "Aborting resync for player %s.\n", their->player.callsign));
1183                         Network_send_objects = 0;
1184                         Network_sending_extras=0;
1185                         Network_rejoined=0;
1186                         Player_joining_extras=-1;
1187                         Network_send_objnum = -1;
1188                 }
1189         }
1190 }
1191
1192 ubyte object_buffer[IPX_MAX_DATA_SIZE];
1193
1194 void network_send_objects(void)
1195 {
1196         short remote_objnum;
1197         sbyte owner;
1198         int loc, i, h;
1199
1200         static int obj_count = 0;
1201         static int frame_num = 0;
1202
1203         int obj_count_frame = 0;
1204         int player_num = Network_player_rejoining.player.connected;
1205
1206         // Send clear objects array trigger and send player num
1207
1208         Assert(Network_send_objects != 0);
1209         Assert(player_num >= 0);
1210         Assert(player_num < MaxNumNetPlayers);
1211
1212         if (Endlevel_sequence || Control_center_destroyed)
1213         {
1214                 // Endlevel started before we finished sending the goods, we'll
1215                 // have to stop and try again after the level.
1216
1217                 if (Network_game_type == IPX_GAME)
1218                         network_dump_player(Network_player_rejoining.player.network.ipx.server,Network_player_rejoining.player.network.ipx.node, DUMP_ENDLEVEL);
1219                 #ifdef MACINTOSH
1220                 else
1221                         network_dump_appletalk_player(Network_player_rejoining.player.network.appletalk.node,Network_player_rejoining.player.network.appletalk.net, Network_player_rejoining.player.network.appletalk.socket, DUMP_ENDLEVEL);
1222                 #endif
1223                 Network_send_objects = 0; 
1224                 return;
1225         }
1226
1227         for (h = 0; h < OBJ_PACKETS_PER_FRAME; h++) // Do more than 1 per frame, try to speed it up without
1228                                                                                                                           // over-stressing the receiver.
1229         {
1230                 obj_count_frame = 0;
1231                 memset(object_buffer, 0, IPX_MAX_DATA_SIZE);
1232                 object_buffer[0] = PID_OBJECT_DATA;
1233                 loc = 3;
1234         
1235                 if (Network_send_objnum == -1)
1236                 {
1237                         obj_count = 0;
1238                         Network_send_object_mode = 0;
1239 //       mprintf((0, "Sending object array to player %d.\n", player_num));
1240                         *(short *)(object_buffer+loc) = INTEL_SHORT(-1);            loc += 2;
1241                         object_buffer[loc] = player_num;                            loc += 1;
1242                         /* Placeholder for remote_objnum, not used here */          loc += 2;
1243                         Network_send_objnum = 0;
1244                         obj_count_frame = 1;
1245                         frame_num = 0;
1246                 }
1247                 
1248                 for (i = Network_send_objnum; i <= Highest_object_index; i++)
1249                 {
1250                         if ((Objects[i].type != OBJ_POWERUP) && (Objects[i].type != OBJ_PLAYER) &&
1251                                  (Objects[i].type != OBJ_CNTRLCEN) && (Objects[i].type != OBJ_GHOST) &&
1252                                  (Objects[i].type != OBJ_ROBOT) && (Objects[i].type != OBJ_HOSTAGE) &&
1253                                  !(Objects[i].type==OBJ_WEAPON && Objects[i].id==PMINE_ID))
1254                                 continue;
1255                         if ((Network_send_object_mode == 0) && ((object_owner[i] != -1) && (object_owner[i] != player_num)))
1256                                 continue;
1257                         if ((Network_send_object_mode == 1) && ((object_owner[i] == -1) || (object_owner[i] == player_num)))
1258                                 continue;
1259
1260                         if ( ((IPX_MAX_DATA_SIZE-1) - loc) < (sizeof(object)+5) )
1261                                 break; // Not enough room for another object
1262
1263                         obj_count_frame++;
1264                         obj_count++;
1265         
1266                         remote_objnum = objnum_local_to_remote((short)i, &owner);
1267                         Assert(owner == object_owner[i]);
1268
1269                         *(short *)(object_buffer+loc) = INTEL_SHORT((short)i);      loc += 2;
1270                         object_buffer[loc] = owner;                                 loc += 1;
1271                         *(short *)(object_buffer+loc) = INTEL_SHORT(remote_objnum); loc += 2;
1272                         memcpy(&object_buffer[loc], &Objects[i], sizeof(object));
1273                         if (Network_game_type == IPX_GAME)
1274                                 swap_object((object *)&object_buffer[loc]);
1275                         loc += sizeof(object);
1276 //                      mprintf((0, "..packing object %d, remote %d\n", i, remote_objnum));
1277                 }
1278
1279                 if (obj_count_frame) // Send any objects we've buffered
1280                 {
1281                         frame_num++;
1282         
1283                         Network_send_objnum = i;
1284                         object_buffer[1] = obj_count_frame;  object_buffer[2] = frame_num;
1285 //       mprintf((0, "Object packet %d contains %d objects.\n", frame_num, obj_count_frame));
1286
1287                         Assert(loc <= IPX_MAX_DATA_SIZE);
1288
1289                         if (Network_game_type == IPX_GAME)
1290                                 ipx_send_internetwork_packet_data( object_buffer, loc, Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node );
1291                         #ifdef MACINTOSH
1292                         else
1293                                 appletalk_send_packet_data( object_buffer, loc, Network_player_rejoining.player.network.appletalk.node,
1294                                         Network_player_rejoining.player.network.appletalk.net,
1295                                         Network_player_rejoining.player.network.appletalk.socket);
1296                         #endif
1297
1298                         // OLD ipx_send_packet_data(object_buffer, loc, &Network_player_rejoining.player.node);
1299                 }
1300
1301                 if (i > Highest_object_index)
1302                 {
1303                         if (Network_send_object_mode == 0)
1304                         {
1305                                 Network_send_objnum = 0;
1306                                 Network_send_object_mode = 1; // go to next mode
1307                         }
1308                         else 
1309                         {
1310                                 Assert(Network_send_object_mode == 1); 
1311
1312                                 frame_num++;
1313                                 // Send count so other side can make sure he got them all
1314 //                              mprintf((0, "Sending end marker in packet #%d.\n", frame_num));
1315                                 mprintf((0, "Sent %d objects.\n", obj_count));
1316                                 object_buffer[0] = PID_OBJECT_DATA;
1317                                 object_buffer[1] = 1;
1318                                 object_buffer[2] = frame_num;
1319                                 *(short *)(object_buffer+3) = INTEL_SHORT(-2);
1320                                 *(short *)(object_buffer+6) = INTEL_SHORT(obj_count);
1321                                 //OLD ipx_send_packet_data(object_buffer, 8, &Network_player_rejoining.player.node);
1322                                 if (Network_game_type == IPX_GAME)
1323                                         ipx_send_internetwork_packet_data(object_buffer, 8, Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1324                                 #ifdef MACINTOSH
1325                                 else
1326                                         appletalk_send_packet_data( object_buffer, 8, Network_player_rejoining.player.network.appletalk.node,
1327                                                                                                 Network_player_rejoining.player.network.appletalk.net,
1328                                                                                                 Network_player_rejoining.player.network.appletalk.socket);
1329                                 #endif
1330                                 
1331                         
1332                                 // Send sync packet which tells the player who he is and to start!
1333                                 network_send_rejoin_sync(player_num);
1334                                 mprintf ((0,"VerfiyPlayerJoined is now set to %d\n",player_num));
1335                                 VerifyPlayerJoined=player_num;
1336
1337                                 // Turn off send object mode
1338                                 Network_send_objnum = -1;
1339                                 Network_send_objects = 0;
1340                                 obj_count = 0;
1341
1342                                 //if (!network_i_am_master ())
1343                                 // Int3();  // Bad!! Get Jason.  Someone goofy is trying to get ahold of the game!
1344
1345                                 Network_sending_extras=40; // start to send extras
1346                            Player_joining_extras=player_num;
1347
1348                                 return;
1349                         } // mode == 1;
1350                 } // i > Highest_object_index
1351         } // For PACKETS_PER_FRAME
1352 }
1353
1354 extern void multi_send_powerup_update();
1355
1356 void network_send_rejoin_sync(int player_num)
1357 {
1358         int i, j;
1359
1360         Players[player_num].connected = 1; // connect the new guy
1361         LastPacketTime[player_num] = timer_get_approx_seconds();
1362
1363         if (Endlevel_sequence || Control_center_destroyed)
1364         {
1365                 // Endlevel started before we finished sending the goods, we'll
1366                 // have to stop and try again after the level.
1367
1368                 if (Network_game_type == IPX_GAME)
1369                         network_dump_player(Network_player_rejoining.player.network.ipx.server,Network_player_rejoining.player.network.ipx.node, DUMP_ENDLEVEL);
1370                 #ifdef MACINTOSH
1371                 else
1372                         network_dump_appletalk_player(Network_player_rejoining.player.network.appletalk.node,Network_player_rejoining.player.network.appletalk.net, Network_player_rejoining.player.network.appletalk.socket, DUMP_ENDLEVEL);
1373                 #endif
1374                 Network_send_objects = 0; 
1375                 Network_sending_extras=0;
1376                 return;
1377         }
1378
1379         if (Network_player_added)
1380         {
1381                 Network_player_rejoining.type = PID_ADDPLAYER;
1382                 Network_player_rejoining.player.connected = player_num;
1383                 network_new_player(&Network_player_rejoining);
1384
1385                 for (i = 0; i < N_players; i++)
1386                 {
1387                         if ((i != player_num) && (i != Player_num) && (Players[i].connected))
1388                                 if (Network_game_type == IPX_GAME) {
1389                                         send_sequence_packet( Network_player_rejoining, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, Players[i].net_address);
1390                                 #ifdef MACINTOSH
1391                                 } else {
1392                                         appletalk_send_packet_data( (ubyte *)&Network_player_rejoining, sizeof(sequence_packet), NetPlayers.players[i].network.appletalk.node,
1393                                                                                                 NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket);
1394                                 #endif
1395                                 }
1396                 }
1397         }       
1398
1399         // Send sync packet to the new guy
1400
1401         network_update_netgame();
1402
1403         // Fill in the kill list
1404         for (j=0; j<MAX_PLAYERS; j++)
1405         {
1406                 for (i=0; i<MAX_PLAYERS;i++)
1407                         Netgame.kills[j][i] = kill_matrix[j][i];
1408                 Netgame.killed[j] = Players[j].net_killed_total;
1409                 Netgame.player_kills[j] = Players[j].net_kills_total;
1410                 Netgame.player_score[j] = Players[j].score;
1411         }       
1412
1413         Netgame.level_time = Players[Player_num].time_level;
1414         Netgame.monitor_vector = network_create_monitor_vector();
1415
1416         mprintf((0, "Sending rejoin sync packet!!!\n"));
1417
1418         if (Network_game_type == IPX_GAME) {
1419                 send_internetwork_full_netgame_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1420                 send_netplayers_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1421         #ifdef MACINTOSH
1422         } else {
1423                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.appletalk.node,
1424                                                                         Network_player_rejoining.player.network.appletalk.net,
1425                                                                         Network_player_rejoining.player.network.appletalk.socket);
1426                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.appletalk.node,
1427                                                                         Network_player_rejoining.player.network.appletalk.net,
1428                                                                         Network_player_rejoining.player.network.appletalk.socket);
1429         #endif
1430         }
1431         return;
1432 }
1433 void resend_sync_due_to_packet_loss_for_allender ()
1434 {
1435    int i,j;
1436
1437    mprintf ((0,"I'm resending a sync packet! VPJ=%d\n",VerifyPlayerJoined));
1438   
1439         network_update_netgame();
1440
1441         // Fill in the kill list
1442         for (j=0; j<MAX_PLAYERS; j++)
1443         {
1444                 for (i=0; i<MAX_PLAYERS;i++)
1445                         Netgame.kills[j][i] = kill_matrix[j][i];
1446                 Netgame.killed[j] = Players[j].net_killed_total;
1447                 Netgame.player_kills[j] = Players[j].net_kills_total;
1448                 Netgame.player_score[j] = Players[j].score;
1449         }       
1450
1451         Netgame.level_time = Players[Player_num].time_level;
1452         Netgame.monitor_vector = network_create_monitor_vector();
1453
1454         if (Network_game_type == IPX_GAME) {
1455                 send_internetwork_full_netgame_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1456                 send_netplayers_packet(Network_player_rejoining.player.network.ipx.server, Network_player_rejoining.player.network.ipx.node);
1457         #ifdef MACINTOSH
1458         } else {
1459                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), Network_player_rejoining.player.network.appletalk.node,
1460                                                                         Network_player_rejoining.player.network.appletalk.net,
1461                                                                         Network_player_rejoining.player.network.appletalk.socket);
1462                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), Network_player_rejoining.player.network.appletalk.node,
1463                                                                         Network_player_rejoining.player.network.appletalk.net,
1464                                                                         Network_player_rejoining.player.network.appletalk.socket);
1465         #endif
1466         }
1467 }
1468
1469
1470 char * network_get_player_name( int objnum )
1471 {
1472         if ( objnum < 0 ) return NULL; 
1473         if ( Objects[objnum].type != OBJ_PLAYER ) return NULL;
1474         if ( Objects[objnum].id >= MAX_PLAYERS ) return NULL;
1475         if ( Objects[objnum].id >= N_players ) return NULL;
1476         
1477         return Players[Objects[objnum].id].callsign;
1478 }
1479
1480
1481 void network_add_player(sequence_packet *p)
1482 {
1483         int i;
1484         
1485         mprintf((0, "Got add player request!\n"));
1486
1487         for (i=0; i<N_players; i++ )    {
1488                 if (Network_game_type == IPX_GAME) {
1489                         if ( !memcmp( NetPlayers.players[i].network.ipx.node, p->player.network.ipx.node, 6) && !memcmp(NetPlayers.players[i].network.ipx.server, p->player.network.ipx.server, 4)) 
1490                                 return;         // already got them
1491                 } else {
1492                         if ( (NetPlayers.players[i].network.appletalk.node == p->player.network.appletalk.node) &&
1493                                  (NetPlayers.players[i].network.appletalk.net == p->player.network.appletalk.net))
1494                                         return;
1495                 }
1496         }
1497
1498         if (Network_game_type == IPX_GAME) {
1499                 memcpy( NetPlayers.players[N_players].network.ipx.node, p->player.network.ipx.node, 6 );
1500                 memcpy( NetPlayers.players[N_players].network.ipx.server, p->player.network.ipx.server, 4 );
1501         } else {
1502                 NetPlayers.players[N_players].network.appletalk.node = p->player.network.appletalk.node;
1503                 NetPlayers.players[N_players].network.appletalk.net = p->player.network.appletalk.net;
1504                 NetPlayers.players[N_players].network.appletalk.socket = p->player.network.appletalk.socket;
1505         }
1506    
1507    ClipRank (&p->player.rank);
1508   
1509         memcpy( NetPlayers.players[N_players].callsign, p->player.callsign, CALLSIGN_LEN+1 );
1510         NetPlayers.players[N_players].version_major=p->player.version_major;
1511         NetPlayers.players[N_players].version_minor=p->player.version_minor;
1512    NetPlayers.players[N_players].rank=p->player.rank;
1513         NetPlayers.players[N_players].connected = 1;
1514    network_check_for_old_version (N_players);
1515
1516         Players[N_players].KillGoalCount=0;
1517         Players[N_players].connected = 1;
1518         LastPacketTime[N_players] = timer_get_approx_seconds();
1519         N_players++;
1520         Netgame.numplayers = N_players;
1521
1522         // Broadcast updated info
1523
1524    mprintf ((0,"sending_game_info!\n"));
1525         network_send_game_info(NULL);
1526 }
1527
1528 // One of the players decided not to join the game
1529
1530 void network_remove_player(sequence_packet *p)
1531 {
1532         int i,pn;
1533         
1534         pn = -1;
1535         for (i=0; i<N_players; i++ )    {
1536                 if (Network_game_type == IPX_GAME) {
1537                         if (!memcmp(NetPlayers.players[i].network.ipx.node, p->player.network.ipx.node, 6) && !memcmp(NetPlayers.players[i].network.ipx.server, p->player.network.ipx.server, 4)) {
1538                                 pn = i;
1539                                 break;
1540                         }
1541                 } else {
1542                         if ( (NetPlayers.players[i].network.appletalk.node == p->player.network.appletalk.node) && (NetPlayers.players[i].network.appletalk.net == p->player.network.appletalk.net) ) {
1543                                 pn = i;
1544                                 break;
1545                         }
1546                 }
1547         }
1548         
1549         if (pn < 0 ) return;
1550
1551         for (i=pn; i<N_players-1; i++ ) {
1552                 if (Network_game_type == IPX_GAME) {
1553                         memcpy( NetPlayers.players[i].network.ipx.node, NetPlayers.players[i+1].network.ipx.node, 6 );
1554                         memcpy( NetPlayers.players[i].network.ipx.server, NetPlayers.players[i+1].network.ipx.server, 4 );
1555                 } else {
1556                         NetPlayers.players[i].network.appletalk.node = NetPlayers.players[i+1].network.appletalk.node;
1557                         NetPlayers.players[i].network.appletalk.net = NetPlayers.players[i+1].network.appletalk.net;
1558                         NetPlayers.players[i].network.appletalk.socket = NetPlayers.players[i+1].network.appletalk.socket;
1559                 }
1560                 memcpy( NetPlayers.players[i].callsign, NetPlayers.players[i+1].callsign, CALLSIGN_LEN+1 );
1561                 NetPlayers.players[i].version_major=NetPlayers.players[i+1].version_major;
1562                 NetPlayers.players[i].version_minor=NetPlayers.players[i+1].version_minor;
1563
1564            NetPlayers.players[i].rank=NetPlayers.players[i+1].rank;
1565                 ClipRank (&NetPlayers.players[i].rank);
1566            network_check_for_old_version(i);    
1567         }
1568                 
1569         N_players--;
1570         Netgame.numplayers = N_players;
1571
1572         // Broadcast new info
1573
1574         network_send_game_info(NULL);
1575
1576 }
1577
1578 void
1579 network_dump_player(ubyte * server, ubyte *node, int why)
1580 {
1581         // Inform player that he was not chosen for the netgame
1582
1583         sequence_packet temp;
1584
1585         temp.type = PID_DUMP;
1586         memcpy(temp.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
1587         temp.player.connected = why;
1588         if (Network_game_type == IPX_GAME) {
1589                 send_internetwork_sequence_packet(temp, server, node);
1590         } else {
1591                 Int3();
1592         }
1593 }
1594
1595 #ifdef MACINTOSH
1596 void network_dump_appletalk_player(ubyte node, ushort net, ubyte socket, int why)
1597 {
1598         sequence_packet temp;
1599
1600         temp.type = PID_DUMP;
1601         memcpy(temp.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
1602         temp.player.connected = why;
1603         if (Network_game_type == APPLETALK_GAME) {
1604                 appletalk_send_packet_data( (ubyte *)&temp, sizeof(sequence_packet), node, net, socket );
1605         } else {
1606                 Int3();
1607         }
1608 }
1609 #endif
1610
1611 void
1612 network_send_game_list_request()
1613 {
1614         // Send a broadcast request for game info
1615
1616         sequence_packet me;
1617
1618         mprintf((0, "Sending game_list request.\n"));
1619         me.type = PID_GAME_LIST;
1620         memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
1621
1622         if (Network_game_type == IPX_GAME) {
1623                 memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
1624                 memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
1625
1626                 send_broadcast_sequence_packet(me);
1627         #ifdef MACINTOSH
1628         } else {
1629                 me.player.network.appletalk.node = appletalk_get_my_node();
1630                 me.player.network.appletalk.net = appletalk_get_my_net();
1631                 me.player.network.appletalk.socket = appletalk_get_my_socket();
1632                 appletalk_send_game_info( (ubyte *)&me, sizeof(sequence_packet), Network_zone_name );
1633         #endif
1634         }
1635 }
1636
1637 void network_send_all_info_request(char type,int which_security)
1638 {
1639         // Send a broadcast request for game info
1640
1641         sequence_packet me;
1642
1643         mprintf((0, "Sending all_info request.\n"));
1644    
1645         me.Security=which_security;
1646         me.type = type;
1647         memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
1648         
1649         if (Network_game_type == IPX_GAME) {
1650                 memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
1651                 memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
1652
1653                 send_broadcast_sequence_packet(me);
1654         #ifdef MACINTOSH
1655         } else {
1656                 me.player.network.appletalk.node = appletalk_get_my_node();
1657                 me.player.network.appletalk.net = appletalk_get_my_net();
1658                 me.player.network.appletalk.socket = appletalk_get_my_socket();
1659                 appletalk_send_game_info( (ubyte *)&me, sizeof(sequence_packet), Network_zone_name );
1660         #endif
1661         }
1662 }
1663
1664
1665 void
1666 network_update_netgame(void)
1667 {
1668         // Update the netgame struct with current game variables
1669
1670         int i, j;
1671
1672    Netgame.numconnected=0;
1673    for (i=0;i<N_players;i++)
1674          if (Players[i].connected)
1675                 Netgame.numconnected++;
1676
1677 // This is great: D2 1.0 and 1.1 ignore upper part of the game_flags field of
1678 //      the lite_info struct when you're sitting on the join netgame screen.  We can
1679 //      "sneak" Hoard information into this field.  This is better than sending 
1680 //      another packet that could be lost in transit.
1681
1682
1683         if (HoardEquipped())
1684         {
1685                 if (Game_mode & GM_HOARD)
1686                 {
1687                         Netgame.game_flags |=NETGAME_FLAG_HOARD;
1688                         if (Game_mode & GM_TEAM)
1689                                 Netgame.game_flags |=NETGAME_FLAG_TEAM_HOARD;
1690                 }
1691         }
1692  
1693         if (Network_status == NETSTAT_STARTING)
1694                 return;
1695
1696         Netgame.numplayers = N_players;
1697         Netgame.game_status = Network_status;
1698         Netgame.max_numplayers = MaxNumNetPlayers;
1699
1700         for (i = 0; i < MAX_NUM_NET_PLAYERS; i++) 
1701         {
1702                 NetPlayers.players[i].connected = Players[i].connected;
1703                 for(j = 0; j < MAX_NUM_NET_PLAYERS; j++)
1704                         Netgame.kills[i][j] = kill_matrix[i][j];
1705
1706                 Netgame.killed[i] = Players[i].net_killed_total;
1707                 Netgame.player_kills[i] = Players[i].net_kills_total;
1708                 Netgame.player_score[i] = Players[i].score;
1709                 Netgame.player_flags[i] = (Players[i].flags & (PLAYER_FLAGS_BLUE_KEY | PLAYER_FLAGS_RED_KEY | PLAYER_FLAGS_GOLD_KEY));
1710         }
1711         Netgame.team_kills[0] = team_kills[0];
1712         Netgame.team_kills[1] = team_kills[1];
1713         Netgame.levelnum = Current_level_num;
1714
1715  
1716 }
1717
1718 void
1719 network_send_endlevel_sub(int player_num)
1720 {
1721         endlevel_info end;
1722         int i = 0;
1723 #ifdef WORDS_BIGENDIAN
1724         int j = 0;
1725 #endif
1726
1727         // Send an endlevel packet for a player
1728         end.type                = PID_ENDLEVEL;
1729         end.player_num = player_num;
1730         end.connected   = Players[player_num].connected;
1731         end.kills               = INTEL_SHORT(Players[player_num].net_kills_total);
1732         end.killed              = INTEL_SHORT(Players[player_num].net_killed_total);
1733         memcpy(end.kill_matrix, kill_matrix[player_num], MAX_PLAYERS*sizeof(short));
1734 #ifdef WORDS_BIGENDIAN
1735         for (i = 0; i < MAX_PLAYERS; i++)
1736                 for (j = 0; j < MAX_PLAYERS; j++)
1737                         end.kill_matrix[i][j] = INTEL_SHORT(end.kill_matrix[i][j]);
1738 #endif
1739
1740         if (Players[player_num].connected == 1) // Still playing
1741         {
1742                 Assert(Control_center_destroyed);
1743                 end.seconds_left = Countdown_seconds_left;
1744         }
1745
1746 //      mprintf((0, "Sending endlevel packet.\n"));
1747
1748         for (i = 0; i < N_players; i++)
1749         {       
1750                 if ((i != Player_num) && (i!=player_num) && (Players[i].connected)) {
1751                   if (Players[i].connected==1)
1752                          network_send_endlevel_short_sub(player_num,i);
1753                   else {
1754                         if (Network_game_type == IPX_GAME)
1755                                 ipx_send_packet_data((ubyte *)&end, sizeof(endlevel_info), NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address);
1756                         #ifdef MACINTOSH
1757                         else
1758                                 appletalk_send_packet_data( (ubyte *)&end, sizeof(endlevel_info), NetPlayers.players[i].network.appletalk.node,
1759                                                                                         NetPlayers.players[i].network.appletalk.net,
1760                                                                                         NetPlayers.players[i].network.appletalk.socket);
1761                         #endif
1762                         }       
1763                 }
1764         }
1765 }
1766
1767 /* Send an updated endlevel status to other hosts */
1768 void
1769 network_send_endlevel_packet(void)
1770 {
1771         network_send_endlevel_sub(Player_num);
1772 }
1773
1774
1775 /* Send an endlevel packet for a player */
1776 void
1777 network_send_endlevel_short_sub(int from_player_num,int to_player)
1778 {
1779         endlevel_info_short end;
1780
1781         end.type = PID_ENDLEVEL_SHORT;
1782         end.player_num = from_player_num;
1783         end.connected = Players[from_player_num].connected;
1784         end.seconds_left = Countdown_seconds_left;
1785
1786
1787         if (Players[from_player_num].connected == 1) // Still playing
1788         {
1789                 Assert(Control_center_destroyed);
1790         }
1791
1792         if ((to_player != Player_num) && (to_player!=from_player_num) && (Players[to_player].connected))
1793         {
1794                 mprintf((0, "Sending short endlevel packet to %s.\n",Players[to_player].callsign));
1795                 if (Network_game_type == IPX_GAME)
1796                         ipx_send_packet_data((ubyte *)&end, sizeof(endlevel_info_short), NetPlayers.players[to_player].network.ipx.server, NetPlayers.players[to_player].network.ipx.node,Players[to_player].net_address);
1797                 #ifdef MACINTOSH
1798                 else
1799                         appletalk_send_packet_data( (ubyte *)&end, sizeof(endlevel_info_short), NetPlayers.players[to_player].network.appletalk.node,
1800                                                                                 NetPlayers.players[to_player].network.appletalk.net,
1801                                                                                 NetPlayers.players[to_player].network.appletalk.socket);
1802                 #endif
1803         }
1804 }
1805
1806 extern fix ThisLevelTime;
1807
1808 void
1809 network_send_game_info(sequence_packet *their)
1810 {
1811         // Send game info to someone who requested it
1812
1813         char old_type, old_status;
1814    fix timevar;
1815    int i;
1816
1817         mprintf((0, "Sending game info.\n"));
1818
1819         network_update_netgame(); // Update the values in the netgame struct
1820
1821         old_type = Netgame.type;
1822         old_status = Netgame.game_status;
1823
1824         Netgame.type = PID_GAME_INFO;
1825    NetPlayers.type = PID_PLAYERSINFO;
1826
1827    NetPlayers.Security=Netgame.Security;
1828         Netgame.version_major=Version_major;
1829         Netgame.version_minor=Version_minor;
1830
1831         if (Endlevel_sequence || Control_center_destroyed)
1832                 Netgame.game_status = NETSTAT_ENDLEVEL;
1833
1834         if (Netgame.PlayTimeAllowed)
1835     {
1836                 timevar=i2f (Netgame.PlayTimeAllowed*5*60);
1837                 i=f2i(timevar-ThisLevelTime);
1838                 if (i<30)
1839                         Netgame.game_status=NETSTAT_ENDLEVEL;
1840         }       
1841
1842         if (!their) {
1843                 if (Network_game_type == IPX_GAME) {
1844                         send_broadcast_full_netgame_packet();
1845                         send_broadcast_netplayers_packet();
1846                 } // nothing to do for appletalk games I think....
1847         } else {
1848                 if (Network_game_type == IPX_GAME) {
1849                         send_internetwork_full_netgame_packet(their->player.network.ipx.server, their->player.network.ipx.node);
1850                         send_netplayers_packet(their->player.network.ipx.server, their->player.network.ipx.node);
1851                 #ifdef MACINTOSH
1852                 } else {
1853                         appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), their->player.network.appletalk.node,
1854                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1855                         appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), their->player.network.appletalk.node,
1856                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1857                 #endif
1858                 }
1859         }  
1860
1861         Netgame.type = old_type;
1862         Netgame.game_status = old_status;
1863 }       
1864
1865 void network_send_lite_info(sequence_packet *their)
1866 {
1867         // Send game info to someone who requested it
1868
1869         char old_type, old_status,oldstatus;
1870
1871         mprintf((0, "Sending lite game info.\n"));
1872
1873         network_update_netgame(); // Update the values in the netgame struct
1874
1875         old_type = Netgame.type;
1876         old_status = Netgame.game_status;
1877
1878         Netgame.type = PID_LITE_INFO;
1879
1880         if (Endlevel_sequence || Control_center_destroyed)
1881                 Netgame.game_status = NETSTAT_ENDLEVEL;
1882
1883 // If hoard mode, make this game look closed even if it isn't
1884    if (HoardEquipped())
1885         {
1886                 if (Game_mode & GM_HOARD)
1887                 {
1888                         oldstatus=Netgame.game_status;
1889                         Netgame.game_status=NETSTAT_ENDLEVEL;
1890                         Netgame.gamemode=NETGAME_CAPTURE_FLAG;
1891                         if (oldstatus==NETSTAT_ENDLEVEL)
1892                                 Netgame.game_flags|=NETGAME_FLAG_REALLY_ENDLEVEL;
1893                         if (oldstatus==NETSTAT_STARTING)
1894                                 Netgame.game_flags|=NETGAME_FLAG_REALLY_FORMING;
1895                 }
1896         }
1897
1898         if (!their) {
1899                 if (Network_game_type == IPX_GAME) {
1900                         send_broadcast_lite_netgame_packet();
1901                 }               // nothing to do for appletalk I think....
1902         } else {
1903                 if (Network_game_type == IPX_GAME) {
1904                         send_internetwork_lite_netgame_packet(their->player.network.ipx.server, their->player.network.ipx.node);
1905                 #ifdef MACINTOSH
1906                 } else {
1907                         appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(lite_info), their->player.network.appletalk.node,
1908                                                                                 their->player.network.appletalk.net, their->player.network.appletalk.socket );
1909                 #endif
1910                 }
1911         }  
1912
1913         //  Restore the pre-hoard mode
1914         if (HoardEquipped())
1915         {
1916                 if (Game_mode & GM_HOARD)
1917                 {
1918                         if (!(Game_mode & GM_TEAM))
1919                            Netgame.gamemode=NETGAME_HOARD;
1920                         else
1921                            Netgame.gamemode=NETGAME_TEAM_HOARD;
1922                         Netgame.game_flags&=~NETGAME_FLAG_REALLY_ENDLEVEL;
1923                         Netgame.game_flags&=~NETGAME_FLAG_REALLY_FORMING;
1924                         Netgame.game_flags&=~NETGAME_FLAG_TEAM_HOARD;
1925                 }
1926         }
1927
1928         Netgame.type = old_type;
1929         Netgame.game_status = old_status;
1930
1931 }       
1932
1933 /* Send game info to all players in this game */
1934 void network_send_netgame_update()
1935 {
1936         char old_type, old_status;
1937         int i;
1938
1939         mprintf((0, "Sending updated game info.\n"));
1940
1941         network_update_netgame(); // Update the values in the netgame struct
1942
1943         old_type = Netgame.type;
1944         old_status = Netgame.game_status;
1945
1946         Netgame.type = PID_GAME_UPDATE;
1947
1948         if (Endlevel_sequence || Control_center_destroyed)
1949                 Netgame.game_status = NETSTAT_ENDLEVEL;
1950  
1951         for (i=0; i<N_players; i++ )    {
1952                 if ( (Players[i].connected) && (i!=Player_num ) )       {
1953                         if (Network_game_type == IPX_GAME) {
1954                                 send_lite_netgame_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, Players[i].net_address);
1955                         #ifdef MACINTOSH
1956                         } else {
1957                                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(lite_info), NetPlayers.players[i].network.appletalk.node,
1958                                                                                         NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket );
1959                         #endif
1960                         }
1961                 }
1962         }
1963
1964         Netgame.type = old_type;
1965         Netgame.game_status = old_status;
1966 }       
1967                           
1968 int network_send_request(void)
1969 {
1970         // Send a request to join a game 'Netgame'.  Returns 0 if we can join this
1971         // game, non-zero if there is some problem.
1972         int i;
1973
1974         if (Netgame.numplayers < 1)
1975          return 1;
1976
1977         for (i = 0; i < MAX_NUM_NET_PLAYERS; i++)
1978           if (NetPlayers.players[i].connected)
1979               break;
1980
1981         Assert(i < MAX_NUM_NET_PLAYERS);
1982
1983         mprintf((0, "Sending game enroll request to player %d (%s). Serv=%x Node=%x Level=%d\n", i, Players[i].callsign,NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node,Netgame.levelnum));
1984
1985 //      segments_checksum = netmisc_calc_checksum( Segments, sizeof(segment)*(Highest_segment_index+1) );       
1986
1987         My_Seq.type = PID_REQUEST;
1988         My_Seq.player.connected = Current_level_num;
1989
1990         if (Network_game_type == IPX_GAME) {
1991                 send_internetwork_sequence_packet(My_Seq, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
1992         #ifdef MACINTOSH
1993         } else {
1994                 appletalk_send_packet_data( (ubyte *)&My_Seq, sizeof(sequence_packet), NetPlayers.players[i].network.appletalk.node,
1995                                                                         NetPlayers.players[i].network.appletalk.net,
1996                                                                         NetPlayers.players[i].network.appletalk.socket);
1997         #endif
1998         }
1999
2000         return i;
2001 }
2002
2003 int SecurityCheck=0;
2004         
2005 void network_process_gameinfo(ubyte *data)
2006 {
2007         int i, j;
2008         netgame_info *new = (netgame_info *)data;
2009 #ifdef WORDS_BIGENDIAN
2010         netgame_info tmp_info;
2011
2012         if (Network_game_type == IPX_GAME)  {
2013                 receive_netgame_packet(data, &tmp_info, 0);                     // get correctly aligned structure
2014                 new = &tmp_info;
2015         }
2016 #endif
2017         
2018
2019    WaitingForPlayerInfo=0;
2020
2021    if (new->Security !=TempPlayersInfo->Security)
2022     {
2023      Int3();     // Get Jason
2024      return;     // If this first half doesn't go with the second half
2025     }
2026
2027         Network_games_changed = 1;
2028
2029    //mprintf((0, "Got game data for game %s.\n", new->game_name));
2030
2031    Assert (TempPlayersInfo!=NULL);
2032
2033         for (i = 0; i < num_active_games; i++)
2034          {
2035           //mprintf ((0,"GAMEINFO: Game %d is %s!\n",i,Active_games[i].game_name));
2036           
2037           if (!stricmp(Active_games[i].game_name, new->game_name) && 
2038                                   Active_games[i].Security==new->Security)
2039                break;
2040          }
2041
2042         if (i == MAX_ACTIVE_NETGAMES)
2043         {
2044                 mprintf((0, "Too many netgames.\n"));
2045                 return;
2046         }
2047         
2048 // MWA  memcpy(&Active_games[i], data, sizeof(netgame_info));
2049         memcpy(&Active_games[i], (ubyte *)new, sizeof(netgame_info));
2050         memcpy (&ActiveNetPlayers[i],TempPlayersInfo,sizeof(AllNetPlayers_info));
2051
2052    if (SecurityCheck)
2053          if (Active_games[i].Security==SecurityCheck)
2054                 SecurityCheck=-1;
2055
2056         //mprintf ((0,"Recieved %d unique games...\n",i));
2057
2058         if (i == num_active_games)
2059                 num_active_games++;
2060
2061         if (Active_games[i].numplayers == 0)
2062         {
2063          mprintf ((0,"DELETING THIS GAME!!!\n"));       
2064                 // Delete this game
2065                 for (j = i; j < num_active_games-1; j++)
2066         {
2067              memcpy(&Active_games[j], &Active_games[j+1], sizeof(netgame_info));
2068            memcpy (&ActiveNetPlayers[j],&ActiveNetPlayers[j+1],sizeof(AllNetPlayers_info));
2069         }
2070                 num_active_games--;
2071                 SecurityCheck=0;
2072         }
2073 }
2074
2075 void network_process_lite_info(ubyte *data)
2076 {
2077         int i, j;
2078         lite_info *new = (lite_info *)data;
2079 #ifdef WORDS_BIGENDIAN
2080         lite_info tmp_info;
2081
2082         if (Network_game_type == IPX_GAME) {
2083                 receive_netgame_packet(data, (netgame_info *)&tmp_info, 1);
2084                 new = &tmp_info;
2085         }
2086 #endif
2087
2088         Network_games_changed = 1;
2089
2090    //mprintf((0, "Got game data for game %s.\n", new->game_name));
2091
2092         for (i = 0; i < num_active_games; i++)
2093     {
2094       //mprintf ((0,"GAMEINFO: Game %d is %s!\n",i,Active_games[i].game_name));
2095       
2096       if ((!stricmp(Active_games[i].game_name, new->game_name)) && 
2097                          Active_games[i].Security==new->Security)
2098                                 break;
2099     }
2100
2101         if (i == MAX_ACTIVE_NETGAMES)
2102         {
2103                 mprintf((0, "Too many netgames.\n"));
2104                 return;
2105         }
2106         
2107         memcpy(&Active_games[i], (ubyte *)new, sizeof(lite_info));
2108
2109 // See if this is really a Hoard game
2110 // If so, adjust all the data accordingly
2111
2112         if (HoardEquipped())
2113         {
2114                 if (Active_games[i].game_flags & NETGAME_FLAG_HOARD)
2115                 {
2116                         Active_games[i].gamemode=NETGAME_HOARD;                                   
2117                         Active_games[i].game_status=NETSTAT_PLAYING;
2118                         
2119                         if (Active_games[i].game_flags & NETGAME_FLAG_TEAM_HOARD)
2120                                 Active_games[i].gamemode=NETGAME_TEAM_HOARD;                                      
2121                         if (Active_games[i].game_flags & NETGAME_FLAG_REALLY_ENDLEVEL)
2122                                 Active_games[i].game_status=NETSTAT_ENDLEVEL;
2123                         if (Active_games[i].game_flags & NETGAME_FLAG_REALLY_FORMING)
2124                                 Active_games[i].game_status=NETSTAT_STARTING;
2125                 }
2126         }
2127
2128    //mprintf ((0,"Recieved %d unique games...\n",i));
2129
2130         if (i == num_active_games)
2131                 num_active_games++;
2132
2133         if (Active_games[i].numplayers == 0)
2134     {
2135            mprintf ((0,"DELETING THIS GAME!!!\n"));     
2136                 // Delete this game
2137                 for (j = i; j < num_active_games-1; j++)
2138         {
2139              memcpy(&Active_games[j], &Active_games[j+1], sizeof(netgame_info));
2140         }
2141                 num_active_games--;
2142         }
2143 }
2144
2145 void network_process_dump(sequence_packet *their)
2146 {
2147         // Our request for join was denied.  Tell the user why.
2148
2149         char temp[40];
2150         int i;
2151
2152         mprintf((0, "Dumped by player %s, type %d.\n", their->player.callsign, their->player.connected));
2153
2154    if (their->player.connected!=7)
2155                 nm_messagebox(NULL, 1, TXT_OK, NET_DUMP_STRINGS(their->player.connected));
2156         else
2157                 {
2158                  for (i=0;i<N_players;i++)
2159                         if (!stricmp (their->player.callsign,Players[i].callsign))
2160                         {
2161                                 if (i!=network_who_is_master())
2162                                 {
2163                                         HUD_init_message ("%s attempted to kick you out.",their->player.callsign);
2164                                 }
2165                                 else
2166                                 {
2167                                   sprintf (temp,"%s has kicked you out!",their->player.callsign);
2168                                   nm_messagebox(NULL, 1, TXT_OK, &temp);
2169                             if (Network_status==NETSTAT_PLAYING)
2170                                   {
2171                                         IWasKicked=1;
2172                                         multi_leave_game();     
2173                                   }
2174                                  else
2175                                         Network_status = NETSTAT_MENU;
2176                       }
2177                    }
2178                 }
2179 }       
2180 void network_process_request(sequence_packet *their)
2181 {
2182         // Player is ready to receieve a sync packet
2183         int i;
2184
2185         mprintf((0, "Player %s ready for sync.\n", their->player.callsign));
2186
2187         for (i = 0; i < N_players; i++) {
2188                 if (Network_game_type == IPX_GAME) {
2189                         if (!memcmp(their->player.network.ipx.server, NetPlayers.players[i].network.ipx.server, 4) && !memcmp(their->player.network.ipx.node, NetPlayers.players[i].network.ipx.node, 6) && (!stricmp(their->player.callsign, NetPlayers.players[i].callsign))) {
2190                                 Players[i].connected = 1;
2191                                 break;
2192                         }
2193                 } else {
2194                         if ( (their->player.network.appletalk.node == NetPlayers.players[i].network.appletalk.node) && (their->player.network.appletalk.net == NetPlayers.players[i].network.appletalk.net) && (!stricmp(their->player.callsign, NetPlayers.players[i].callsign)) ) {
2195                                 Players[i].connected = 1;
2196                                 break;
2197                         }
2198                 }
2199         }                       
2200 }
2201
2202 #define REFUSE_INTERVAL F1_0 * 8
2203 extern void multi_reset_object_texture (object *);
2204
2205 void network_process_packet(ubyte *data, int length )
2206 {
2207         sequence_packet *their = (sequence_packet *)data;
2208 #ifdef WORDS_BIGENDIAN
2209         sequence_packet tmp_packet;
2210
2211         if (Network_game_type == IPX_GAME) {
2212                 receive_sequence_packet(data, &tmp_packet);
2213                 their = &tmp_packet;                                            // reassign their to point to correctly alinged structure
2214         }
2215 #endif
2216
2217    //mprintf( (0, "Got packet of length %d, type %d\n", length, their->type ));
2218         
2219 //      if ( length < sizeof(sequence_packet) ) return;
2220
2221         switch( data[0] )       {
2222         
2223          case PID_GAME_INFO:            // Jason L. says we can safely ignore this type.
2224                 break;
2225         
2226      case PID_PLAYERSINFO:
2227
2228                 mprintf ((0,"Got a PID_PLAYERSINFO!\n"));
2229
2230                 if (Network_status==NETSTAT_WAITING)
2231                 {
2232                         if (Network_game_type == IPX_GAME)
2233                                 receive_netplayers_packet(data, &TempPlayersBase);
2234                         else
2235                                 memcpy (&TempPlayersBase,data,sizeof(AllNetPlayers_info));
2236
2237                         if (TempPlayersBase.Security!=Netgame.Security)
2238                          {
2239                           mprintf ((0,"Bad security for PLAYERSINFO\n"));
2240                           break;
2241                          }      
2242                 
2243                         mprintf ((0,"Got a waiting PID_PLAYERSINFO!\n"));
2244                         if (length!=ALLNETPLAYERSINFO_SIZE)
2245                         {
2246                                 mprintf ((0,"Invalid size for netplayers packet!\n"));
2247                                 return;
2248                         }
2249
2250                         TempPlayersInfo=&TempPlayersBase;
2251                         WaitingForPlayerInfo=0;
2252                         NetSecurityNum=TempPlayersInfo->Security;
2253                         NetSecurityFlag=NETSECURITY_WAIT_FOR_SYNC;
2254            }
2255
2256      break;
2257
2258    case PID_LITE_INFO:
2259
2260          if (length != LITE_INFO_SIZE)
2261                  {
2262                   mprintf ((0,"WARNING! Recieved invalid size for PID_LITE_INFO\n"));
2263                   return;
2264                  }
2265  
2266          if (Network_status == NETSTAT_BROWSING)
2267                 network_process_lite_info (data);
2268     break;
2269
2270         case PID_GAME_LIST:
2271                 // Someone wants a list of games
2272
2273            if (length != SEQUENCE_PACKET_SIZE)
2274                  {
2275                   mprintf ((0,"WARNING! Recieved invalid size for PID_GAME_LIST\n"));
2276                   return;
2277                  }
2278                         
2279                 mprintf((0, "Got a PID_GAME_LIST!\n"));
2280                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2281                         if (network_i_am_master())
2282                                 network_send_lite_info(their);
2283                 break;
2284
2285
2286         case PID_SEND_ALL_GAMEINFO:
2287
2288            if (length != SEQUENCE_PACKET_SIZE)
2289                  {
2290                   mprintf ((0,"WARNING! Recieved invalid size for PID_SEND_ALL_GAMEINFO\n"));
2291                   return;
2292                  }
2293
2294                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2295                         if (network_i_am_master() && their->Security==Netgame.Security)
2296                                 network_send_game_info(their);
2297                 break;
2298         
2299         case PID_ADDPLAYER:
2300
2301                 mprintf( (0, "Got NEWPLAYER message from %s.\n", their->player.callsign));
2302                 
2303            if (length != SEQUENCE_PACKET_SIZE)
2304                  {
2305                   mprintf ((0,"WARNING! Recieved invalid size for PID_ADDPLAYER\n"));
2306                   return;
2307                  }
2308                 mprintf( (0, "Got NEWPLAYER message from %s.\n", their->player.callsign));
2309                 network_new_player(their);
2310                 break;                  
2311         case PID_REQUEST:
2312            if (length != SEQUENCE_PACKET_SIZE)
2313                  {
2314                   mprintf ((0,"WARNING! Recieved invalid size for PID_REQUEST\n"));
2315                   return;
2316                  }
2317
2318                 mprintf( (0, "Got REQUEST from '%s'\n", their->player.callsign ));
2319                 if (Network_status == NETSTAT_STARTING) 
2320                 {
2321                         // Someone wants to join our game!
2322                         network_add_player(their);
2323                 }
2324                 else if (Network_status == NETSTAT_WAITING)
2325                 {
2326                         // Someone is ready to recieve a sync packet
2327                         network_process_request(their);
2328                 }
2329                 else if (Network_status == NETSTAT_PLAYING)
2330                 {
2331                         // Someone wants to join a game in progress!
2332                         if (Netgame.RefusePlayers)
2333                 DoRefuseStuff (their);
2334                    else 
2335                                 network_welcome_player(their);
2336                 }
2337                 break;
2338         case PID_DUMP:  
2339
2340            if (length != SEQUENCE_PACKET_SIZE)
2341                  {
2342                   mprintf ((0,"WARNING! Recieved invalid size for PID_DUMP\n"));
2343                   return;
2344                  }
2345   
2346                 if (Network_status == NETSTAT_WAITING || Network_status==NETSTAT_PLAYING )
2347                         network_process_dump(their);
2348                 break;
2349         case PID_QUIT_JOINING:
2350
2351            if (length != SEQUENCE_PACKET_SIZE)
2352                  {
2353                   mprintf ((0,"WARNING! Recieved invalid size for PID_QUIT_JOINING\n"));
2354                   return;
2355                  }
2356                 if (Network_status == NETSTAT_STARTING)
2357                         network_remove_player( their );
2358                 else if ((Network_status == NETSTAT_PLAYING) && (Network_send_objects))
2359                         network_stop_resync( their );
2360                 break;
2361         case PID_SYNC:  
2362
2363                 mprintf ((0,"Got a sync packet! Network_status=%d\n",NETSTAT_WAITING));
2364
2365                 if (Network_status == NETSTAT_WAITING)  {
2366
2367                         if (Network_game_type == IPX_GAME)
2368                                 receive_full_netgame_packet(data, &TempNetInfo);
2369                         else
2370                                 memcpy((ubyte *)&(TempNetInfo), data, sizeof(netgame_info));
2371
2372                         if (TempNetInfo.Security!=Netgame.Security)
2373                          {
2374                                 mprintf ((0,"Bad security on sync packet.\n"));
2375                                 break;
2376                          }
2377
2378                         if (NetSecurityFlag==NETSECURITY_WAIT_FOR_SYNC)
2379                          {
2380                           if (TempNetInfo.Security==TempPlayersInfo->Security)
2381                           {
2382                                 network_read_sync_packet (&TempNetInfo,0);
2383                                 NetSecurityFlag=0;
2384                                 NetSecurityNum=0;
2385                           }     
2386                          }
2387                         else
2388                          {      
2389                         NetSecurityFlag=NETSECURITY_WAIT_FOR_PLAYERS;
2390                         NetSecurityNum=TempNetInfo.Security;
2391
2392                         if ( network_wait_for_playerinfo())
2393                                 network_read_sync_packet((netgame_info *)data,0);
2394  
2395                         NetSecurityFlag=0;
2396                         NetSecurityNum=0;
2397                          }
2398                 }
2399                 break;
2400
2401         case PID_PDATA: 
2402                 if ((Game_mode&GM_NETWORK) && ((Network_status == NETSTAT_PLAYING)||(Network_status == NETSTAT_ENDLEVEL) || Network_status==NETSTAT_WAITING)) { 
2403                         network_process_pdata((char *)data);
2404                 }
2405                 break;
2406    case PID_NAKED_PDATA:
2407                 if ((Game_mode&GM_NETWORK) && ((Network_status == NETSTAT_PLAYING)||(Network_status == NETSTAT_ENDLEVEL) || Network_status==NETSTAT_WAITING)) 
2408                         network_process_naked_pdata((char *)data,length);
2409            break;
2410
2411         case PID_OBJECT_DATA:
2412                 if (Network_status == NETSTAT_WAITING) 
2413                         network_read_object_packet(data);
2414                 break;
2415         case PID_ENDLEVEL:
2416                 if ((Network_status == NETSTAT_ENDLEVEL) || (Network_status == NETSTAT_PLAYING))
2417                         network_read_endlevel_packet(data);
2418                 else
2419                         mprintf((0, "Junked endlevel packet.\n"));
2420                 break;
2421         case PID_ENDLEVEL_SHORT:
2422                 if ((Network_status == NETSTAT_ENDLEVEL) || (Network_status == NETSTAT_PLAYING))
2423                         network_read_endlevel_short_packet(data);
2424                 else
2425                         mprintf((0, "Junked short endlevel packet!\n"));
2426                 break;
2427
2428         case PID_GAME_UPDATE:
2429                 mprintf ((0,"Got a GAME_UPDATE!\n"));
2430                         
2431                 if (Network_status==NETSTAT_PLAYING)
2432                  {
2433                         if (Network_game_type == IPX_GAME)
2434                                 receive_lite_netgame_packet(data, &TempNetInfo);
2435                         else
2436                                 memcpy((ubyte *)&TempNetInfo, data, sizeof(lite_info) );
2437                   if (TempNetInfo.Security==Netgame.Security)
2438                          memcpy (&Netgame,(ubyte *)&TempNetInfo,sizeof(lite_info));
2439                  }
2440                 if (Game_mode & GM_TEAM)
2441                  {
2442                         int i;
2443
2444                         for (i=0;i<N_players;i++)
2445                          if (Players[i].connected)
2446                         multi_reset_object_texture (&Objects[Players[i].objnum]);
2447                     reset_cockpit();
2448                  }
2449            break;
2450    case PID_PING_SEND:
2451                 network_ping (PID_PING_RETURN,data[1]);
2452                 break;
2453    case PID_PING_RETURN:
2454                 network_handle_ping_return(data[1]);  // data[1] is player who told us of their ping time
2455                 break;
2456    case PID_NAMES_RETURN:
2457                 if (Network_status==NETSTAT_BROWSING && NamesInfoSecurity!=-1)
2458                   network_process_names_return ((ubyte *) data);
2459                 break;
2460         case PID_GAME_PLAYERS:
2461                 // Someone wants a list of players in this game
2462
2463            if (length != SEQUENCE_PACKET_SIZE)
2464                  {
2465                   mprintf ((0,"WARNING! Recieved invalid size for PID_GAME_PLAYERS\n"));
2466                   return;
2467                  }
2468                         
2469                 mprintf((0, "Got a PID_GAME_PLAYERS!\n"));
2470                 if ((Network_status == NETSTAT_PLAYING) || (Network_status == NETSTAT_STARTING) || (Network_status == NETSTAT_ENDLEVEL))
2471                         if (network_i_am_master() && their->Security==Netgame.Security)
2472                                 network_send_player_names(their);
2473                 break;
2474
2475         default:
2476                 mprintf((0, "Ignoring invalid packet type.\n"));
2477                 Int3(); // Invalid network packet type, see ROB
2478            break;
2479         }
2480 }
2481
2482 #ifndef NDEBUG
2483 void dump_segments()
2484 {
2485         PHYSFS_file *fp;
2486
2487         fp = PHYSFS_openWrite("test.dmp");
2488         PHYSFS_write(fp, Segments, sizeof(segment), Highest_segment_index + 1);
2489         PHYSFS_close(fp);
2490         mprintf( (0, "SS=%d\n", sizeof(segment) ));
2491 }
2492 #endif
2493
2494
2495 void
2496 network_read_endlevel_packet( ubyte *data )
2497 {
2498         // Special packet for end of level syncing
2499         int playernum;
2500         endlevel_info *end = (endlevel_info *)data;
2501 #ifdef WORDS_BIGENDIAN
2502         int i, j;
2503
2504         for (i = 0; i < MAX_PLAYERS; i++)
2505                 for (j = 0; j < MAX_PLAYERS; j++)
2506                         end->kill_matrix[i][j] = INTEL_SHORT(end->kill_matrix[i][j]);
2507         end->kills = INTEL_SHORT(end->kills);
2508         end->killed = INTEL_SHORT(end->killed);
2509 #endif
2510
2511         playernum = end->player_num;
2512         
2513         Assert(playernum != Player_num);
2514     
2515         if (playernum>=N_players)
2516          {              
2517                 Int3(); // weird, but it an happen in a coop restore game
2518                 return; // if it happens in a coop restore, don't worry about it
2519          }
2520
2521         if ((Network_status == NETSTAT_PLAYING) && (end->connected != 0))
2522                 return; // Only accept disconnect packets if we're not out of the level yet
2523
2524         Players[playernum].connected = end->connected;
2525         memcpy(&kill_matrix[playernum][0], end->kill_matrix, MAX_PLAYERS*sizeof(short));
2526         Players[playernum].net_kills_total = end->kills;
2527         Players[playernum].net_killed_total = end->killed;
2528
2529         if ((Players[playernum].connected == 1) && (end->seconds_left < Countdown_seconds_left))
2530                 Countdown_seconds_left = end->seconds_left;
2531
2532         LastPacketTime[playernum] = timer_get_approx_seconds();
2533
2534 //      mprintf((0, "Got endlevel packet from player %d.\n", playernum));
2535 }
2536
2537 void
2538 network_read_endlevel_short_packet( ubyte *data )
2539 {
2540         // Special packet for end of level syncing
2541
2542         int playernum;
2543         endlevel_info_short *end;       
2544
2545         end = (endlevel_info_short *)data;
2546
2547         playernum = end->player_num;
2548         
2549         Assert(playernum != Player_num);
2550     
2551         if (playernum>=N_players)
2552          {              
2553                 Int3(); // weird, but it can happen in a coop restore game
2554                 return; // if it happens in a coop restore, don't worry about it
2555          }
2556
2557         if ((Network_status == NETSTAT_PLAYING) && (end->connected != 0))
2558          {
2559                 //mprintf ((0,"Returning early for short_endlevel\n"));
2560                 return; // Only accept disconnect packets if we're not out of the level yet
2561          }
2562
2563         Players[playernum].connected = end->connected;
2564
2565         if ((Players[playernum].connected == 1) && (end->seconds_left < Countdown_seconds_left))
2566                 Countdown_seconds_left = end->seconds_left;
2567
2568         LastPacketTime[playernum] = timer_get_approx_seconds();
2569 }
2570
2571
2572 void
2573 network_pack_objects(void)
2574 {
2575         // Switching modes, pack the object array
2576
2577         special_reset_objects();
2578 }                               
2579
2580 int
2581 network_verify_objects(int remote, int local)
2582 {
2583         int i;
2584         int nplayers, got_controlcen=0;
2585
2586    mprintf ((0,"NETWORK:remote=%d local=%d\n",remote,local));
2587
2588         if ((remote-local) > 10)
2589                 return(-1);
2590
2591         if (Game_mode & GM_MULTI_ROBOTS)
2592                 got_controlcen = 1;
2593
2594         nplayers = 0;
2595
2596         for (i = 0; i <= Highest_object_index; i++)
2597         {
2598                 if ((Objects[i].type == OBJ_PLAYER) || (Objects[i].type == OBJ_GHOST))
2599                         nplayers++;
2600                 if (Objects[i].type == OBJ_CNTRLCEN)
2601                         got_controlcen=1;
2602         }
2603
2604     if (got_controlcen && (MaxNumNetPlayers<=nplayers))
2605                 return(0);
2606
2607         return(1);
2608 }
2609
2610 void
2611 network_read_object_packet( ubyte *data )
2612 {
2613         // Object from another net player we need to sync with
2614
2615         short objnum, remote_objnum;
2616         sbyte obj_owner;
2617         int segnum, i;
2618         object *obj;
2619
2620         static int my_pnum = 0;
2621         static int mode = 0;
2622         static int object_count = 0;
2623         static int frame_num = 0;
2624         int nobj = data[1];
2625         int loc = 3;
2626         int remote_frame_num = data[2];
2627         
2628         frame_num++;
2629
2630 //      mprintf((0, "Object packet %d (remote #%d) contains %d objects.\n", frame_num, remote_frame_num, nobj));
2631
2632         for (i = 0; i < nobj; i++)
2633         {
2634                 objnum = INTEL_SHORT( *(short *)(data+loc) );                   loc += 2;
2635                 obj_owner = data[loc];                                          loc += 1;
2636                 remote_objnum = INTEL_SHORT( *(short *)(data+loc) );            loc += 2;
2637
2638                 if (objnum == -1) 
2639                 {
2640                         // Clear object array
2641                         mprintf((0, "Clearing object array.\n"));
2642
2643                         init_objects();
2644                         Network_rejoined = 1;
2645                         my_pnum = obj_owner;
2646                         change_playernum_to(my_pnum);
2647                         mode = 1;
2648                         object_count = 0;
2649                         frame_num = 1;
2650                 }
2651                 else if (objnum == -2)
2652                 {
2653                         // Special debug checksum marker for entire send
2654                         if (mode == 1)
2655                         {
2656                                 network_pack_objects();
2657                                 mode = 0;
2658                         }
2659                         mprintf((0, "Objnum -2 found in frame local %d remote %d.\n", frame_num, remote_frame_num));
2660                         mprintf((0, "Got %d objects, expected %d.\n", object_count, remote_objnum));
2661                         if (remote_objnum != object_count) {
2662                                 Int3();
2663                         }
2664                         if (network_verify_objects(remote_objnum, object_count))
2665                         {
2666                                 // Failed to sync up 
2667                                 nm_messagebox(NULL, 1, TXT_OK, TXT_NET_SYNC_FAILED);
2668                                 Network_status = NETSTAT_MENU;                          
2669                                 return;
2670                         }
2671                         frame_num = 0;
2672                 }
2673                 else 
2674                 {
2675                         if (frame_num != remote_frame_num)
2676                                 Int3();
2677                         mprintf ((0,"Got a type 3 object packet!\n"));
2678                         object_count++;
2679                         if ((obj_owner == my_pnum) || (obj_owner == -1)) 
2680                         {
2681                                 if (mode != 1)
2682                                         Int3(); // SEE ROB
2683                                 objnum = remote_objnum;
2684                                 //if (objnum > Highest_object_index)
2685                                 //{
2686                                 //      Highest_object_index = objnum;
2687                                 //      num_objects = Highest_object_index+1;
2688                                 //}
2689                         }
2690                         else {
2691                                 if (mode == 1)
2692                                 {
2693                                         network_pack_objects();
2694                                         mode = 0;
2695                                 }
2696                                 objnum = obj_allocate();
2697                         }
2698                         if (objnum != -1) {
2699                                 obj = &Objects[objnum];
2700                                 if (obj->segnum != -1)
2701                                         obj_unlink(objnum);
2702                                 Assert(obj->segnum == -1);
2703                                 Assert(objnum < MAX_OBJECTS);
2704                                 memcpy(obj, &data[loc], sizeof(object));
2705                                 if (Network_game_type == IPX_GAME)
2706                                         swap_object(obj);
2707                                 loc += sizeof(object);
2708                                 segnum = obj->segnum;
2709                                 obj->next = obj->prev = obj->segnum = -1;
2710                                 obj->attached_obj = -1;
2711                                 if (segnum > -1)
2712                                         obj_link(OBJECT_NUMBER(obj), segnum);
2713                                 if (obj_owner == my_pnum) 
2714                                         map_objnum_local_to_local(objnum);
2715                                 else if (obj_owner != -1)
2716                                         map_objnum_local_to_remote(objnum, remote_objnum, obj_owner);
2717                                 else
2718                                         object_owner[objnum] = -1;
2719                         }
2720                 } // For a standard onbject
2721         } // For each object in packet
2722 }
2723         
2724 /* Polling loop waiting for sync packet to start game
2725  * after having sent request
2726  */
2727 void network_sync_poll( int nitems, newmenu_item * menus, int * key, int citem )
2728 {
2729
2730         static fix t1 = 0;
2731
2732         network_listen();
2733
2734         if (Network_status != NETSTAT_WAITING)  // Status changed to playing, exit the menu
2735                 *key = -2;
2736
2737         if (!Network_rejoined && (timer_get_approx_seconds() > t1+F1_0*2))
2738         {
2739                 int i;
2740
2741                 // Poll time expired, re-send request
2742                 
2743                 t1 = timer_get_approx_seconds();
2744
2745                 mprintf((0, "Re-sending join request.\n"));
2746                 i = network_send_request();
2747                 if (i < 0)
2748                         *key = -2;
2749         }
2750 }
2751
2752 void network_start_poll( int nitems, newmenu_item * menus, int * key, int citem )
2753 {
2754         int i,n,nm;
2755
2756         Assert(Network_status == NETSTAT_STARTING);
2757
2758         if (!menus[0].value) {
2759                         menus[0].value = 1;
2760                         menus[0].redraw = 1;
2761         }
2762
2763         for (i=1; i<nitems; i++ )       {
2764                 if ( (i>= N_players) && (menus[i].value) )      {
2765                         menus[i].value = 0;
2766                         menus[i].redraw = 1;
2767                 }
2768         }
2769
2770         nm = 0;
2771         for (i=0; i<nitems; i++ )       {
2772                 if ( menus[i].value )   {
2773                         nm++;
2774                         if ( nm > N_players )   {
2775                                 menus[i].value = 0;
2776                                 menus[i].redraw = 1;
2777                         }
2778                 }
2779         }
2780
2781         if ( nm > MaxNumNetPlayers )    {
2782                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d %s", TXT_SORRY_ONLY, MaxNumNetPlayers, TXT_NETPLAYERS_IN );
2783                 // Turn off the last player highlighted
2784                 for (i = N_players; i > 0; i--)
2785                         if (menus[i].value == 1) 
2786                         {
2787                                 menus[i].value = 0;
2788                                 menus[i].redraw = 1;
2789                                 break;
2790                         }
2791         }
2792
2793 //       if (nitems > MAX_PLAYERS ) return; 
2794         
2795         n = Netgame.numplayers;
2796         network_listen();
2797
2798         if (n < Netgame.numplayers )    
2799         {
2800                 digi_play_sample (SOUND_HUD_MESSAGE,F1_0);
2801
2802       mprintf ((0,"More players are printed!"));
2803                 if (FindArg("-norankings"))
2804               sprintf( menus[N_players-1].text, "%d. %-20s", N_players,NetPlayers.players[N_players-1].callsign );
2805                 else
2806               sprintf( menus[N_players-1].text, "%d. %s%-20s", N_players, RankStrings[NetPlayers.players[N_players-1].rank],NetPlayers.players[N_players-1].callsign );
2807
2808                 menus[N_players-1].redraw = 1;
2809                 if (N_players <= MaxNumNetPlayers)
2810                 {
2811                         menus[N_players-1].value = 1;
2812                 }
2813         } 
2814         else if ( n > Netgame.numplayers )      
2815         {
2816                 // One got removed...
2817
2818       digi_play_sample (SOUND_HUD_KILL,F1_0);
2819   
2820                 for (i=0; i<N_players; i++ )    
2821                 {
2822          
2823          if (FindArg("-norankings"))    
2824                  sprintf( menus[i].text, "%d. %-20s", i+1, NetPlayers.players[i].callsign );
2825          else
2826                  sprintf( menus[i].text, "%d. %s%-20s", i+1, RankStrings[NetPlayers.players[i].rank],NetPlayers.players[i].callsign );
2827                         if (i < MaxNumNetPlayers)
2828                                 menus[i].value = 1;
2829                         else
2830                                 menus[i].value = 0;
2831                         menus[i].redraw = 1;
2832                 }
2833                 for (i=N_players; i<n; i++ )    
2834                 {
2835                         sprintf( menus[i].text, "%d. ", i+1 );          // Clear out the deleted entries...
2836                         menus[i].value = 0;
2837                         menus[i].redraw = 1;
2838                 }
2839    }
2840 }
2841
2842 int opt_cinvul, opt_team_anarchy, opt_coop, opt_show_on_map, opt_closed,opt_maxnet;
2843 int last_cinvul=0,last_maxnet,opt_team_hoard;
2844 int opt_refuse,opt_capture;
2845
2846 void network_game_param_poll( int nitems, newmenu_item * menus, int * key, int citem )
2847 {
2848         static int oldmaxnet=0;
2849
2850         if (((HoardEquipped() && menus[opt_team_hoard].value) || (menus[opt_team_anarchy].value || menus[opt_capture].value)) && !menus[opt_closed].value && !menus[opt_refuse].value) { 
2851                 menus[opt_refuse].value = 1;
2852                 menus[opt_refuse].redraw = 1;
2853                 menus[opt_refuse-1].value = 0;
2854                 menus[opt_refuse-1].redraw = 1;
2855                 menus[opt_refuse-2].value = 0;
2856                 menus[opt_refuse-2].redraw = 1;
2857         }
2858
2859         #ifndef MACINTOSH
2860         if (menus[opt_coop].value)
2861         #else
2862         if ( (menus[opt_coop].value) || ((Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) && (menus[opt_coop-1].value)) )
2863         #endif
2864         {
2865                 oldmaxnet=1;
2866
2867                 if (menus[opt_maxnet].value>2) 
2868                 {
2869                     menus[opt_maxnet].value=2;
2870                     menus[opt_maxnet].redraw=1;
2871                 }
2872
2873                 if (menus[opt_maxnet].max_value>2)
2874                 {
2875                     menus[opt_maxnet].max_value=2;
2876                     menus[opt_maxnet].redraw=1;
2877                 }
2878
2879                 #ifdef MACINTOSH
2880                 if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
2881                         if (menus[opt_maxnet].value > 0) {
2882                             menus[opt_maxnet].value=0;
2883                             menus[opt_maxnet].redraw=1;
2884                         }
2885                         if (menus[opt_maxnet].max_value > 0) {
2886                                 menus[opt_maxnet].max_value=0;
2887                                 menus[opt_maxnet].redraw=1;
2888                         }
2889                 }
2890                 #endif
2891
2892                 if ( !(Netgame.game_flags & NETGAME_FLAG_SHOW_MAP) )
2893                         Netgame.game_flags |= NETGAME_FLAG_SHOW_MAP;
2894
2895                 if (Netgame.PlayTimeAllowed || Netgame.KillGoal)
2896                 {
2897                     Netgame.PlayTimeAllowed=0;
2898                     Netgame.KillGoal=0;
2899                 }
2900
2901         }
2902         else // if !Coop game
2903     {
2904                 if (oldmaxnet)
2905                 {
2906                     oldmaxnet=0;
2907                         menus[opt_maxnet].value=6;
2908                         menus[opt_maxnet].max_value=6;
2909
2910                     #ifdef MACINTOSH
2911                         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
2912                                 menus[opt_maxnet].value=1;
2913                                 menus[opt_maxnet].max_value=1;
2914                         }
2915                         #endif
2916                           
2917                 }
2918         }         
2919
2920     if ( last_maxnet != menus[opt_maxnet].value )   
2921         {
2922                 sprintf( menus[opt_maxnet].text, "Maximum players: %d", menus[opt_maxnet].value+2 );
2923                 last_maxnet = menus[opt_maxnet].value;
2924                 menus[opt_maxnet].redraw = 1;
2925         }               
2926  }
2927
2928 int netgame_difficulty;
2929
2930 int network_get_game_params( char * game_name, int *mode, int *game_flags, int *level )
2931 {
2932         int i;
2933         int opt, opt_name, opt_level, opt_mode,opt_moreopts;
2934         newmenu_item m[20];
2935         char name[NETGAME_NAME_LEN+1];
2936         char slevel[5];
2937         char level_text[32];
2938         char srmaxnet[50];
2939
2940         *game_flags=*game_flags;
2941
2942         SetAllAllowablesTo (1);
2943         NamesInfoSecurity=-1;
2944
2945         for (i=0;i<MAX_PLAYERS;i++)
2946                 if (i!=Player_num)
2947                         Players[i].callsign[0]=0;
2948
2949         MaxNumNetPlayers = MAX_NUM_NET_PLAYERS;
2950         Netgame.KillGoal=0;
2951         Netgame.PlayTimeAllowed=0;
2952         Netgame.Allow_marker_view=1;
2953         netgame_difficulty = Player_default_difficulty.intval;
2954
2955     ExtGameStatus=GAMESTAT_START_MULTIPLAYER_MISSION;
2956     if (!select_mission(1, TXT_MULTI_MISSION))
2957         return -1;
2958
2959         if (!(FindArg ("-packets") && FindArg ("-shortpackets")))
2960                 if (!network_choose_connect ())
2961                         return -1;
2962
2963 #ifdef MACINTOSH
2964         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) )
2965                 MaxNumNetPlayers = 3;
2966 #endif
2967
2968         strcpy(Netgame.mission_name, Current_mission_filename);
2969         strcpy(Netgame.mission_title, Current_mission_longname);
2970         Netgame.control_invul_time = control_invul_time;
2971
2972         sprintf( name, "%s%s", Players[Player_num].callsign, TXT_S_GAME );
2973         sprintf( slevel, "1" );
2974
2975         opt = 0;
2976         m[opt].type = NM_TYPE_TEXT; m[opt].text = TXT_DESCRIPTION; opt++;
2977
2978         opt_name = opt;
2979         m[opt].type = NM_TYPE_INPUT; m[opt].text = name; m[opt].text_len = NETGAME_NAME_LEN; opt++;
2980
2981         sprintf(level_text, "%s (1-%d)", TXT_LEVEL_, Last_level);
2982
2983 //      if (Last_secret_level < -1)
2984 //              sprintf(level_text+strlen(level_text)-1, ", S1-S%d)", -Last_secret_level);
2985 //      else if (Last_secret_level == -1)
2986 //              sprintf(level_text+strlen(level_text)-1, ", S1)");
2987
2988         Assert(strlen(level_text) < 32);
2989
2990         m[opt].type = NM_TYPE_TEXT; m[opt].text = level_text; opt++;
2991
2992         opt_level = opt;
2993         m[opt].type = NM_TYPE_INPUT; m[opt].text = slevel; m[opt].text_len=4; opt++;
2994 //      m[opt].type = NM_TYPE_TEXT; m[opt].text = TXT_OPTIONS; opt++;
2995         
2996         opt_mode = opt;
2997         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_ANARCHY; m[opt].value=1; m[opt].group=0; opt++;
2998         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_TEAM_ANARCHY; m[opt].value=0; m[opt].group=0; opt_team_anarchy=opt; opt++;
2999         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_ANARCHY_W_ROBOTS; m[opt].value=0; m[opt].group=0; opt++;
3000         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_COOPERATIVE; m[opt].value=0; m[opt].group=0; opt_coop=opt; opt++;
3001         m[opt].type = NM_TYPE_RADIO; m[opt].text = "Capture the flag"; m[opt].value=0; m[opt].group=0; opt_capture=opt; opt++;
3002    
3003         if (HoardEquipped())
3004         {
3005                 m[opt].type = NM_TYPE_RADIO; m[opt].text = "Hoard"; m[opt].value=0; m[opt].group=0; opt++;
3006                 m[opt].type = NM_TYPE_RADIO; m[opt].text = "Team Hoard"; m[opt].value=0; m[opt].group=0; opt_team_hoard=opt; opt++;
3007            m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++;
3008         } 
3009         else
3010          {  m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++; }
3011
3012         m[opt].type = NM_TYPE_RADIO; m[opt].text = "Open game"; m[opt].group=1; m[opt].value=0; opt++;
3013         opt_closed = opt;
3014         m[opt].type = NM_TYPE_RADIO; m[opt].text = TXT_CLOSED_GAME; m[opt].group=1; m[opt].value=0; opt++;
3015    opt_refuse = opt;
3016    m[opt].type = NM_TYPE_RADIO; m[opt].text = "Restricted Game              "; m[opt].group=1; m[opt].value=Netgame.RefusePlayers; opt++;
3017
3018 //      m[opt].type = NM_TYPE_CHECK; m[opt].text = TXT_SHOW_IDS; m[opt].value=0; opt++;
3019
3020    opt_maxnet = opt;
3021    sprintf( srmaxnet, "Maximum players: %d", MaxNumNetPlayers);
3022    m[opt].type = NM_TYPE_SLIDER; m[opt].value=MaxNumNetPlayers-2; m[opt].text= srmaxnet; m[opt].min_value=0; 
3023    m[opt].max_value=MaxNumNetPlayers-2; opt++;
3024    last_maxnet=MaxNumNetPlayers-2;
3025
3026    opt_moreopts=opt;
3027    m[opt].type = NM_TYPE_MENU;  m[opt].text = "More options..."; opt++;
3028
3029         Assert(opt <= 20);
3030
3031 menu:
3032    ExtGameStatus=GAMESTAT_NETGAME_OPTIONS; 
3033         i = newmenu_do1( NULL, NULL, opt, m, network_game_param_poll, 1 );
3034                                                                         //TXT_NETGAME_SETUP
3035    if (i==opt_moreopts)
3036     {
3037      if ( m[opt_mode+3].value )
3038       Game_mode=GM_MULTI_COOP;
3039      network_more_game_options();
3040      Game_mode=0;
3041      goto menu;
3042     }
3043   Netgame.RefusePlayers=m[opt_refuse].value;
3044
3045
3046         if ( i > -1 )   {
3047                 int j;
3048                       
3049    MaxNumNetPlayers = m[opt_maxnet].value+2;
3050    Netgame.max_numplayers=MaxNumNetPlayers;
3051                                 
3052                 for (j = 0; j < num_active_games; j++)
3053                         if (!stricmp(Active_games[j].game_name, name))
3054                         {
3055                                 nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_DUPLICATE_NAME);
3056                                 goto menu;
3057                         }
3058
3059                 strcpy( game_name, name );
3060                 
3061
3062                 *level = atoi(slevel);
3063
3064                 if ((*level < 1) || (*level > Last_level))
3065                 {
3066                         nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_LEVEL_OUT_RANGE );
3067                         sprintf(slevel, "1");
3068                         goto menu;
3069                 }
3070                 if ( m[opt_mode].value )
3071                         *mode = NETGAME_ANARCHY;
3072
3073 #ifdef SHAREWARE
3074                 else 
3075                 {
3076                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_REGISTERED_ONLY );
3077                         m[opt_mode+1].value = 0;
3078                         m[opt_mode+2].value = 0;
3079                         m[opt_mode+3].value = 0;
3080                    if (HoardEquipped())
3081                                 m[opt_mode+4].value = 0;
3082
3083                         m[opt_mode].value = 1;
3084                         goto menu;
3085                 }
3086 #else
3087                 else if (m[opt_mode+1].value) {
3088                         *mode = NETGAME_TEAM_ANARCHY;
3089                 }
3090                 else if (m[opt_capture].value)
3091                         *mode = NETGAME_CAPTURE_FLAG;
3092                 else if (HoardEquipped() && m[opt_capture+1].value)
3093                                 *mode = NETGAME_HOARD;
3094                 else if (HoardEquipped() && m[opt_capture+2].value)
3095                                 *mode = NETGAME_TEAM_HOARD;
3096                 else if (ANARCHY_ONLY_MISSION) {
3097                         nm_messagebox(NULL, 1, TXT_OK, TXT_ANARCHY_ONLY_MISSION);
3098                         m[opt_mode+2].value = 0;
3099                         m[opt_mode+3].value = 0;
3100                         m[opt_mode].value = 1;
3101                         goto menu;
3102                 }               
3103                 else if ( m[opt_mode+2].value ) 
3104                         *mode = NETGAME_ROBOT_ANARCHY;
3105                 else if ( m[opt_mode+3].value ) 
3106                         *mode = NETGAME_COOPERATIVE;
3107                 else Int3(); // Invalid mode -- see Rob
3108 #endif
3109                 if (m[opt_closed].value)
3110                         Netgame.game_flags |= NETGAME_FLAG_CLOSED;
3111       
3112         }
3113
3114         return i;
3115 }
3116
3117 void
3118 network_set_game_mode(int gamemode)
3119 {
3120         Show_kill_list = 1;
3121
3122         if ( gamemode == NETGAME_ANARCHY )
3123                 Game_mode = GM_NETWORK;
3124         else if ( gamemode == NETGAME_ROBOT_ANARCHY )
3125                 Game_mode = GM_NETWORK | GM_MULTI_ROBOTS;
3126         else if ( gamemode == NETGAME_COOPERATIVE ) 
3127                 Game_mode = GM_NETWORK | GM_MULTI_COOP | GM_MULTI_ROBOTS;
3128         else if (gamemode == NETGAME_CAPTURE_FLAG)
3129                 {
3130                  Game_mode = GM_NETWORK | GM_TEAM | GM_CAPTURE;
3131                  Show_kill_list=3;
3132                 }
3133
3134         else if (HoardEquipped() && gamemode == NETGAME_HOARD)
3135                  Game_mode = GM_NETWORK | GM_HOARD;
3136         else if (HoardEquipped() && gamemode == NETGAME_TEAM_HOARD)
3137                  {
3138                   Game_mode = GM_NETWORK | GM_HOARD | GM_TEAM;
3139                   Show_kill_list=3;
3140                  }
3141         else if ( gamemode == NETGAME_TEAM_ANARCHY )
3142         {
3143                 Game_mode = GM_NETWORK | GM_TEAM;
3144                 Show_kill_list = 3;
3145         }
3146         else
3147                 Int3();
3148
3149 #if 0
3150 #ifdef MACINTOSH                        // minimize players on localtalk games
3151         if ( (Network_game_type == APPLETALK_GAME) && (Network_appletalk_type == LOCALTALK_TYPE) ) {
3152                 if (Game_mode & GM_MULTI_ROBOTS)
3153                         MaxNumNetPlayers = 2;
3154                 else
3155                         MaxNumNetPlayers = 3;
3156         } else {
3157                 if (Game_mode & GM_MULTI_COOP)
3158                         MaxNumNetPlayers = 4;
3159                 else
3160                         MaxNumNetPlayers = 8;
3161         }
3162 #endif
3163 #endif
3164
3165 }
3166
3167 int
3168 network_find_game(void)
3169 {
3170         // Find out whether or not there is space left on this socket
3171
3172         fix t1;
3173
3174         Network_status = NETSTAT_BROWSING;
3175
3176         num_active_games = 0;
3177
3178         show_boxed_message(TXT_WAIT);
3179
3180         network_send_game_list_request();
3181         t1 = timer_get_approx_seconds() + F1_0*3;
3182
3183         while (timer_get_approx_seconds() < t1) // Wait 3 seconds for replies
3184                 network_listen();
3185
3186         clear_boxed_message();
3187
3188 //      mprintf((0, "%s %d %s\n", TXT_FOUND, num_active_games, TXT_ACTIVE_GAMES));
3189
3190         if (num_active_games < MAX_ACTIVE_NETGAMES)
3191                 return 0;
3192         return 1;
3193 }
3194
3195 void network_read_sync_packet( netgame_info * sp, int rsinit)
3196 {
3197         int i, j;
3198         char temp_callsign[CALLSIGN_LEN+1];
3199 #ifdef WORDS_BIGENDIAN
3200         netgame_info tmp_info;
3201
3202         if ( (Network_game_type == IPX_GAME) && (sp != &Netgame) ) {                            // for macintosh -- get the values unpacked to our structure format
3203                 receive_full_netgame_packet((ubyte *)sp, &tmp_info);
3204                 sp = &tmp_info;
3205         }
3206 #endif
3207
3208    if (rsinit)
3209      TempPlayersInfo=&NetPlayers;
3210         
3211         // This function is now called by all people entering the netgame.
3212
3213         // mprintf( (0, "%s %d\n", TXT_STARTING_NETGAME, sp->levelnum ));
3214
3215         if (sp != &Netgame)
3216          {
3217           memcpy( &Netgame, sp, sizeof(netgame_info) );
3218           memcpy (&NetPlayers,TempPlayersInfo,sizeof (AllNetPlayers_info));
3219          }
3220
3221         N_players = sp->numplayers;
3222         Difficulty_level = sp->difficulty;
3223         Network_status = sp->game_status;
3224
3225    //Assert(Function_mode != FMODE_GAME);
3226
3227         // New code, 11/27
3228
3229         mprintf((1, "Netgame.checksum = %d, calculated checksum = %d.\n", Netgame.segments_checksum, my_segments_checksum));
3230
3231         if (Netgame.segments_checksum != my_segments_checksum)
3232         {
3233                 Network_status = NETSTAT_MENU;
3234                 nm_messagebox(TXT_ERROR, 1, TXT_OK, TXT_NETLEVEL_NMATCH);
3235 #ifdef RELEASE
3236                 return;
3237 #endif
3238         }
3239
3240         // Discover my player number
3241
3242         memcpy(temp_callsign, Players[Player_num].callsign, CALLSIGN_LEN+1);
3243         
3244         Player_num = -1;
3245
3246         for (i=0; i<MAX_NUM_NET_PLAYERS; i++ )  {
3247                 Players[i].net_kills_total = 0;
3248 //              Players[i].net_killed_total = 0;
3249         }
3250
3251         for (i=0; i<N_players; i++ )    {
3252                 if (Network_game_type == IPX_GAME) {
3253                         if ( (!memcmp( TempPlayersInfo->players[i].network.ipx.node, My_Seq.player.network.ipx.node, 6 )) && (!stricmp( TempPlayersInfo->players[i].callsign, temp_callsign)) ) {
3254                                 if (Player_num!=-1) {
3255                                         Int3(); // Hey, we've found ourselves twice
3256                                         mprintf ((0,"Hey, we've found ourselves twice!\n"));
3257                                         Network_status = NETSTAT_MENU;
3258                                         return; 
3259                                 }
3260                                 change_playernum_to(i);
3261                         }
3262                 } else {
3263                         if ( (TempPlayersInfo->players[i].network.appletalk.node == My_Seq.player.network.appletalk.node) && (!stricmp( TempPlayersInfo->players[i].callsign, temp_callsign)) ) {
3264                                 if (Player_num!=-1) {
3265                                         Int3(); // Hey, we've found ourselves twice
3266                                         Network_status = NETSTAT_MENU;
3267                                         return; 
3268                                 }
3269                                 change_playernum_to(i);
3270                         }
3271                 }
3272                 memcpy( Players[i].callsign, TempPlayersInfo->players[i].callsign, CALLSIGN_LEN+1 );
3273
3274                 if (Network_game_type == IPX_GAME) {
3275 #ifdef WORDS_NEED_ALIGNMENT
3276                         uint server;
3277                         memcpy(&server, TempPlayersInfo->players[i].network.ipx.server, 4);
3278                         if (server != 0)
3279                                 ipx_get_local_target((ubyte *)&server, TempPlayersInfo->players[i].network.ipx.node, Players[i].net_address);
3280 #else // WORDS_NEED_ALIGNMENT
3281                         if ((*(uint *)TempPlayersInfo->players[i].network.ipx.server) != 0)
3282                                 ipx_get_local_target(TempPlayersInfo->players[i].network.ipx.server, TempPlayersInfo->players[i].network.ipx.node, Players[i].net_address);
3283 #endif // WORDS_NEED_ALIGNMENT
3284                         else
3285                                 memcpy( Players[i].net_address, TempPlayersInfo->players[i].network.ipx.node, 6 );
3286                 }
3287                                 
3288                 Players[i].n_packets_got=0;                             // How many packets we got from them
3289                 Players[i].n_packets_sent=0;                            // How many packets we sent to them
3290                 Players[i].connected = TempPlayersInfo->players[i].connected;
3291                 Players[i].net_kills_total = sp->player_kills[i];
3292                 Players[i].net_killed_total = sp->killed[i];
3293                 if ((Network_rejoined) || (i != Player_num))
3294                         Players[i].score = sp->player_score[i];
3295                 for (j = 0; j < MAX_NUM_NET_PLAYERS; j++)
3296                 {
3297                         kill_matrix[i][j] = sp->kills[i][j];
3298                 }
3299         }
3300
3301         if ( Player_num < 0 )   {
3302                 mprintf ((0,"Bad Player_num, resetting to NETSTAT_MENU!\n"));
3303                 Network_status = NETSTAT_MENU;
3304                 return;
3305         }
3306
3307         if (Network_rejoined) 
3308                 for (i=0; i<N_players;i++)
3309                         Players[i].net_killed_total = sp->killed[i];
3310
3311         if (Network_rejoined) {
3312                 network_process_monitor_vector(sp->monitor_vector);
3313                 Players[Player_num].time_level = sp->level_time;
3314         }
3315
3316         team_kills[0] = sp->team_kills[0];
3317         team_kills[1] = sp->team_kills[1];
3318         
3319         Players[Player_num].connected = 1;
3320    NetPlayers.players[Player_num].connected = 1;
3321    NetPlayers.players[Player_num].rank=GetMyNetRanking();
3322
3323         if (!Network_rejoined)
3324                 for (i=0; i<NumNetPlayerPositions; i++) {
3325                         Objects[Players[i].objnum].pos = Player_init[Netgame.locations[i]].pos;
3326                         Objects[Players[i].objnum].orient = Player_init[Netgame.locations[i]].orient;
3327                         obj_relink(Players[i].objnum,Player_init[Netgame.locations[i]].segnum);
3328                 }
3329
3330         Objects[Players[Player_num].objnum].type = OBJ_PLAYER;
3331
3332    mprintf ((0,"Changing to NETSTAT_PLAYING!\n"));
3333         Network_status = NETSTAT_PLAYING;
3334         Function_mode = FMODE_GAME;
3335         multi_sort_kill_list();
3336
3337 }
3338
3339 void
3340 network_send_sync(void)
3341 {
3342         int i, j, np;
3343
3344         // Randomize their starting locations...
3345
3346         d_srand( timer_get_fixed_seconds() );
3347         for (i=0; i<NumNetPlayerPositions; i++ )        
3348         {
3349                 if (Players[i].connected)
3350                         Players[i].connected = 1; // Get rid of endlevel connect statuses
3351                 if (Game_mode & GM_MULTI_COOP)
3352                         Netgame.locations[i] = i;
3353                 else {
3354                         do 
3355                         {
3356                                 np = d_rand() % NumNetPlayerPositions;
3357                                 for (j=0; j<i; j++ )    
3358                                 {
3359                                         if (Netgame.locations[j]==np)   
3360                                         {
3361                                                 np =-1;
3362                                                 break;
3363                                         }
3364                                 }
3365                         } while (np<0);
3366                         // np is a location that is not used anywhere else..
3367                         Netgame.locations[i]=np;
3368 //                      mprintf((0, "Player %d starting in location %d\n" ,i ,np ));
3369                 }
3370         }
3371
3372         // Push current data into the sync packet
3373
3374         network_update_netgame();
3375         Netgame.game_status = NETSTAT_PLAYING;
3376         Netgame.type = PID_SYNC;
3377         Netgame.segments_checksum = my_segments_checksum;
3378
3379         for (i=0; i<N_players; i++ )    {
3380                 if ((!Players[i].connected) || (i == Player_num))
3381                         continue;
3382
3383                 if (Network_game_type == IPX_GAME) {
3384                 // Send several times, extras will be ignored
3385                         send_internetwork_full_netgame_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
3386                         send_netplayers_packet(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node);
3387                 #ifdef MACINTOSH
3388                 } else {
3389                                 appletalk_send_packet_data( (ubyte *)&Netgame, sizeof(netgame_info), NetPlayers.players[i].network.appletalk.node,
3390                                         NetPlayers.players[i].network.appletalk.net,
3391                                         NetPlayers.players[i].network.appletalk.socket);
3392                                 appletalk_send_packet_data( (ubyte *)&NetPlayers, sizeof(AllNetPlayers_info), NetPlayers.players[i].network.appletalk.node,
3393                                         NetPlayers.players[i].network.appletalk.net,
3394                                         NetPlayers.players[i].network.appletalk.socket);
3395                 #endif
3396                 }
3397
3398         }
3399
3400         network_read_sync_packet(&Netgame,1); // Read it myself, as if I had sent it
3401 }
3402
3403 int
3404 network_select_teams(void)
3405 {
3406 #ifndef SHAREWARE
3407         newmenu_item m[MAX_PLAYERS+4];
3408         int choice, opt, opt_team_b;
3409         ubyte team_vector = 0;
3410         char team_names[2][CALLSIGN_LEN+1];
3411         int i;
3412         int pnums[MAX_PLAYERS+2];
3413
3414         // One-time initialization
3415
3416         for (i = N_players/2; i < N_players; i++) // Put first half of players on team A
3417         {
3418                 team_vector |= (1 << i);
3419         }
3420
3421         sprintf(team_names[0], "%s", TXT_BLUE);
3422         sprintf(team_names[1], "%s", TXT_RED);
3423
3424         // Here comes da menu
3425 menu:
3426         m[0].type = NM_TYPE_INPUT; m[0].text = team_names[0]; m[0].text_len = CALLSIGN_LEN; 
3427
3428         opt = 1;
3429         for (i = 0; i < N_players; i++)
3430         {
3431                 if (!(team_vector & (1 << i)))
3432                 {
3433                         m[opt].type = NM_TYPE_MENU; m[opt].text = NetPlayers.players[i].callsign; pnums[opt] = i; opt++;
3434                 }
3435         }
3436         opt_team_b = opt;
3437         m[opt].type = NM_TYPE_INPUT; m[opt].text = team_names[1]; m[opt].text_len = CALLSIGN_LEN; opt++;
3438         for (i = 0; i < N_players; i++)
3439         {
3440                 if (team_vector & (1 << i))
3441                 {
3442                         m[opt].type = NM_TYPE_MENU; m[opt].text = NetPlayers.players[i].callsign; pnums[opt] = i; opt++;
3443                 }
3444         }
3445         m[opt].type = NM_TYPE_TEXT; m[opt].text = ""; opt++;
3446         m[opt].type = NM_TYPE_MENU; m[opt].text = TXT_ACCEPT; opt++;
3447
3448         Assert(opt <= MAX_PLAYERS+4);
3449         
3450         choice = newmenu_do(NULL, TXT_TEAM_SELECTION, opt, m, NULL);
3451
3452         if (choice == opt-1)
3453         {
3454                 if ((opt-2-opt_team_b < 2) || (opt_team_b == 1)) 
3455                 {
3456                         nm_messagebox(NULL, 1, TXT_OK, TXT_TEAM_MUST_ONE);
3457                         #ifdef RELEASE
3458                                 goto menu;
3459                         #endif
3460                 }
3461                 
3462                 Netgame.team_vector = team_vector;
3463                 strcpy(Netgame.team_name[0], team_names[0]);
3464                 strcpy(Netgame.team_name[1], team_names[1]);
3465                 return 1;
3466         }
3467
3468         else if ((choice > 0) && (choice < opt_team_b)) {
3469                 team_vector |= (1 << pnums[choice]);
3470         }
3471         else if ((choice > opt_team_b) && (choice < opt-2)) {
3472                 team_vector &= ~(1 << pnums[choice]);
3473         }
3474         else if (choice == -1)
3475                 return 0;
3476         goto menu;
3477 #else
3478         return 0;
3479 #endif
3480 }
3481
3482 int
3483 network_select_players(void)
3484 {
3485         int i, j;
3486    newmenu_item m[MAX_PLAYERS+4];
3487    char text[MAX_PLAYERS+4][45];
3488         char title[50];
3489         int save_nplayers;              //how may people would like to join
3490
3491         network_add_player( &My_Seq );
3492                 
3493         for (i=0; i< MAX_PLAYERS+4; i++ ) {
3494                 sprintf( text[i], "%d.  %-20s", i+1, "" );
3495                 m[i].type = NM_TYPE_CHECK; m[i].text = text[i]; m[i].value = 0;
3496         }
3497
3498         m[0].value = 1;                         // Assume server will play...
3499
3500    if (FindArg("-norankings"))
3501                 sprintf( text[0], "%d. %-20s", 1, Players[Player_num].callsign );
3502         else
3503                 sprintf( text[0], "%d. %s%-20s", 1, RankStrings[NetPlayers.players[Player_num].rank],Players[Player_num].callsign );
3504
3505         sprintf( title, "%s %d %s", TXT_TEAM_SELECT, MaxNumNetPlayers, TXT_TEAM_PRESS_ENTER );
3506
3507 GetPlayersAgain:
3508    ExtGameStatus=GAMESTAT_NETGAME_PLAYER_SELECT;
3509         j=newmenu_do1( NULL, title, MAX_PLAYERS+4, m, network_start_poll, 1 );
3510
3511         save_nplayers = N_players;
3512
3513         if (j<0) 
3514         {
3515                 // Aborted!                                      
3516                 // Dump all players and go back to menu mode
3517
3518 abort:
3519                 for (i=1; i<save_nplayers; i++) {
3520                         if (Network_game_type == IPX_GAME)
3521                                 network_dump_player(NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node, DUMP_ABORTED);
3522                         #ifdef MACINTOSH
3523                         else
3524                                 network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node,NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_ABORTED);
3525                         #endif
3526                 }
3527                         
3528
3529                 Netgame.numplayers = 0;
3530                 network_send_game_info(0); // Tell everyone we're bailing
3531                 ipx_handle_leave_game(); // Tell the network driver we're bailing too
3532
3533                 Network_status = NETSTAT_MENU;
3534                 return(0);
3535         }
3536        
3537         // Count number of players chosen
3538
3539         N_players = 0;
3540         for (i=0; i<save_nplayers; i++ )
3541         {
3542                 if (m[i].value) 
3543                         N_players++;
3544         }
3545         
3546         if ( N_players > Netgame.max_numplayers) {
3547                 #ifndef MACINTOSH
3548                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d %s", TXT_SORRY_ONLY, MaxNumNetPlayers, TXT_NETPLAYERS_IN );
3549                 #else
3550                 nm_messagebox( TXT_ERROR, 1, TXT_OK, "%s %d netplayers for this game.", TXT_SORRY_ONLY, MaxNumNetPlayers );
3551                 #endif
3552                 N_players = save_nplayers;
3553                 goto GetPlayersAgain;
3554         }
3555
3556 #ifdef RELEASE
3557         if ( N_players < 2 )    {
3558                 nm_messagebox( TXT_ERROR, 1, TXT_OK, TXT_TEAM_ATLEAST_TWO );
3559                 N_players = save_nplayers;
3560                 goto GetPlayersAgain;
3561         }
3562 #endif
3563
3564 #ifdef RELEASE
3565         if ( (Netgame.gamemode == NETGAME_TEAM_ANARCHY ||
3566                    Netgame.gamemode == NETGAME_CAPTURE_FLAG || Netgame.gamemode == NETGAME_TEAM_HOARD) && (N_players < 2) ) {
3567                 nm_messagebox(TXT_ERROR, 1, TXT_OK, "You must select at least two\nplayers to start a team game" );
3568                 N_players = save_nplayers;
3569                 goto GetPlayersAgain;
3570         }
3571 #endif
3572
3573         // Remove players that aren't marked.
3574         N_players = 0;
3575         for (i=0; i<save_nplayers; i++ )        {
3576                 if (m[i].value) 
3577                 {
3578                         if (i > N_players)
3579                         {
3580                                 if (Network_game_type == IPX_GAME) {
3581                                         memcpy(NetPlayers.players[N_players].network.ipx.node, NetPlayers.players[i].network.ipx.node, 6);
3582                                         memcpy(NetPlayers.players[N_players].network.ipx.server, NetPlayers.players[i].network.ipx.server, 4);
3583                                 } else {
3584                                         NetPlayers.players[N_players].network.appletalk.node = NetPlayers.players[i].network.appletalk.node;
3585                                         NetPlayers.players[N_players].network.appletalk.net = NetPlayers.players[i].network.appletalk.net;
3586                                         NetPlayers.players[N_players].network.appletalk.socket = NetPlayers.players[i].network.appletalk.socket;
3587                                 }
3588                                 memcpy(NetPlayers.players[N_players].callsign, NetPlayers.players[i].callsign, CALLSIGN_LEN+1);
3589                                 NetPlayers.players[N_players].version_major=NetPlayers.players[i].version_major;
3590                                 NetPlayers.players[N_players].version_minor=NetPlayers.players[i].version_minor;
3591                                 NetPlayers.players[N_players].rank=NetPlayers.players[i].rank;
3592                                 ClipRank (&NetPlayers.players[N_players].rank);
3593                                 network_check_for_old_version(i);
3594                         }
3595                         Players[N_players].connected = 1;
3596                         N_players++;
3597                 }
3598                 else
3599                 {
3600                         if (Network_game_type == IPX_GAME)
3601                                 network_dump_player(NetPlayers.players[i].network.ipx.server,NetPlayers.players[i].network.ipx.node, DUMP_DORK);
3602                         #ifdef MACINTOSH
3603                         else
3604                                 network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node,NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_DORK);
3605                         #endif
3606                 }
3607         }
3608
3609         for (i = N_players; i < MAX_NUM_NET_PLAYERS; i++) {
3610                 if (Network_game_type == IPX_GAME) {
3611                 memset(NetPlayers.players[i].network.ipx.node, 0, 6);
3612                 memset(NetPlayers.players[i].network.ipx.server, 0, 4);
3613             } else {
3614                 NetPlayers.players[i].network.appletalk.node = 0;
3615                 NetPlayers.players[i].network.appletalk.net = 0;
3616                 NetPlayers.players[i].network.appletalk.socket = 0;
3617             }
3618         memset(NetPlayers.players[i].callsign, 0, CALLSIGN_LEN+1);
3619                 NetPlayers.players[i].version_major=0;
3620                 NetPlayers.players[i].version_minor=0;
3621                 NetPlayers.players[i].rank=0;
3622         }
3623
3624    mprintf ((0,"Select teams: Game mode is %d\n",Netgame.gamemode));
3625
3626         if (Netgame.gamemode == NETGAME_TEAM_ANARCHY ||
3627             Netgame.gamemode == NETGAME_CAPTURE_FLAG ||
3628                  Netgame.gamemode == NETGAME_TEAM_HOARD)
3629                  if (!network_select_teams())
3630                         goto abort;
3631
3632         return(1); 
3633 }
3634
3635 void 
3636 network_start_game()
3637 {
3638         int i;
3639         char game_name[NETGAME_NAME_LEN+1];
3640         int chosen_game_mode, game_flags, level;
3641
3642         if (Network_game_type == IPX_GAME) {
3643
3644                 Assert( FRAME_INFO_SIZE < IPX_MAX_DATA_SIZE );
3645                 mprintf((0, "Using frame_info len %d, max %d.\n", FRAME_INFO_SIZE, IPX_MAX_DATA_SIZE));
3646                 
3647                 if ( !Network_active )
3648                 {
3649                         nm_messagebox(NULL, 1, TXT_OK, TXT_IPX_NOT_FOUND );
3650                         return;
3651                 }
3652         #ifdef MACINTOSH
3653         } else {
3654                 int err;
3655                 char buf[256];
3656
3657                 Assert( FRAME_INFO_SIZE < APPLETALK_MAX_DATA_SIZE );            
3658                 mprintf((0, "Using frame_info len %d, max %d.\n", sizeof(frame_info), APPLETALK_MAX_DATA_SIZE));
3659                 if (Appletalk_active <= 0) {
3660                         switch (Appletalk_active) {
3661                         case APPLETALK_NOT_OPEN:
3662                                 sprintf(buf, "Appletalk is not currently active.\nPlease enable AppleTalk from the\nChooser and restart Descent.");
3663                                 break;
3664                         case APPLETALK_BAD_LISTENER:
3665                                 sprintf(buf, "The Resource Fork of Descent appears damaged.\nPlease re-install Descent or contact\nMacPlay technical support.");
3666                                 break;
3667                         case APPLETALK_NO_LOCAL_ADDR:
3668                                 sprintf(buf, "Wow! Strange!\n\nNo Local Address.");
3669                                 break;
3670                         case APPLETALK_NO_SOCKET:
3671                                 sprintf(buf, "All AppleTalk sockets are in use.\nTry shutting down other network\napplications and restarting Descent.\n");
3672                                 break;
3673                         }
3674                         nm_messagebox(NULL, 1, TXT_OK, buf);
3675                         return;
3676                 }
3677                 strcpy(Network_zone_name, DEFAULT_ZONE_NAME);
3678         #endif
3679         }
3680
3681         network_init();
3682         change_playernum_to(0);
3683
3684         if (network_find_game())
3685         {
3686                 nm_messagebox(NULL, 1, TXT_OK, TXT_NET_FULL);
3687                 return;
3688         }
3689
3690         game_flags = 0;
3691         i = network_get_game_params( game_name, &chosen_game_mode, &game_flags, &level );
3692
3693         if (i<0) return;
3694
3695     if (is_D2_OEM)
3696         My_Seq.player.version_minor|=NETWORK_OEM;
3697     
3698         N_players = 0;
3699
3700 // LoadLevel(level); Old, no longer used.
3701
3702         Netgame.difficulty = Difficulty_level;
3703         Netgame.gamemode = chosen_game_mode;
3704         Netgame.game_status = NETSTAT_STARTING;
3705         Netgame.numplayers = 0;
3706         Netgame.max_numplayers = MaxNumNetPlayers;
3707         Netgame.levelnum = level;
3708         Netgame.protocol_version = MULTI_PROTO_VERSION;
3709
3710         strcpy(Netgame.game_name, game_name);
3711         
3712         Network_status = NETSTAT_STARTING;
3713         // Have the network driver initialize whatever data it wants to
3714         // store for this netgame.
3715         // For mcast4, this randomly chooses a multicast session and port.
3716         // Clients subscribe to this address when they call
3717         // ipx_handle_netgame_aux_data.
3718         ipx_init_netgame_aux_data(Netgame.AuxData);
3719
3720         #ifdef MACINTOSH
3721         if (Network_game_type == APPLETALK_GAME) {
3722                 OSErr err;
3723                 fix t1;
3724                 int count = 0;
3725                 
3726                 show_boxed_message("Registering Netgame");
3727                 do {
3728                         err = appletalk_register_netgame( game_name, TickCount() );
3729                         t1 = timer_get_fixed_seconds() + F1_0;
3730                         while (timer_get_fixed_seconds() < t1) ;
3731                         count++;
3732                 } while ( (err == nbpDuplicate) && (count != MAX_REGISTER_TRIES) );
3733                 clear_boxed_message();
3734                 if ( (err == tooManyReqs) || (count == MAX_REGISTER_TRIES) ) {
3735                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
3736                         Game_mode = GM_GAME_OVER;
3737                         return;
3738                 }
3739         }
3740         #endif
3741
3742         network_set_game_mode(Netgame.gamemode);
3743
3744    d_srand( timer_get_fixed_seconds() );
3745    Netgame.Security=d_rand();  // For syncing Netgames with player packets
3746
3747         if(network_select_players())
3748         {
3749                 StartNewLevel(Netgame.levelnum, 0);
3750         }
3751         else
3752                 Game_mode = GM_GAME_OVER;
3753         
3754 }
3755
3756 void restart_net_searching(newmenu_item * m)
3757 {
3758         int i;
3759         N_players = 0;
3760         num_active_games = 0;
3761
3762         memset(Active_games, 0, sizeof(netgame_info)*MAX_ACTIVE_NETGAMES);
3763
3764         for (i = 0; i < MAX_ACTIVE_NETGAMES; i++)
3765         {
3766                 sprintf(m[i+2].text, "%d.                                                     ",i+1);
3767                 m[i+2].redraw = 1;
3768         }
3769   
3770    NamesInfoSecurity=-1;
3771         Network_games_changed = 1;      
3772 }
3773
3774 char *ModeLetters[]={"ANRCHY","TEAM","ROBO","COOP","FLAG","HOARD","TMHOARD"};
3775
3776 int NumActiveNetgames=0;
3777
3778 void network_join_poll( int nitems, newmenu_item * menus, int * key, int citem )
3779 {
3780         // Polling loop for Join Game menu
3781         static fix t1 = 0;
3782         int i, osocket,join_status,temp;
3783
3784         if ( (Network_game_type == IPX_GAME) && Network_allow_socket_changes ) {
3785                 osocket = Network_socket;
3786
3787                 if ( *key==KEY_PAGEDOWN )       { Network_socket--; *key = 0; }
3788                 if ( *key==KEY_PAGEUP )         { Network_socket++; *key = 0; }
3789
3790                 if (Network_socket>99)
3791                         Network_socket=99;
3792                 if (Network_socket<-99)
3793                         Network_socket=-99;
3794
3795                 if ( Network_socket+IPX_DEFAULT_SOCKET > 0x8000 )
3796                         Network_socket  = 0x8000 - IPX_DEFAULT_SOCKET;
3797
3798                 if ( Network_socket+IPX_DEFAULT_SOCKET < 0 )
3799                         Network_socket  = IPX_DEFAULT_SOCKET;
3800
3801                 if (Network_socket != osocket )         {
3802                         sprintf( menus[0].text, "\t%s %+d (PgUp/PgDn to change)", TXT_CURRENT_IPX_SOCKET, Network_socket );
3803                         menus[0].redraw = 1;
3804                         mprintf(( 0, "Changing to socket %d\n", Network_socket ));
3805                         network_listen();
3806                         mprintf ((0,"netgood 1!\n"));
3807                         ipx_change_default_socket( IPX_DEFAULT_SOCKET + Network_socket );
3808                         mprintf ((0,"netgood 2!\n"));
3809                         restart_net_searching(menus);
3810                         mprintf ((0,"netgood 3!\n"));
3811                         network_send_game_list_request();
3812                         mprintf ((0,"netgood 4!\n"));
3813                         return;
3814                 }
3815         }
3816
3817         // send a request for game info every 3 seconds
3818
3819         if (Network_game_type == IPX_GAME) {
3820                 if (timer_get_approx_seconds() > t1+F1_0*3) {
3821                         t1 = timer_get_approx_seconds();
3822                         network_send_game_list_request();
3823                 }
3824 #ifdef MACINTOSH
3825         } else if (timer_get_approx_seconds() > t1+F1_0*20) {
3826                 hide_cursor();
3827                 t1 = timer_get_approx_seconds();
3828                 restart_net_searching(menus);
3829                 show_boxed_message("Requesting list of Netgames");
3830                 network_send_game_list_request();
3831                 clear_boxed_message();
3832                 show_cursor();
3833 #endif
3834         }
3835
3836         temp=num_active_games;
3837
3838         network_listen();
3839
3840         NumActiveNetgames=num_active_games;
3841
3842         if (!Network_games_changed)
3843                 return;
3844
3845         if (temp!=num_active_games)
3846                 digi_play_sample (SOUND_HUD_MESSAGE,F1_0);
3847
3848         Network_games_changed = 0;
3849         mprintf ((0,"JOIN POLL: I'm looking at %d games!\n",num_active_games));
3850
3851         // Copy the active games data into the menu options
3852         for (i = 0; i < num_active_games; i++)
3853         {
3854                 int game_status = Active_games[i].game_status;
3855                 int j,x, k,tx,ty,ta,nplayers = 0;
3856                 char levelname[8],MissName[25],GameName[25],thold[2];
3857                 thold[1]=0;
3858
3859                 // These next two loops protect against menu skewing
3860                 // if missiontitle or gamename contain a tab
3861
3862                 for (x=0,tx=0,k=0,j=0;j<15;j++)
3863                 {
3864                         if (Active_games[i].mission_title[j]=='\t')
3865                                 continue;
3866                         thold[0]=Active_games[i].mission_title[j];
3867                         gr_get_string_size (thold,&tx,&ty,&ta);
3868
3869                         if ((x+=tx)>=LHX(55))
3870                         {
3871                                 MissName[k]=MissName[k+1]=MissName[k+2]='.';
3872                                 k+=3;
3873                                 break;
3874                         }
3875
3876                         MissName[k++]=Active_games[i].mission_title[j];
3877                 }
3878                 MissName[k]=0;
3879
3880                 for (x=0,tx=0,k=0,j=0;j<15;j++)
3881                 {
3882                         if (Active_games[i].game_name[j]=='\t')
3883                                 continue;
3884                         thold[0]=Active_games[i].game_name[j];
3885                         gr_get_string_size (thold,&tx,&ty,&ta);
3886
3887                         if ((x+=tx)>=LHX(55))
3888                         {
3889                                 GameName[k]=GameName[k+1]=GameName[k+2]='.';
3890                                 k+=3;
3891                                 break;
3892                         }
3893                         GameName[k++]=Active_games[i].game_name[j];
3894                 }
3895                 GameName[k]=0;
3896
3897
3898                 nplayers=Active_games[i].numconnected;
3899
3900                 if (Active_games[i].levelnum < 0)
3901                         sprintf(levelname, "S%d", -Active_games[i].levelnum);
3902                 else
3903                         sprintf(levelname, "%d", Active_games[i].levelnum);
3904
3905                 if (game_status == NETSTAT_STARTING)
3906                 {
3907                         sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3908                                          i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3909                                          Active_games[i].max_numplayers,MissName,levelname,"Forming");
3910                 }
3911                 else if (game_status == NETSTAT_PLAYING)
3912                 {
3913                         join_status=can_join_netgame(&Active_games[i],NULL);
3914                         //               mprintf ((0,"Joinstatus=%d\n",join_status));
3915
3916                         if (join_status==1)
3917                                 sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3918                                                  i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3919                                                  Active_games[i].max_numplayers,MissName,levelname,"Open");
3920                         else if (join_status==2)
3921                                 sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3922                                                  i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3923                                                  Active_games[i].max_numplayers,MissName,levelname,"Full");
3924                         else if (join_status==3)
3925                                 sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3926                                                  i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3927                                                  Active_games[i].max_numplayers,MissName,levelname,"Restrict");
3928                         else
3929                                 sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3930                                                  i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3931                                                  Active_games[i].max_numplayers,MissName,levelname,"Closed");
3932
3933                 }
3934                 else
3935                         sprintf (menus[i+2].text,"%d.\t%s \t%s \t  %d/%d \t%s \t %s \t%s",
3936                                          i+1,GameName,ModeLetters[Active_games[i].gamemode],nplayers,
3937                                          Active_games[i].max_numplayers,MissName,levelname,"Between");
3938
3939
3940                 Assert(strlen(menus[i+2].text) < 100);
3941                 menus[i+2].redraw = 1;
3942         }
3943
3944         for (i = num_active_games; i < MAX_ACTIVE_NETGAMES; i++)
3945         {
3946                 sprintf(menus[i+2].text, "%d.                                                     ",i+1);
3947                 menus[i+2].redraw = 1;
3948         }
3949 }
3950
3951 int
3952 network_wait_for_sync(void)
3953 {
3954         char text[60];
3955         newmenu_item m[2];
3956         int i, choice;
3957         
3958         Network_status = NETSTAT_WAITING;
3959
3960         m[0].type=NM_TYPE_TEXT; m[0].text = text;
3961         m[1].type=NM_TYPE_TEXT; m[1].text = TXT_NET_LEAVE;
3962         
3963         i = network_send_request();
3964
3965         if (i < 0)
3966                 return(-1);
3967
3968         sprintf( m[0].text, "%s\n'%s' %s", TXT_NET_WAITING, NetPlayers.players[i].callsign, TXT_NET_TO_ENTER );
3969
3970 menu:   
3971         choice=newmenu_do( NULL, TXT_WAIT, 2, m, network_sync_poll );
3972
3973         if (choice > -1)
3974                 goto menu;
3975
3976         if (Network_status != NETSTAT_PLAYING)  
3977         {
3978                 sequence_packet me;
3979
3980 //              if (Network_status == NETSTAT_ENDLEVEL)
3981 //              {
3982 //                      network_send_endlevel_packet(0);
3983 //                      longjmp(LeaveGame, 0);
3984 //              }               
3985
3986                 mprintf((0, "Aborting join.\n"));
3987                 me.type = PID_QUIT_JOINING;
3988                 memcpy( me.player.callsign, Players[Player_num].callsign, CALLSIGN_LEN+1 );
3989                 if (Network_game_type == IPX_GAME) {
3990                         memcpy( me.player.network.ipx.node, ipx_get_my_local_address(), 6 );
3991                         memcpy( me.player.network.ipx.server, ipx_get_my_server_address(), 4 );
3992                         send_internetwork_sequence_packet(me, NetPlayers.players[0].network.ipx.server, NetPlayers.players[0].network.ipx.node);
3993                 #ifdef MACINTOSH
3994                 } else {
3995                         me.player.network.appletalk.node = appletalk_get_my_node();
3996                         me.player.network.appletalk.net = appletalk_get_my_net();
3997                         me.player.network.appletalk.socket = appletalk_get_my_socket();
3998                 #endif
3999                 }
4000                 N_players = 0;
4001                 Function_mode = FMODE_MENU;
4002                 Game_mode = GM_GAME_OVER;
4003                 return(-1);     // they cancelled               
4004         }
4005         return(0);
4006 }
4007
4008 void 
4009 network_request_poll( int nitems, newmenu_item * menus, int * key, int citem )
4010 {
4011         // Polling loop for waiting-for-requests menu
4012
4013         int i = 0;
4014         int num_ready = 0;
4015
4016         // Send our endlevel packet at regular intervals
4017
4018 //      if (timer_get_approx_seconds() > t1+ENDLEVEL_SEND_INTERVAL)
4019 //      {
4020 //              network_send_endlevel_packet();
4021 //              t1 = timer_get_approx_seconds();
4022 //      }
4023
4024         network_listen();
4025
4026         for (i = 0; i < N_players; i++)
4027         {
4028                 if ((Players[i].connected == 1) || (Players[i].connected == 0))
4029                         num_ready++;
4030         }
4031
4032         if (num_ready == N_players) // All players have checked in or are disconnected
4033         {
4034                 *key = -2;
4035         }
4036 }
4037
4038 void
4039 network_wait_for_requests(void)
4040 {
4041         // Wait for other players to load the level before we send the sync
4042         int choice, i;
4043         newmenu_item m[1];
4044         
4045         Network_status = NETSTAT_WAITING;
4046
4047         m[0].type=NM_TYPE_TEXT; m[0].text = TXT_NET_LEAVE;
4048
4049         mprintf((0, "Entered wait_for_requests : N_players = %d.\n", N_players));
4050
4051         for (choice = 0; choice < N_players; choice++)
4052                 mprintf((0, "Players[%d].connected = %d.\n", choice, Players[choice].connected));
4053
4054         Network_status = NETSTAT_WAITING;
4055         network_flush();
4056
4057         Players[Player_num].connected = 1;
4058
4059 menu:
4060         choice = newmenu_do(NULL, TXT_WAIT, 1, m, network_request_poll);        
4061
4062         if (choice == -1)
4063         {
4064                 // User aborted
4065                 choice = nm_messagebox(NULL, 3, TXT_YES, TXT_NO, TXT_START_NOWAIT, TXT_QUITTING_NOW);
4066                 if (choice == 2)
4067                         return;
4068                 if (choice != 0)
4069                         goto menu;
4070                 
4071                 // User confirmed abort
4072                 
4073                 for (i=0; i < N_players; i++) {
4074                         if ((Players[i].connected != 0) && (i != Player_num)) {
4075                                 if (Network_game_type == IPX_GAME)
4076                                         network_dump_player(NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node, DUMP_ABORTED);
4077                                 #ifdef MACINTOSH
4078                                 else
4079                                         network_dump_appletalk_player(NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket, DUMP_ABORTED);
4080                                 #endif
4081                         }
4082                 }
4083
4084                 #ifdef MACINTOSH
4085                 if (Network_game_type == APPLETALK_GAME)
4086                         network_release_registered_game();
4087                 #endif
4088                 longjmp(LeaveGame, 0);  
4089         }
4090         else if (choice != -2)
4091                 goto menu;
4092 }
4093
4094 /* Do required syncing after each level, before starting new one */
4095 int
4096 network_level_sync(void)
4097 {
4098         int result;
4099
4100         mprintf((0, "Player %d entering network_level_sync.\n", Player_num));
4101         
4102         MySyncPackInitialized = 0;
4103
4104 //      my_segments_checksum = netmisc_calc_checksum(Segments, sizeof(segment)*(Highest_segment_index+1));
4105
4106         network_flush(); // Flush any old packets
4107
4108         if (N_players == 0)
4109                 result = network_wait_for_sync();
4110         else if (network_i_am_master())
4111         {
4112                 network_wait_for_requests();
4113                 network_send_sync();
4114                 result = 0;
4115         }
4116         else
4117                 result = network_wait_for_sync();
4118
4119    network_count_powerups_in_mine();
4120
4121         if (result)
4122         {
4123                 Players[Player_num].connected = 0;
4124                 network_send_endlevel_packet();
4125                 #ifdef MACINTOSH
4126                 if (Network_game_type == APPLETALK_GAME)
4127                         network_release_registered_game();
4128                 #endif
4129                 longjmp(LeaveGame, 0);
4130         }
4131         return(0);
4132 }
4133
4134 void network_count_powerups_in_mine(void)
4135  {
4136   int i;
4137
4138   for (i=0;i<MAX_POWERUP_TYPES;i++)
4139         PowerupsInMine[i]=0;
4140         
4141   for (i=0;i<=Highest_object_index;i++) 
4142         {
4143          if (Objects[i].type==OBJ_POWERUP)
4144           {
4145                 PowerupsInMine[Objects[i].id]++;
4146                 if (multi_powerup_is_4pack(Objects[i].id))
4147                    PowerupsInMine[Objects[i].id-1]+=4;
4148           }
4149         }
4150                   
4151  }
4152
4153 #ifdef MACINTOSH
4154
4155 // code to release the NBP binding of an appletalk game
4156
4157 void network_release_registered_game()
4158 {
4159         if (Network_game_type == APPLETALK_GAME)
4160                 appletalk_remove_netgame();
4161 }
4162
4163 // code to sort zone lists....
4164
4165 int zone_sort_func(const char **e0, const char **e1)
4166 {
4167         return strcmp(*e0, *e1);
4168 }
4169
4170 void network_get_appletalk_zone()
4171 {
4172         int num_zones, i, item, default_item;
4173         char **zone_list;
4174         char default_zone[MAX_ZONE_LENGTH];                     // my zone
4175
4176         Network_zone_name[0] = '\0';
4177         
4178         show_boxed_message("Looking for AppleTalk Zones");
4179         num_zones = appletalk_get_zone_names(&zone_list);
4180         clear_boxed_message();
4181
4182         if (num_zones < 0)      {               // error in getting zone list...maybe no router available....
4183                 if ( (num_zones == tooManyReqs) || (num_zones == noDataArea) ){
4184                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
4185                         longjmp(LeaveGame,0);
4186                 }
4187                 num_zones = 0;
4188         }
4189         
4190         if (num_zones == 0) {
4191                 strcpy(Network_zone_name, DEFAULT_ZONE_NAME);
4192                 return;
4193         }
4194         
4195         if (num_zones == 1) {
4196                 Network_zone_name[0] = (char)(strlen(zone_list[0]));
4197                 memcpy( &(Network_zone_name[1]), zone_list[0], strlen(zone_list[0]) );
4198                 goto zone_done;
4199         }
4200         
4201 // sort the zone names
4202
4203         for (i = 0; i < num_zones; i++)
4204                 strlwr(zone_list[i]);
4205
4206         qsort(zone_list, num_zones, sizeof(char *), zone_sort_func);
4207
4208 // get my current zone so we can highlight that one first
4209
4210         if (appletalk_get_my_zone(default_zone))
4211                 default_item = 0;
4212         else {
4213                 for (i = 0; i < num_zones; i++) {
4214                         if ( !stricmp(zone_list[i], default_zone) ) {
4215                                 default_item = i;
4216                                 break;
4217                         }
4218                 }
4219         }
4220
4221 rezone:         
4222         item = newmenu_listbox1("AppleTalk Zones", num_zones, zone_list, 0, default_item, NULL);
4223         
4224         if (item == -1)
4225                 goto rezone;
4226                 
4227         Network_zone_name[0] = (char)(strlen(zone_list[item]));
4228         memcpy( &(Network_zone_name[1]), zone_list[item], strlen(zone_list[item]) );
4229         
4230 zone_done:
4231         for (i = 0; i < num_zones; i++)
4232                 d_free(zone_list[i]);
4233         d_free(zone_list);
4234 }
4235 #endif
4236
4237 void nm_draw_background1(char * filename);
4238
4239 void network_join_game()
4240 {
4241         int choice, i;
4242         char menu_text[MAX_ACTIVE_NETGAMES+2][200];
4243         
4244         newmenu_item m[MAX_ACTIVE_NETGAMES+2];
4245
4246         if (Network_game_type == IPX_GAME) {
4247                 if ( !Network_active )
4248                 {
4249                         nm_messagebox(NULL, 1, TXT_OK, TXT_IPX_NOT_FOUND);
4250                         return;
4251                 }
4252         #ifdef MACINTOSH
4253         } else if (Appletalk_active <= 0) {
4254                 char buf[256];
4255                 
4256                 switch (Appletalk_active) {
4257                         case APPLETALK_NOT_OPEN:
4258                                 sprintf(buf, "Appletalk is not currently active.\nPlease enable AppleTalk from the\nChooser and restart Descent.");
4259                                 break;
4260                         case APPLETALK_BAD_LISTENER:
4261                                 sprintf(buf, "The Resource Fork of Descent appears damaged.\nPlease re-install Descent or contact\nMacPlay technical support.");
4262                                 break;
4263                         case APPLETALK_NO_LOCAL_ADDR:
4264                                 sprintf(buf, "Wow! Strange!\n\nNo Local Address.");
4265                                 break;
4266                         case APPLETALK_NO_SOCKET:
4267                                 sprintf(buf, "All AppleTalk sockets are in use.\nTry shutting down other network\napplications and restarting Descent.\n");
4268                                 break;
4269                 }
4270                 nm_messagebox(NULL, 1, TXT_OK, buf);
4271                 return;
4272         #endif
4273         }
4274
4275         network_init();
4276
4277         N_players = 0;
4278
4279         setjmp(LeaveGame);
4280         
4281         #ifdef MACINTOSH
4282         if (Network_game_type == APPLETALK_GAME)
4283                 network_get_appletalk_zone();
4284         #endif
4285         
4286         Network_send_objects = 0; 
4287         Network_sending_extras=0;
4288         Network_rejoined=0;
4289           
4290         Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4291         
4292    network_flush();
4293         network_listen();  // Throw out old info
4294
4295         #ifdef MACINTOSH
4296         if (Network_game_type == IPX_GAME)
4297         #endif          // note link to if
4298                 network_send_game_list_request(); // broadcast a request for lists
4299
4300         num_active_games = 0;
4301
4302    memset(m, 0, sizeof(newmenu_item)*MAX_ACTIVE_NETGAMES);
4303    memset(Active_games, 0, sizeof(netgame_info)*MAX_ACTIVE_NETGAMES);
4304    memset(ActiveNetPlayers,0,sizeof(AllNetPlayers_info)*MAX_ACTIVE_NETGAMES);
4305         
4306         gr_set_fontcolor(BM_XRGB(15,15,23),-1);
4307
4308         m[0].text = menu_text[0];
4309         m[0].type = NM_TYPE_TEXT;
4310         if (Network_game_type == IPX_GAME) {
4311                 if (Network_allow_socket_changes)
4312                         sprintf( m[0].text, "\tCurrent IPX Socket is default %+d (PgUp/PgDn to change)", Network_socket );
4313                 else
4314                         strcpy( m[0].text, "" ); //sprintf( m[0].text, "" );
4315         #ifdef MACINTOSH
4316         } else {
4317                 p2cstr(Network_zone_name);
4318                 if (strcmp(Network_zone_name, "*"))             // only print if there is a zone name
4319                         sprintf(m[0].text, "\tCurrent Zone is %s", Network_zone_name);          // is Network_zone_name a pascal string????
4320                 c2pstr(Network_zone_name);
4321         #endif
4322         }
4323
4324         m[1].text=menu_text[1];
4325         m[1].type=NM_TYPE_TEXT;
4326         sprintf (m[1].text,"\tGAME \tMODE \t#PLYRS \tMISSION \tLEV \tSTATUS");
4327
4328         for (i = 0; i < MAX_ACTIVE_NETGAMES; i++) {
4329                 m[i+2].text = menu_text[i+2];
4330                 m[i+2].type = NM_TYPE_MENU;
4331                 sprintf(m[i+2].text, "%d.                                                               ", i+1);
4332                 m[i+2].redraw = 1;
4333         }
4334
4335         Network_games_changed = 1;      
4336 remenu:
4337         SurfingNet=1;
4338         nm_draw_background1(Menu_pcx_name);             //load this here so if we abort after loading level, we restore the palette
4339         gr_palette_load(gr_palette);
4340    ExtGameStatus=GAMESTAT_JOIN_NETGAME;
4341         choice=newmenu_dotiny("NETGAMES", NULL,MAX_ACTIVE_NETGAMES+2, m, network_join_poll);
4342         SurfingNet=0;
4343
4344         if (choice==-1) {
4345                 Network_status = NETSTAT_MENU;
4346                 return; // they cancelled               
4347         }               
4348    choice-=2;
4349
4350         if (choice >=num_active_games)
4351         {
4352                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_INVALID_CHOICE);
4353                 goto remenu;
4354         }
4355
4356         // Choice has been made and looks legit
4357         if (Active_games[choice].game_status == NETSTAT_ENDLEVEL)
4358         {
4359                 nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_NET_GAME_BETWEEN2);
4360                 goto remenu;
4361         }
4362
4363         if (Active_games[choice].protocol_version != MULTI_PROTO_VERSION)
4364         {
4365                 if (Active_games[choice].protocol_version == 3) {
4366                         #ifndef SHAREWARE
4367                                 nm_messagebox(TXT_SORRY, 1, TXT_OK, "Your version of Descent 2\nis incompatible with the\nDemo version");
4368                         #endif
4369                 }
4370                 else if (Active_games[choice].protocol_version == 4) {
4371                         #ifdef SHAREWARE
4372                                 nm_messagebox(TXT_SORRY, 1, TXT_OK, "This Demo version of\nDescent 2 is incompatible\nwith the full commercial version");
4373                         #endif
4374                 }
4375                 else
4376                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_VERSION_MISMATCH);
4377
4378                 goto remenu;
4379         }
4380
4381 #ifndef SHAREWARE
4382         {       
4383                 // Check for valid mission name
4384                         mprintf((0, "Loading mission:%s.\n", Active_games[choice].mission_name));
4385                         if (!load_mission_by_name(Active_games[choice].mission_name))
4386                         {
4387                                 nm_messagebox(NULL, 1, TXT_OK, TXT_MISSION_NOT_FOUND);
4388                                 goto remenu;
4389                         }
4390             
4391             if (is_D2_OEM)
4392                 My_Seq.player.version_minor|=NETWORK_OEM;
4393     }
4394 #endif
4395
4396         if (is_D2_OEM)
4397         {
4398                 if (Active_games[choice].levelnum>8)
4399                  {
4400                                 nm_messagebox(NULL, 1, TXT_OK, "This OEM version only supports\nthe first 8 levels!");
4401                                 goto remenu;
4402                  }
4403         }
4404
4405         if (is_MAC_SHARE)
4406         {
4407                 if (Active_games[choice].levelnum > 4)
4408                 {
4409                         nm_messagebox(NULL, 1, TXT_OK, "This SHAREWARE version only supports\nthe first 4 levels!");
4410                         goto remenu;
4411                 }
4412         }
4413
4414      if (!network_wait_for_all_info (choice))
4415                 {
4416                   nm_messagebox (TXT_SORRY,1,TXT_OK,"There was a join error!");
4417                   Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4418                   goto remenu;
4419                 }       
4420           
4421           Network_status = NETSTAT_BROWSING; // We are looking at a game menu
4422  
4423      if (!can_join_netgame(&Active_games[choice],&ActiveNetPlayers[choice]))
4424                         {
4425                                 if (Active_games[choice].numplayers == Active_games[choice].max_numplayers)
4426                                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_GAME_FULL);
4427                                 else
4428                                         nm_messagebox(TXT_SORRY, 1, TXT_OK, TXT_IN_PROGRESS);
4429                                 goto remenu;
4430                         }
4431
4432         // Choice is valid, prepare to join in
4433
4434         memcpy(&Netgame, &Active_games[choice], sizeof(netgame_info));
4435    memcpy (&NetPlayers,&ActiveNetPlayers[choice],sizeof(AllNetPlayers_info));
4436
4437         Difficulty_level = Netgame.difficulty;
4438         MaxNumNetPlayers = Netgame.max_numplayers;
4439         change_playernum_to(1);
4440
4441         // Handle the extra data for the network driver
4442         // For the mcast4 driver, this is the game's multicast address, to
4443         // which the driver subscribes.
4444         if(ipx_handle_netgame_aux_data(Netgame.AuxData) < 0)
4445         {
4446                 Network_status = NETSTAT_BROWSING;
4447                 goto remenu;
4448         }
4449
4450         #ifdef MACINTOSH
4451
4452 // register the joining player with NBP.  This will have the nice effect of a player wanting to
4453 // join to be able to see the netgame if this player were to become the master.
4454
4455         if (Network_game_type == APPLETALK_GAME) {
4456                 OSErr err;
4457                 int count = 0;
4458                 fix t1;
4459                 
4460                 show_boxed_message("Registering Netgame");
4461                 do {
4462                         err = appletalk_register_netgame( Active_games[choice].game_name, TickCount() );
4463                         t1 = timer_get_fixed_seconds() + F1_0;
4464                         while ( timer_get_fixed_seconds() < t1 ) ;
4465                         count++;
4466                 } while ( (err == nbpDuplicate) && (count != MAX_REGISTER_TRIES) );
4467                 clear_boxed_message();
4468                 if ( (err == tooManyReqs) || (count == MAX_REGISTER_TRIES) ) {
4469                         nm_messagebox(NULL, 1, TXT_OK, "AppleTalk Network is too busy.\nPlease try again shortly.");
4470                         goto remenu;
4471                 }
4472         }
4473         #endif
4474
4475         network_set_game_mode(Netgame.gamemode);
4476
4477         network_AdjustMaxDataSize ();
4478
4479         StartNewLevel(Netgame.levelnum, 0);
4480
4481         return;         // look ma, we're in a game!!!
4482 }
4483
4484 void network_AdjustMaxDataSize ()
4485  {
4486           
4487    if (Netgame.ShortPackets)
4488         MaxXDataSize=NET_XDATA_SIZE;
4489    else
4490       MaxXDataSize=NET_XDATA_SIZE;
4491  }
4492   
4493
4494 fix StartWaitAllTime=0;
4495 int WaitAllChoice=0;
4496 #define ALL_INFO_REQUEST_INTERVAL F1_0*3
4497
4498 void network_wait_all_poll( int nitems, newmenu_item * menus, int * key, int citem )
4499  {
4500   static fix t1=0;
4501
4502   if (timer_get_approx_seconds() > t1+ALL_INFO_REQUEST_INTERVAL)
4503         {
4504                 network_send_all_info_request(PID_SEND_ALL_GAMEINFO,SecurityCheck);
4505                 t1 = timer_get_approx_seconds();
4506         }
4507
4508   network_do_big_wait(WaitAllChoice);  
4509    
4510   if(SecurityCheck==-1)
4511    *key=-2;
4512  }
4513  
4514 int network_wait_for_all_info (int choice)
4515  {
4516   int pick;
4517   
4518   newmenu_item m[2];
4519
4520   m[0].type=NM_TYPE_TEXT; m[0].text = "Press Escape to cancel";
4521
4522   WaitAllChoice=choice;
4523   StartWaitAllTime=timer_get_approx_seconds();
4524   SecurityCheck=Active_games[choice].Security;
4525   NetSecurityFlag=0;
4526
4527   GetMenu:
4528   pick=newmenu_do( NULL, "Connecting...", 1, m, network_wait_all_poll );
4529
4530   if (pick>-1 && SecurityCheck!=-1)
4531         goto GetMenu;
4532
4533   if (SecurityCheck==-1)
4534     {   
4535            SecurityCheck=0;     
4536            return (1);
4537          }
4538   SecurityCheck=0;      
4539   return (0);
4540  }
4541
4542 void network_do_big_wait(int choice)
4543 {
4544         int size;
4545         ubyte packet[IPX_MAX_DATA_SIZE],*data;
4546         AllNetPlayers_info *temp_info;
4547 #ifdef WORDS_BIGENDIAN
4548         AllNetPlayers_info info_struct;
4549 #endif
4550 #ifdef MACINTOSH
4551         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4552 #endif
4553   
4554         #ifdef MACINTOSH
4555         if (Network_game_type == APPLETALK_GAME)
4556                 size=appletalk_get_packet_data( apacket );
4557         else
4558         #endif
4559                 size=ipx_get_packet_data( packet );
4560         
4561   if (size>0)
4562         {
4563                 #ifdef MACINTOSH
4564                 if (Network_game_type == APPLETALK_GAME)
4565                         data = apacket;
4566                 else
4567                 #endif
4568                         data = packet;
4569   
4570          switch (data[0])
4571      {  
4572                 case PID_GAME_INFO:
4573
4574                 if (Network_game_type == IPX_GAME) {
4575                         receive_full_netgame_packet(data, &TempNetInfo);
4576                 } else {
4577                         memcpy((ubyte *)&TempNetInfo, data, sizeof(netgame_info));
4578                 }
4579                 mprintf ((0,"This is %s game with a security of %d\n",TempNetInfo.game_name,TempNetInfo.Security));
4580
4581       if (TempNetInfo.Security !=SecurityCheck)
4582                  {
4583                   mprintf ((0,"Bad security on big_wait...rejecting.\n"));      
4584                   break;
4585                  }
4586                       
4587       if (NetSecurityFlag==NETSECURITY_WAIT_FOR_GAMEINFO)
4588            {
4589                    if (TempPlayersInfo->Security==TempNetInfo.Security)
4590                         {
4591                           mprintf ((0,"EQUAL !: Game=%d Players=%d ",TempPlayersInfo->Security,TempNetInfo.Security));
4592                 if (TempPlayersInfo->Security==SecurityCheck)
4593                           {
4594                                         memcpy (&Active_games[choice],(ubyte *)&TempNetInfo,sizeof(netgame_info));
4595                                         memcpy (&ActiveNetPlayers[choice],TempPlayersInfo,sizeof(AllNetPlayers_info));
4596                                         SecurityCheck=-1;
4597                           }
4598                         }
4599            }
4600                 else
4601            {
4602               NetSecurityFlag=NETSECURITY_WAIT_FOR_PLAYERS;
4603               NetSecurityNum=TempNetInfo.Security;
4604                                     
4605               if (network_wait_for_playerinfo())
4606                         {
4607                            mprintf ((0,"HUH? Game=%d Player=%d\n",NetSecurityNum,TempPlayersInfo->Security));
4608                                 memcpy (&Active_games[choice],(ubyte *)&TempNetInfo,sizeof(netgame_info));
4609                                 memcpy (&ActiveNetPlayers[choice],TempPlayersInfo,sizeof(AllNetPlayers_info));
4610                                 SecurityCheck=-1;
4611                         }
4612               NetSecurityFlag=0;
4613               NetSecurityNum=0;
4614            }
4615         break;
4616       case PID_PLAYERSINFO:
4617                mprintf ((0,"Got a PID_PLAYERSINFO!\n"));
4618
4619                         if (Network_game_type == IPX_GAME) {
4620 #ifndef WORDS_BIGENDIAN
4621                                 temp_info=(AllNetPlayers_info *)data;
4622 #else
4623                                 receive_netplayers_packet(data, &info_struct);
4624                                 temp_info = &info_struct;
4625 #endif
4626                         } else {
4627                                 temp_info = (AllNetPlayers_info *)data;
4628                         }
4629                         if (temp_info->Security!=SecurityCheck) 
4630                                 break;     // If this isn't the guy we're looking for, move on
4631
4632                         memcpy (&TempPlayersBase,(ubyte *)&temp_info,sizeof(AllNetPlayers_info));
4633                         TempPlayersInfo=&TempPlayersBase;
4634                         WaitingForPlayerInfo=0;
4635                         NetSecurityNum=TempPlayersInfo->Security;
4636                         NetSecurityFlag=NETSECURITY_WAIT_FOR_GAMEINFO;
4637                         break;
4638            }
4639         }
4640 }
4641
4642 void network_leave_game()
4643
4644    int nsave;
4645                 
4646         network_do_frame(1, 1);
4647    
4648    #ifdef NETPROFILING
4649         fclose (SendLogFile);
4650            fclose (RecieveLogFile);
4651         #endif
4652
4653         if ((network_i_am_master()))
4654         {
4655                 while (Network_sending_extras>1 && Player_joining_extras!=-1)
4656                   network_send_extras();
4657    
4658                 Netgame.numplayers = 0;
4659            nsave=N_players;
4660            N_players=0;
4661                 network_send_game_info(NULL);
4662                 N_players=nsave;
4663                 
4664                 mprintf ((0,"HEY! I'm master and I've left.\n"));
4665         }
4666         
4667         Players[Player_num].connected = 0;
4668         network_send_endlevel_packet();
4669         change_playernum_to(0);
4670         Game_mode = GM_GAME_OVER;
4671         WriteConfigFile();
4672
4673 //      WIN(ipx_destroy_read_thread());
4674
4675         // Tell the network driver we're done with the game.
4676         // This is used by ipx_mcast4.c to unsubscribe from the game's
4677         // multicast session
4678         ipx_handle_leave_game();
4679
4680         network_flush();
4681 }
4682
4683 void network_flush()
4684 {
4685         #ifdef MACINTOSH
4686         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4687         #endif
4688         ubyte packet[IPX_MAX_DATA_SIZE];
4689
4690         #ifdef MACINTOSH
4691         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4692                 return;
4693         #endif
4694         
4695         if ( Network_game_type == IPX_GAME )
4696                 if (!Network_active) return;
4697
4698         #ifdef MACINTOSH
4699         if (Network_game_type == APPLETALK_GAME)
4700                 while (appletalk_get_packet_data(apacket) > 0) ;
4701         else
4702         #endif
4703                 while (ipx_get_packet_data(packet) > 0) ;
4704 }
4705
4706 void network_listen()
4707 {
4708         #ifdef MACINTOSH
4709         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4710         #endif
4711         int size;
4712         ubyte packet[IPX_MAX_DATA_SIZE];
4713         int i,loopmax=999;
4714
4715         if (Network_status==NETSTAT_PLAYING && Netgame.ShortPackets && !Network_send_objects)
4716          {
4717                 loopmax=N_players*Netgame.PacketsPerSec;
4718          }
4719         
4720         #ifdef MACINTOSH
4721         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4722                 return;
4723         #endif
4724
4725         if (Network_game_type == IPX_GAME)      
4726                 if (!Network_active) return;
4727
4728         if (!(Game_mode & GM_NETWORK) && (Function_mode == FMODE_GAME))
4729                 mprintf((0, "Calling network_listen() when not in net game.\n"));
4730
4731         WaitingForPlayerInfo=1;
4732         NetSecurityFlag=NETSECURITY_OFF;
4733
4734         i=1;
4735         if (Network_game_type == IPX_GAME) {
4736                 size = ipx_get_packet_data( packet );
4737                 while ( size > 0)       {
4738                         network_process_packet( packet, size );
4739                         if (++i>loopmax)
4740                          break;
4741                         size = ipx_get_packet_data( packet );
4742                 }
4743         #ifdef MACINTOSH
4744         } else {
4745                 size = appletalk_get_packet_data( apacket );
4746                 while ( size > 0)       {
4747                         network_process_packet( apacket, size );
4748                         if (++i>loopmax)
4749                          break;
4750                         size = appletalk_get_packet_data( apacket );
4751                 }
4752         #endif
4753         }
4754 }
4755
4756 int network_wait_for_playerinfo()
4757 {
4758         int size,retries=0;
4759         ubyte packet[IPX_MAX_DATA_SIZE];
4760         struct AllNetPlayers_info *TempInfo;
4761         fix basetime;
4762         ubyte id;
4763 #ifdef WORDS_BIGENDIAN
4764         AllNetPlayers_info info_struct;
4765 #endif
4766 #ifdef MACINTOSH
4767         ubyte apacket[APPLETALK_MAX_DATA_SIZE];
4768 #endif
4769
4770         #ifdef MACINTOSH
4771         if ( (Network_game_type == APPLETALK_GAME) && (Appletalk_active <= 0) )
4772                 return;
4773         #endif
4774
4775         if ( Network_game_type == IPX_GAME)
4776                 if (!Network_active) return(0);
4777                 
4778       //  if (!WaitingForPlayerInfo)
4779         // return (1);
4780
4781         if (!(Game_mode & GM_NETWORK) && (Function_mode == FMODE_GAME))
4782                 {
4783         mprintf((0, "Calling network_wait_for_playerinfo() when not in net game.\n"));
4784                 }       
4785         if (Network_status==NETSTAT_PLAYING)
4786          {
4787                   Int3(); //MY GOD! Get Jason...this is the source of many problems
4788              return (0);
4789          }
4790    basetime=timer_get_approx_seconds();
4791
4792    while (WaitingForPlayerInfo && retries<50 && (timer_get_approx_seconds()<(basetime+(F1_0*5))))
4793       {
4794                 if (Network_game_type == IPX_GAME) {
4795                         size = ipx_get_packet_data( packet );
4796                         id = packet[0];
4797                 } else {
4798                         #ifdef MACINTOSH
4799                         size = appletalk_get_packet_data( apacket );
4800                         id = apacket[0];
4801                         #endif
4802                 }
4803
4804         if (size>0 && id==PID_PLAYERSINFO)
4805         {
4806 #ifdef WORDS_BIGENDIAN
4807 #ifdef MACINTOSH
4808                 if (Network_game_type == APPLETALK_GAME) {
4809                         TempInfo = (AllNetPlayers_info *)apacket;
4810                 } else
4811 #endif
4812                 {
4813                         receive_netplayers_packet(packet, &info_struct);
4814                         TempInfo = &info_struct;
4815                 }
4816 #else
4817                 TempInfo=(AllNetPlayers_info *)packet;
4818 #endif
4819
4820                 retries++;
4821
4822             if (NetSecurityFlag==NETSECURITY_WAIT_FOR_PLAYERS)
4823              {
4824               if (NetSecurityNum==TempInfo->Security)
4825                {
4826                 mprintf ((0,"HEYEQUAL: Player=%d Game=%d\n",TempInfo->Security,NetSecurityNum));
4827                 memcpy (&TempPlayersBase,(ubyte *)TempInfo,sizeof(AllNetPlayers_info));
4828                 TempPlayersInfo=&TempPlayersBase;
4829                 NetSecurityFlag=NETSECURITY_OFF;
4830                 NetSecurityNum=0;
4831                 WaitingForPlayerInfo=0;
4832                 return (1);
4833                }
4834               else
4835                continue;
4836              }
4837             else
4838              {
4839               mprintf ((0,"I'm original!\n"));
4840
4841               NetSecurityNum=TempInfo->Security;
4842               NetSecurityFlag=NETSECURITY_WAIT_FOR_GAMEINFO;
4843            
4844               memcpy (&TempPlayersBase,(ubyte *)TempInfo,sizeof(AllNetPlayers_info));
4845               TempPlayersInfo=&TempPlayersBase;
4846               WaitingForPlayerInfo=0;
4847               return (1);
4848              }
4849            }
4850          }
4851    return (0);
4852   }
4853
4854
4855 void network_send_data( ubyte * ptr, int len, int urgent )
4856 {
4857         char check;
4858
4859    #ifdef NETPROFILING
4860            TTSent[ptr[0]]++;  
4861            fprintf (SendLogFile,"Packet type: %d Len:%d Urgent:%d TT=%d\n",ptr[0],len,urgent,TTSent[ptr[0]]);
4862            fflush (SendLogFile);
4863         #endif
4864     
4865         if (Endlevel_sequence)
4866                 return;
4867
4868         if (!MySyncPackInitialized)     {
4869                 MySyncPackInitialized = 1;
4870                 memset( &MySyncPack, 0, sizeof(frame_info) );
4871         }
4872         
4873         if (urgent)
4874                 PacketUrgent = 1;
4875
4876         if ((MySyncPack.data_size+len) > MaxXDataSize ) {
4877                 check = ptr[0];
4878                 network_do_frame(1, 0);
4879                 if (MySyncPack.data_size != 0) {
4880                         mprintf((0, "%d bytes were added to data by network_do_frame!\n", MySyncPack.data_size));
4881                         Int3();
4882                 }
4883 //              Int3();         // Trying to send too much!
4884 //              return;
4885                 mprintf((0, "Packet overflow, sending additional packet, type %d len %d.\n", ptr[0], len));
4886                 Assert(check == ptr[0]);
4887         }
4888
4889         Assert(MySyncPack.data_size+len <= MaxXDataSize);
4890
4891         memcpy( &MySyncPack.data[MySyncPack.data_size], ptr, len );
4892         MySyncPack.data_size += len;
4893 }
4894
4895 void network_timeout_player(int playernum)
4896 {
4897         // Remove a player from the game if we haven't heard from them in 
4898         // a long time.
4899         int i, n = 0;
4900
4901         Assert(playernum < N_players);
4902         Assert(playernum > -1);
4903
4904         network_disconnect_player(playernum);
4905         create_player_appearance_effect(&Objects[Players[playernum].objnum]);
4906
4907         digi_play_sample(SOUND_HUD_MESSAGE, F1_0);
4908
4909         HUD_init_message("%s %s", Players[playernum].callsign, TXT_DISCONNECTING);
4910         for (i = 0; i < N_players; i++)
4911                 if (Players[i].connected) 
4912                         n++;
4913
4914         if (n == 1)
4915         {
4916                 nm_messagebox(NULL, 1, TXT_OK, TXT_YOU_ARE_ONLY);
4917         }
4918 }
4919
4920 fix last_send_time = 0;
4921 fix last_timeout_check = 0;
4922
4923 #ifdef WORDS_BIGENDIAN
4924 void squish_short_frame_info(short_frame_info old_info, ubyte *data)
4925 {
4926         int loc = 0;
4927         int tmpi;
4928         short tmps;
4929         
4930         data[0] = old_info.type;                                            loc++;
4931         /* skip three for pad byte */                                       loc += 3;
4932         tmpi = INTEL_INT(old_info.numpackets);
4933         memcpy(&(data[loc]), &tmpi, 4);                                     loc += 4;
4934
4935         memcpy(&(data[loc]), old_info.thepos.bytemat, 9);                   loc += 9;
4936         tmps = INTEL_SHORT(old_info.thepos.xo);
4937         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4938         tmps = INTEL_SHORT(old_info.thepos.yo);
4939         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4940         tmps = INTEL_SHORT(old_info.thepos.zo);
4941         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4942         tmps = INTEL_SHORT(old_info.thepos.segment);
4943         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4944         tmps = INTEL_SHORT(old_info.thepos.velx);
4945         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4946         tmps = INTEL_SHORT(old_info.thepos.vely);
4947         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4948         tmps = INTEL_SHORT(old_info.thepos.velz);
4949         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4950
4951         tmps = INTEL_SHORT(old_info.data_size);
4952         memcpy(&(data[loc]), &tmps, 2);                                     loc += 2;
4953
4954         data[loc] = old_info.playernum;                                     loc++;
4955         data[loc] = old_info.obj_render_type;                               loc++;
4956         data[loc] = old_info.level_num;                                     loc++;
4957         memcpy(&(data[loc]), old_info.data, old_info.data_size);
4958 }
4959 #endif
4960
4961 char NakedBuf[NET_XDATA_SIZE+4];
4962 int NakedPacketLen=0;
4963 int NakedPacketDestPlayer=-1;
4964
4965 void network_do_frame(int force, int listen)
4966 {
4967         int i;
4968         short_frame_info ShortSyncPack;
4969         static fix LastEndlevel=0;
4970
4971         if (!(Game_mode&GM_NETWORK)) return;
4972
4973         if ((Network_status != NETSTAT_PLAYING) || (Endlevel_sequence)) // Don't send postion during escape sequence...
4974                 goto listen;
4975
4976   if (NakedPacketLen)
4977         {
4978                 Assert (NakedPacketDestPlayer>-1);
4979 //         mprintf ((0,"Sending a naked packet to %s (%d bytes)!\n",Players[NakedPacketDestPlayer].callsign,NakedPacketLen));
4980                 if (Network_game_type == IPX_GAME) 
4981                         ipx_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[NakedPacketDestPlayer].network.ipx.server, NetPlayers.players[NakedPacketDestPlayer].network.ipx.node,Players[NakedPacketDestPlayer].net_address );
4982                 #ifdef MACINTOSH
4983                 else
4984                         appletalk_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[NakedPacketDestPlayer].network.appletalk.node, NetPlayers.players[NakedPacketDestPlayer].network.appletalk.net,NetPlayers.players[NakedPacketDestPlayer].network.appletalk.socket );
4985                 #endif
4986                 NakedPacketLen=0;
4987                 NakedPacketDestPlayer=-1;
4988    }
4989   
4990    if (WaitForRefuseAnswer && timer_get_approx_seconds()>(RefuseTimeLimit+(F1_0*12)))
4991                 WaitForRefuseAnswer=0;
4992                         
4993         last_send_time += FrameTime;
4994         last_timeout_check += FrameTime;
4995
4996    // Send out packet PacksPerSec times per second maximum... unless they fire, then send more often...
4997    if ( (last_send_time>F1_0/Netgame.PacketsPerSec) || (Network_laser_fired) || force || PacketUrgent )       {        
4998                 if ( Players[Player_num].connected )    {
4999                         int objnum = Players[Player_num].objnum;
5000                         PacketUrgent = 0;
5001
5002                         if (listen) {
5003                                 multi_send_robot_frame(0);
5004                                 multi_send_fire();              // Do firing if needed..
5005                         }
5006
5007                         last_send_time = 0;
5008
5009                         if (Netgame.ShortPackets)
5010                         {
5011 #ifdef WORDS_BIGENDIAN
5012                                 ubyte send_data[IPX_MAX_DATA_SIZE];
5013                                 //int squished_size;
5014 #endif
5015                                 create_shortpos(&ShortSyncPack.thepos, &Objects[objnum], 0);
5016                                 ShortSyncPack.type                                      = PID_PDATA;
5017                                 ShortSyncPack.playernum                         = Player_num;
5018                                 ShortSyncPack.obj_render_type           = Objects[objnum].render_type;
5019                                 ShortSyncPack.level_num                         = Current_level_num;
5020                                 ShortSyncPack.data_size                         = MySyncPack.data_size;
5021                                 memcpy (&ShortSyncPack.data[0],&MySyncPack.data[0],MySyncPack.data_size);
5022
5023 // -- killed -- 2003-10-11 by Aaron
5024 // Use ipx_send_game_packet instead to send packets to everyone in the game.
5025 // Define in arch/*/*net.c
5026 #if 0
5027                                 for (i=0; i<N_players; i++ )    {
5028                                         if ( (Players[i].connected) && (i!=Player_num ) )       {
5029                                                 MySyncPack.numpackets = Players[i].n_packets_sent++;
5030                                                 ShortSyncPack.numpackets=MySyncPack.numpackets;
5031                                                 if (Network_game_type == IPX_GAME) {
5032 #ifndef WORDS_BIGENDIAN
5033                                                         ipx_send_packet_data( (ubyte *)&ShortSyncPack, sizeof(short_frame_info)-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5034 #else
5035                                                         squish_short_frame_info(ShortSyncPack, send_data);
5036                                                         ipx_send_packet_data( (ubyte *)send_data, IPX_SHORT_INFO_SIZE-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5037 #endif
5038                                                 #ifdef MACINTOSH
5039                                                 } else {
5040                                                         appletalk_send_packet_data( (ubyte *)&ShortSyncPack, sizeof(short_frame_info)-MaxXDataSize+MySyncPack.data_size, NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket );
5041                                                 #endif
5042                                                 }
5043                                         }
5044                                 }
5045 #else
5046                                 MySyncPack.numpackets = INTEL_INT(Players[0].n_packets_sent++);
5047                                 ShortSyncPack.numpackets = MySyncPack.numpackets;
5048 #ifndef WORDS_BIGENDIAN
5049                                 ipx_send_game_packet((ubyte*)&ShortSyncPack, sizeof(short_frame_info) - MaxXDataSize + MySyncPack.data_size);
5050 #else
5051                                 squish_short_frame_info(ShortSyncPack, send_data);
5052                                 ipx_send_game_packet((ubyte*)send_data, IPX_SHORT_INFO_SIZE-MaxXDataSize+MySyncPack.data_size);
5053 #endif
5054
5055 #endif
5056                         }
5057                         else  // If long packets
5058                         {
5059                                 int send_data_size;
5060                                 
5061                                 MySyncPack.type                                 = PID_PDATA;
5062                                 MySyncPack.playernum                    = Player_num;
5063                                 MySyncPack.obj_render_type              = Objects[objnum].render_type;
5064                                 MySyncPack.level_num                    = Current_level_num;
5065                                 MySyncPack.obj_segnum                   = Objects[objnum].segnum;
5066                                 MySyncPack.obj_pos                              = Objects[objnum].pos;
5067                                 MySyncPack.obj_orient                   = Objects[objnum].orient;
5068                                 MySyncPack.phys_velocity                = Objects[objnum].mtype.phys_info.velocity;
5069                                 MySyncPack.phys_rotvel                  = Objects[objnum].mtype.phys_info.rotvel;
5070                                 
5071                                 send_data_size = MySyncPack.data_size;                  // do this so correct size data is sent
5072
5073 #ifdef WORDS_BIGENDIAN                        // do the swap stuff
5074                                 if (Network_game_type == IPX_GAME) {
5075                                         MySyncPack.obj_segnum = INTEL_SHORT(MySyncPack.obj_segnum);
5076                                         MySyncPack.obj_pos.x = INTEL_INT((int)MySyncPack.obj_pos.x);
5077                                         MySyncPack.obj_pos.y = INTEL_INT((int)MySyncPack.obj_pos.y);
5078                                         MySyncPack.obj_pos.z = INTEL_INT((int)MySyncPack.obj_pos.z);
5079                                         
5080                                         MySyncPack.obj_orient.rvec.x = INTEL_INT((int)MySyncPack.obj_orient.rvec.x);
5081                                         MySyncPack.obj_orient.rvec.y = INTEL_INT((int)MySyncPack.obj_orient.rvec.y);
5082                                         MySyncPack.obj_orient.rvec.z = INTEL_INT((int)MySyncPack.obj_orient.rvec.z);
5083                                         MySyncPack.obj_orient.uvec.x = INTEL_INT((int)MySyncPack.obj_orient.uvec.x);
5084                                         MySyncPack.obj_orient.uvec.y = INTEL_INT((int)MySyncPack.obj_orient.uvec.y);
5085                                         MySyncPack.obj_orient.uvec.z = INTEL_INT((int)MySyncPack.obj_orient.uvec.z);
5086                                         MySyncPack.obj_orient.fvec.x = INTEL_INT((int)MySyncPack.obj_orient.fvec.x);
5087                                         MySyncPack.obj_orient.fvec.y = INTEL_INT((int)MySyncPack.obj_orient.fvec.y);
5088                                         MySyncPack.obj_orient.fvec.z = INTEL_INT((int)MySyncPack.obj_orient.fvec.z);
5089                                         
5090                                         MySyncPack.phys_velocity.x = INTEL_INT((int)MySyncPack.phys_velocity.x);
5091                                         MySyncPack.phys_velocity.y = INTEL_INT((int)MySyncPack.phys_velocity.y);
5092                                         MySyncPack.phys_velocity.z = INTEL_INT((int)MySyncPack.phys_velocity.z);
5093                                 
5094                                         MySyncPack.phys_rotvel.x = INTEL_INT((int)MySyncPack.phys_rotvel.x);
5095                                         MySyncPack.phys_rotvel.y = INTEL_INT((int)MySyncPack.phys_rotvel.y);
5096                                         MySyncPack.phys_rotvel.z = INTEL_INT((int)MySyncPack.phys_rotvel.z);
5097                                         
5098                                         MySyncPack.data_size = INTEL_SHORT(MySyncPack.data_size);
5099                                 }
5100 #endif
5101
5102 #if 0
5103                                 for (i=0; i<N_players; i++ )    {
5104                                         if ( (Players[i].connected) && (i!=Player_num ) )       {
5105                                                 if (Network_game_type == IPX_GAME)
5106                                                         MySyncPack.numpackets = INTEL_INT(Players[i].n_packets_sent);
5107                                                 else
5108                                                         MySyncPack.numpackets = Players[i].n_packets_sent;
5109
5110                                                 Players[i].n_packets_sent++;
5111                                                 if (Network_game_type == IPX_GAME)
5112                                                         ipx_send_packet_data( (ubyte *)&MySyncPack, sizeof(frame_info)-MaxXDataSize+send_data_size, NetPlayers.players[i].network.ipx.server, NetPlayers.players[i].network.ipx.node,Players[i].net_address );
5113                                                 #ifdef MACINTOSH
5114                                                 else
5115                                                         appletalk_send_packet_data( (ubyte *)&MySyncPack, sizeof(frame_info)-MaxXDataSize+send_data_size, NetPlayers.players[i].network.appletalk.node, NetPlayers.players[i].network.appletalk.net, NetPlayers.players[i].network.appletalk.socket);
5116                                                 #endif
5117                                         }
5118                                 }
5119 #else
5120                                 MySyncPack.numpackets = INTEL_INT(Players[0].n_packets_sent++);
5121                                 ipx_send_game_packet((ubyte*)&MySyncPack, sizeof(frame_info) - MaxXDataSize + send_data_size);
5122 #endif
5123                         }
5124
5125                         MySyncPack.data_size = 0;               // Start data over at 0 length.
5126                         if (Control_center_destroyed)
5127                         {
5128                                 if (Player_is_dead)
5129                                         Players[Player_num].connected=3;
5130                                 if (timer_get_approx_seconds() > (LastEndlevel+(F1_0/2)))
5131                                 {
5132                                         network_send_endlevel_packet();
5133                                         LastEndlevel=timer_get_approx_seconds();
5134                                 }
5135                         }
5136                         //mprintf( (0, "Packet has %d bytes appended (TS=%d)\n", MySyncPack.data_size, sizeof(frame_info)-MaxXDataSize+MySyncPack.data_size ));
5137                 }
5138         }
5139    
5140         if (!listen)
5141                 return;
5142
5143         if ((last_timeout_check > F1_0) && !(Control_center_destroyed))
5144         {
5145                 fix approx_time = timer_get_approx_seconds();
5146                 // Check for player timeouts
5147                 for (i = 0; i < N_players; i++)
5148                 {
5149                         if ((i != Player_num) && (Players[i].connected == 1))
5150                         {
5151                                 if ((LastPacketTime[i] == 0) || (LastPacketTime[i] > approx_time))
5152                                 {
5153                                         LastPacketTime[i] = approx_time;
5154                                         continue;
5155                                 }
5156                                 if ((approx_time - LastPacketTime[i]) > (15*F1_0))
5157                                         network_timeout_player(i);
5158                         }
5159                 }
5160                 last_timeout_check = 0;
5161         }
5162
5163 listen:
5164         if (!listen)
5165         {
5166                 MySyncPack.data_size = 0;
5167                 return;
5168         }
5169         network_listen();
5170
5171    if (VerifyPlayerJoined!=-1 && !(FrameCount & 63))
5172           resend_sync_due_to_packet_loss_for_allender(); // This will resend to network_player_rejoining
5173  
5174         if (Network_send_objects)
5175                 network_send_objects();
5176
5177         if (Network_sending_extras && VerifyPlayerJoined==-1)
5178         {
5179           network_send_extras();
5180           return;
5181     }
5182 }
5183
5184 int missed_packets = 0;
5185
5186 int ConsistencyCount = 0;
5187
5188 void network_consistency_error(void)
5189 {
5190         if (++ConsistencyCount < 10)
5191                 return;
5192
5193         Function_mode = FMODE_MENU;
5194         #ifndef MACINTOSH
5195         nm_messagebox(NULL, 1, TXT_OK, TXT_CONSISTENCY_ERROR);
5196         #else
5197         nm_messagebox(NULL, 1, TXT_OK, "Failed to join the netgame.\nYou are missing packets.  Check\nyour network connection and\ntry again.");
5198         #endif
5199         Function_mode = FMODE_GAME;
5200         ConsistencyCount = 0;
5201         multi_quit_game = 1;
5202         multi_leave_menu = 1;
5203         multi_reset_stuff();
5204         Function_mode = FMODE_MENU;
5205 }
5206
5207 void network_process_pdata (char *data)
5208  {
5209   Assert (Game_mode & GM_NETWORK);
5210  
5211   if (Netgame.ShortPackets)
5212         network_read_pdata_short_packet ((short_frame_info *)data);
5213   else
5214         network_read_pdata_packet ((frame_info *)data);
5215  }
5216
5217 void network_read_pdata_packet(frame_info *pd )
5218 {
5219         int TheirPlayernum;
5220         int TheirObjnum;
5221         object * TheirObj = NULL;
5222         
5223 // frame_info should be aligned...for mac, make the necessary adjustments
5224 #ifdef WORDS_BIGENDIAN
5225         if (Network_game_type == IPX_GAME) {
5226                 pd->numpackets = INTEL_INT(pd->numpackets);
5227                 pd->obj_pos.x = INTEL_INT(pd->obj_pos.x);
5228                 pd->obj_pos.y = INTEL_INT(pd->obj_pos.y);
5229                 pd->obj_pos.z = INTEL_INT(pd->obj_pos.z);
5230         
5231                 pd->obj_orient.rvec.x = (fix)INTEL_INT((int)pd->obj_orient.rvec.x);
5232                 pd->obj_orient.rvec.y = (fix)INTEL_INT((int)pd->obj_orient.rvec.y);
5233                 pd->obj_orient.rvec.z = (fix)INTEL_INT((int)pd->obj_orient.rvec.z);
5234                 pd->obj_orient.uvec.x = (fix)INTEL_INT((int)pd->obj_orient.uvec.x);
5235                 pd->obj_orient.uvec.y = (fix)INTEL_INT((int)pd->obj_orient.uvec.y);
5236                 pd->obj_orient.uvec.z = (fix)INTEL_INT((int)pd->obj_orient.uvec.z);
5237                 pd->obj_orient.fvec.x = (fix)INTEL_INT((int)pd->obj_orient.fvec.x);
5238                 pd->obj_orient.fvec.y = (fix)INTEL_INT((int)pd->obj_orient.fvec.y);
5239                 pd->obj_orient.fvec.z = (fix)INTEL_INT((int)pd->obj_orient.fvec.z);
5240         
5241                 pd->phys_velocity.x = (fix)INTEL_INT((int)pd->phys_velocity.x);
5242                 pd->phys_velocity.y = (fix)INTEL_INT((int)pd->phys_velocity.y);
5243                 pd->phys_velocity.z = (fix)INTEL_INT((int)pd->phys_velocity.z);
5244         
5245                 pd->phys_rotvel.x = (fix)INTEL_INT((int)pd->phys_rotvel.x);
5246                 pd->phys_rotvel.y = (fix)INTEL_INT((int)pd->phys_rotvel.y);
5247                 pd->phys_rotvel.z = (fix)INTEL_INT((int)pd->phys_rotvel.z);
5248                 
5249                 pd->obj_segnum = INTEL_SHORT(pd->obj_segnum);
5250                 pd->data_size = INTEL_SHORT(pd->data_size);
5251         }
5252 #endif
5253
5254         TheirPlayernum = pd->playernum;
5255         TheirObjnum = Players[pd->playernum].objnum;
5256         
5257         if (TheirPlayernum < 0) {
5258                 Int3(); // This packet is bogus!!
5259                 return;
5260         }
5261
5262    if (VerifyPlayerJoined!=-1 && TheirPlayernum==VerifyPlayerJoined)
5263          {
5264           // Hurray! Someone really really got in the game (I think).
5265      mprintf ((0,"Hurray! VPJ (%d) reset!\n",VerifyPlayerJoined));
5266      VerifyPlayerJoined=-1;
5267          }
5268  
5269         if (!multi_quit_game && (TheirPlayernum >= N_players)) {
5270                 if (Network_status!=NETSTAT_WAITING)
5271                  {
5272                         Int3(); // We missed an important packet!
5273                         network_consistency_error();
5274                         return;
5275                  }
5276                 else
5277                  return;
5278         }
5279         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
5280                 int old_Endlevel_sequence = Endlevel_sequence;
5281                 Endlevel_sequence = 1;
5282                 if ( pd->data_size>0 )  {
5283                         // pass pd->data to some parser function....
5284                         multi_process_bigdata( pd->data, pd->data_size );
5285                 }
5286                 Endlevel_sequence = old_Endlevel_sequence;
5287                 return;
5288         }
5289 //      mprintf((0, "Gametime = %d, Frametime = %d.\n", GameTime, FrameTime));
5290
5291         if ((sbyte)pd->level_num != Current_level_num)
5292         {
5293                 mprintf((0, "Got frame packet from player %d wrong level %d!\n", pd->playernum, pd->level_num));
5294                 return;
5295         }
5296
5297         TheirObj = &Objects[TheirObjnum];
5298
5299         //------------- Keep track of missed packets -----------------
5300         Players[TheirPlayernum].n_packets_got++;
5301         TotalPacketsGot++;
5302         LastPacketTime[TheirPlayernum] = timer_get_approx_seconds();
5303
5304         if  ( pd->numpackets != Players[TheirPlayernum].n_packets_got ) {
5305                 int missed_packets;
5306                 
5307                 missed_packets = pd->numpackets-Players[TheirPlayernum].n_packets_got;
5308                 if ((pd->numpackets-Players[TheirPlayernum].n_packets_got)>0)
5309                         TotalMissedPackets += pd->numpackets-Players[TheirPlayernum].n_packets_got;
5310
5311                         if ( missed_packets > 0 )       
5312                                 mprintf(( 0, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets ));
5313                         else
5314                                 mprintf( (0, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets ));
5315
5316                 #ifdef MACINTOSH
5317                 #ifdef APPLETALK_DEBUG
5318                 if (Network_game_type == APPLETALK_GAME) {
5319                         if ( missed_packets > 0 )       
5320                                 fprintf( at_fp, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets );
5321                         else
5322                                 fprintf( at_fp, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets );
5323                 }
5324                 #endif
5325                 
5326                 #ifdef IPX_DEBUG
5327                 if (Network_game_type == IPX_GAME) {
5328                         if ( missed_packets > 0 )       
5329                                 fprintf( ipx_fp, "Missed %d packets from player #%d (%d total)\n", pd->numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets );
5330                         else
5331                                 fprintf( ipx_fp, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-pd->numpackets, TheirPlayernum, missed_packets );
5332                 }
5333                 #endif
5334                 #endif
5335
5336                 Players[TheirPlayernum].n_packets_got = pd->numpackets;
5337         }
5338
5339         //------------ Read the player's ship's object info ----------------------
5340         TheirObj->pos                           = pd->obj_pos;
5341         TheirObj->orient                        = pd->obj_orient;
5342         TheirObj->mtype.phys_info.velocity = pd->phys_velocity;
5343         TheirObj->mtype.phys_info.rotvel = pd->phys_rotvel;
5344
5345         if ((TheirObj->render_type != pd->obj_render_type) && (pd->obj_render_type == RT_POLYOBJ))
5346                 multi_make_ghost_player(TheirPlayernum);
5347
5348         obj_relink(TheirObjnum,pd->obj_segnum);
5349
5350         if (TheirObj->movement_type == MT_PHYSICS)
5351                 set_thrust_from_velocity(TheirObj);
5352
5353         //------------ Welcome them back if reconnecting --------------
5354         if (!Players[TheirPlayernum].connected) {
5355                 Players[TheirPlayernum].connected = 1;
5356
5357                 if (Newdemo_state == ND_STATE_RECORDING)
5358                         newdemo_record_multi_reconnect(TheirPlayernum);
5359
5360                 multi_make_ghost_player(TheirPlayernum);
5361
5362                 create_player_appearance_effect(&Objects[TheirObjnum]);
5363
5364                 digi_play_sample( SOUND_HUD_MESSAGE, F1_0);
5365                 
5366                 ClipRank (&NetPlayers.players[TheirPlayernum].rank);
5367
5368                 if (FindArg("-norankings"))      
5369                         HUD_init_message( "'%s' %s", Players[TheirPlayernum].callsign, TXT_REJOIN );
5370                 else
5371                         HUD_init_message( "%s'%s' %s", RankStrings[NetPlayers.players[TheirPlayernum].rank],Players[TheirPlayernum].callsign, TXT_REJOIN );
5372
5373
5374                 multi_send_score();
5375         }
5376
5377         //------------ Parse the extra data at the end ---------------
5378
5379         if ( pd->data_size>0 )  {
5380                 // pass pd->data to some parser function....
5381                 multi_process_bigdata( pd->data, pd->data_size );
5382         }
5383
5384 }
5385
5386 #ifdef WORDS_BIGENDIAN
5387 void get_short_frame_info(ubyte *old_info, short_frame_info *new_info)
5388 {
5389         int loc = 0;
5390         
5391         new_info->type = old_info[loc];                                     loc++;
5392         /* skip three for pad byte */                                       loc += 3;
5393         memcpy(&(new_info->numpackets), &(old_info[loc]), 4);               loc += 4;
5394         new_info->numpackets = INTEL_INT(new_info->numpackets);
5395         memcpy(new_info->thepos.bytemat, &(old_info[loc]), 9);              loc += 9;
5396         memcpy(&(new_info->thepos.xo), &(old_info[loc]), 2);                loc += 2;
5397         memcpy(&(new_info->thepos.yo), &(old_info[loc]), 2);                loc += 2;
5398         memcpy(&(new_info->thepos.zo), &(old_info[loc]), 2);                loc += 2;
5399         memcpy(&(new_info->thepos.segment), &(old_info[loc]), 2);           loc += 2;
5400         memcpy(&(new_info->thepos.velx), &(old_info[loc]), 2);              loc += 2;
5401         memcpy(&(new_info->thepos.vely), &(old_info[loc]), 2);              loc += 2;
5402         memcpy(&(new_info->thepos.velz), &(old_info[loc]), 2);              loc += 2;
5403         new_info->thepos.xo = INTEL_SHORT(new_info->thepos.xo);
5404         new_info->thepos.yo = INTEL_SHORT(new_info->thepos.yo);
5405         new_info->thepos.zo = INTEL_SHORT(new_info->thepos.zo);
5406         new_info->thepos.segment = INTEL_SHORT(new_info->thepos.segment);
5407         new_info->thepos.velx = INTEL_SHORT(new_info->thepos.velx);
5408         new_info->thepos.vely = INTEL_SHORT(new_info->thepos.vely);
5409         new_info->thepos.velz = INTEL_SHORT(new_info->thepos.velz);
5410
5411         memcpy(&(new_info->data_size), &(old_info[loc]), 2);                loc += 2;
5412         new_info->data_size = INTEL_SHORT(new_info->data_size);
5413         new_info->playernum = old_info[loc];                                loc++;
5414         new_info->obj_render_type = old_info[loc];                          loc++;
5415         new_info->level_num = old_info[loc];                                loc++;
5416         memcpy(new_info->data, &(old_info[loc]), new_info->data_size);
5417 }
5418 #else
5419 #define get_short_frame_info(old_info, new_info) \
5420         memcpy(new_info, old_info, sizeof(short_frame_info))
5421 #endif
5422
5423 void network_read_pdata_short_packet(short_frame_info *pd )
5424 {
5425         int TheirPlayernum;
5426         int TheirObjnum;
5427         object * TheirObj = NULL;
5428         short_frame_info new_pd;
5429
5430 // short frame info is not aligned because of shortpos.  The mac
5431 // will call totally hacked and gross function to fix this up.
5432
5433         if (Network_game_type == IPX_GAME) {
5434                 get_short_frame_info((ubyte *)pd, &new_pd);
5435         } else {
5436                 memcpy(&new_pd, (ubyte *)pd, sizeof(short_frame_info));
5437         }
5438
5439         TheirPlayernum = new_pd.playernum;
5440         TheirObjnum = Players[new_pd.playernum].objnum;
5441
5442         if (TheirPlayernum < 0) {
5443                 Int3(); // This packet is bogus!!
5444                 return;
5445         }
5446         if (!multi_quit_game && (TheirPlayernum >= N_players)) {
5447                 if (Network_status!=NETSTAT_WAITING)
5448                  {
5449                         Int3(); // We missed an important packet!
5450                         network_consistency_error();
5451                         return;
5452                  }
5453                 else
5454                  return;
5455         }
5456
5457    if (VerifyPlayerJoined!=-1 && TheirPlayernum==VerifyPlayerJoined)
5458          {
5459           // Hurray! Someone really really got in the game (I think).
5460       mprintf ((0,"Hurray! VPJ (%d) reset!\n",VerifyPlayerJoined));
5461       VerifyPlayerJoined=-1;
5462          }
5463
5464         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
5465                 int old_Endlevel_sequence = Endlevel_sequence;
5466                 Endlevel_sequence = 1;
5467                 if ( new_pd.data_size>0 )       {
5468                         // pass pd->data to some parser function....
5469                         multi_process_bigdata( new_pd.data, new_pd.data_size );
5470                 }
5471                 Endlevel_sequence = old_Endlevel_sequence;
5472                 return;
5473         }
5474 //      mprintf((0, "Gametime = %d, Frametime = %d.\n", GameTime, FrameTime));
5475
5476         if ((sbyte)new_pd.level_num != Current_level_num)
5477         {
5478                 mprintf((0, "Got frame packet from player %d wrong level %d!\n", new_pd.playernum, new_pd.level_num));
5479                 return;
5480         }
5481
5482         TheirObj = &Objects[TheirObjnum];
5483
5484         //------------- Keep track of missed packets -----------------
5485         Players[TheirPlayernum].n_packets_got++;
5486         TotalPacketsGot++;
5487         LastPacketTime[TheirPlayernum] = timer_get_approx_seconds();
5488
5489         if  ( new_pd.numpackets != Players[TheirPlayernum].n_packets_got )      {
5490                 int missed_packets;
5491         
5492                 missed_packets = new_pd.numpackets-Players[TheirPlayernum].n_packets_got;
5493                 if ((new_pd.numpackets-Players[TheirPlayernum].n_packets_got)>0)
5494                         TotalMissedPackets += new_pd.numpackets-Players[TheirPlayernum].n_packets_got;
5495
5496                 if ( missed_packets > 0 )       
5497                         mprintf( (0, "Missed %d packets from player #%d (%d total)\n", new_pd.numpackets-Players[TheirPlayernum].n_packets_got, TheirPlayernum, missed_packets ));
5498                 else
5499                         mprintf( (0, "Got %d late packets from player #%d (%d total)\n", Players[TheirPlayernum].n_packets_got-new_pd.numpackets, TheirPlayernum, missed_packets ));
5500
5501                 Players[TheirPlayernum].n_packets_got = new_pd.numpackets;
5502         }
5503
5504         //------------ Read the player's ship's object info ----------------------
5505
5506         extract_shortpos(TheirObj, &new_pd.thepos, 0);
5507
5508         if ((TheirObj->render_type != new_pd.obj_render_type) && (new_pd.obj_render_type == RT_POLYOBJ))
5509                 multi_make_ghost_player(TheirPlayernum);
5510
5511         if (TheirObj->movement_type == MT_PHYSICS)
5512                 set_thrust_from_velocity(TheirObj);
5513
5514         //------------ Welcome them back if reconnecting --------------
5515         if (!Players[TheirPlayernum].connected) {
5516                 Players[TheirPlayernum].connected = 1;
5517
5518                 if (Newdemo_state == ND_STATE_RECORDING)
5519                         newdemo_record_multi_reconnect(TheirPlayernum);
5520
5521                 multi_make_ghost_player(TheirPlayernum);
5522
5523                 create_player_appearance_effect(&Objects[TheirObjnum]);
5524
5525                 digi_play_sample( SOUND_HUD_MESSAGE, F1_0);
5526                 ClipRank (&NetPlayers.players[TheirPlayernum].rank);
5527                 
5528                 if (FindArg("-norankings"))
5529                         HUD_init_message( "'%s' %s", Players[TheirPlayernum].callsign, TXT_REJOIN );
5530                 else
5531                         HUD_init_message( "%s'%s' %s", RankStrings[NetPlayers.players[TheirPlayernum].rank],Players[TheirPlayernum].callsign, TXT_REJOIN );
5532
5533
5534                 multi_send_score();
5535         }
5536
5537         //------------ Parse the extra data at the end ---------------
5538
5539         if ( new_pd.data_size>0 )       {
5540                 // pass pd->data to some parser function....
5541                 multi_process_bigdata( new_pd.data, new_pd.data_size );
5542         }
5543
5544 }
5545
5546   
5547 void network_set_power (void)
5548  {
5549   int opt=0,choice,opt_primary,opt_second,opt_power;
5550   newmenu_item m[40];
5551   
5552   opt_primary=opt;
5553   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Laser upgrade"; m[opt].value=Netgame.DoLaserUpgrade; opt++;
5554   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Super lasers"; m[opt].value=Netgame.DoSuperLaser; opt++;
5555   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Quad Lasers"; m[opt].value=Netgame.DoQuadLasers; opt++;
5556   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Vulcan cannon"; m[opt].value=Netgame.DoVulcan; opt++;
5557   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Spreadfire cannon"; m[opt].value=Netgame.DoSpread; opt++;
5558   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Plasma cannon"; m[opt].value=Netgame.DoPlasma; opt++;
5559   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Fusion cannon"; m[opt].value=Netgame.DoFusions; opt++;
5560   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Gauss cannon"; m[opt].value=Netgame.DoGauss; opt++;
5561   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Helix cannon"; m[opt].value=Netgame.DoHelix; opt++;
5562   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Phoenix cannon"; m[opt].value=Netgame.DoPhoenix; opt++;
5563   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Omega cannon"; m[opt].value=Netgame.DoOmega; opt++;
5564   
5565   opt_second=opt;   
5566   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Homing Missiles"; m[opt].value=Netgame.DoHoming; opt++;
5567   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Proximity Bombs"; m[opt].value=Netgame.DoProximity; opt++;
5568   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Smart Missiles"; m[opt].value=Netgame.DoSmarts; opt++;
5569   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Mega Missiles"; m[opt].value=Netgame.DoMegas; opt++;
5570   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Flash Missiles"; m[opt].value=Netgame.DoFlash; opt++;
5571   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Guided Missiles"; m[opt].value=Netgame.DoGuided; opt++;
5572   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Smart Mines"; m[opt].value=Netgame.DoSmartMine; opt++;
5573   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Mercury Missiles"; m[opt].value=Netgame.DoMercury; opt++;
5574   m[opt].type = NM_TYPE_CHECK; m[opt].text = "EarthShaker Missiles"; m[opt].value=Netgame.DoEarthShaker; opt++;
5575
5576   opt_power=opt;
5577   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Invulnerability"; m[opt].value=Netgame.DoInvulnerability; opt++;
5578   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Cloaking"; m[opt].value=Netgame.DoCloak; opt++;
5579   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Afterburners"; m[opt].value=Netgame.DoAfterburner; opt++;
5580   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Ammo rack"; m[opt].value=Netgame.DoAmmoRack; opt++;
5581   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Energy Converter"; m[opt].value=Netgame.DoConverter; opt++;
5582   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Headlight"; m[opt].value=Netgame.DoHeadlight; opt++;
5583   
5584   choice = newmenu_do(NULL, "Objects to allow", opt, m, NULL);
5585
5586   Netgame.DoLaserUpgrade=m[opt_primary].value; 
5587   Netgame.DoSuperLaser=m[opt_primary+1].value;
5588   Netgame.DoQuadLasers=m[opt_primary+2].value;  
5589   Netgame.DoVulcan=m[opt_primary+3].value;
5590   Netgame.DoSpread=m[opt_primary+4].value;
5591   Netgame.DoPlasma=m[opt_primary+5].value;
5592   Netgame.DoFusions=m[opt_primary+6].value;
5593   Netgame.DoGauss=m[opt_primary+7].value;
5594   Netgame.DoHelix=m[opt_primary+8].value;
5595   Netgame.DoPhoenix=m[opt_primary+9].value;
5596   Netgame.DoOmega=m[opt_primary+10].value;
5597   
5598   Netgame.DoHoming=m[opt_second].value;
5599   Netgame.DoProximity=m[opt_second+1].value;
5600   Netgame.DoSmarts=m[opt_second+2].value;
5601   Netgame.DoMegas=m[opt_second+3].value;
5602   Netgame.DoFlash=m[opt_second+4].value;
5603   Netgame.DoGuided=m[opt_second+5].value;
5604   Netgame.DoSmartMine=m[opt_second+6].value;
5605   Netgame.DoMercury=m[opt_second+7].value;
5606   Netgame.DoEarthShaker=m[opt_second+8].value;
5607
5608   Netgame.DoInvulnerability=m[opt_power].value;
5609   Netgame.DoCloak=m[opt_power+1].value;
5610   Netgame.DoAfterburner=m[opt_power+2].value;
5611   Netgame.DoAmmoRack=m[opt_power+3].value;
5612   Netgame.DoConverter=m[opt_power+4].value;     
5613   Netgame.DoHeadlight=m[opt_power+5].value;     
5614   
5615  }
5616
5617 void SetAllAllowablesTo (int on)
5618  {
5619   last_cinvul = control_invul_time = 0;   //default to zero
5620    
5621   Netgame.DoMegas=Netgame.DoSmarts=Netgame.DoFusions=Netgame.DoHelix=\
5622   Netgame.DoPhoenix=Netgame.DoCloak=Netgame.DoInvulnerability=\
5623   Netgame.DoAfterburner=Netgame.DoGauss=Netgame.DoVulcan=Netgame.DoPlasma=on;
5624
5625   Netgame.DoOmega=Netgame.DoSuperLaser=Netgame.DoProximity=\
5626   Netgame.DoSpread=Netgame.DoMercury=Netgame.DoSmartMine=Netgame.DoFlash=\
5627   Netgame.DoGuided=Netgame.DoEarthShaker=on;
5628   
5629   Netgame.DoConverter=Netgame.DoAmmoRack=Netgame.DoHeadlight=on;
5630   Netgame.DoHoming=Netgame.DoLaserUpgrade=Netgame.DoQuadLasers=on;
5631   Netgame.BrightPlayers=Netgame.invul=on;
5632  }
5633
5634 fix LastPTA;
5635 int LastKillGoal;
5636
5637 // Jeez -- mac compiler can't handle all of these on the same decl line.
5638 int opt_setpower,opt_playtime,opt_killgoal,opt_socket,opt_marker_view,opt_light,opt_show_on_map;
5639 int opt_difficulty,opt_packets,opt_short_packets, opt_bright,opt_start_invul;
5640 int opt_show_names;
5641
5642 void network_more_options_poll( int nitems, newmenu_item * menus, int * key, int citem );
5643   
5644 void network_more_game_options ()
5645  {
5646   int opt=0,i;
5647   char PlayText[80],KillText[80],srinvul[50],socket_string[5],packstring[5];
5648   newmenu_item m[21];
5649
5650   sprintf (socket_string,"%d",Network_socket);
5651   sprintf (packstring,"%d",Netgame.PacketsPerSec);
5652
5653   opt_difficulty = opt;
5654   m[opt].type = NM_TYPE_SLIDER; m[opt].value=netgame_difficulty; m[opt].text=TXT_DIFFICULTY; m[opt].min_value=0; m[opt].max_value=(NDL-1); opt++;
5655
5656   opt_cinvul = opt;
5657   sprintf( srinvul, "%s: %d %s", TXT_REACTOR_LIFE, control_invul_time*5, TXT_MINUTES_ABBREV );
5658   m[opt].type = NM_TYPE_SLIDER; m[opt].value=control_invul_time; m[opt].text= srinvul; m[opt].min_value=0; m[opt].max_value=10; opt++;
5659
5660   opt_playtime=opt;
5661   sprintf( PlayText, "Max time: %d %s", Netgame.PlayTimeAllowed*5, TXT_MINUTES_ABBREV );
5662   m[opt].type = NM_TYPE_SLIDER; m[opt].value=Netgame.PlayTimeAllowed; m[opt].text= PlayText; m[opt].min_value=0; m[opt].max_value=10; opt++;
5663
5664   opt_killgoal=opt;
5665   sprintf( KillText, "Kill Goal: %d kills", Netgame.KillGoal*5);
5666   m[opt].type = NM_TYPE_SLIDER; m[opt].value=Netgame.KillGoal; m[opt].text= KillText; m[opt].min_value=0; m[opt].max_value=10; opt++;
5667
5668   opt_start_invul=opt;
5669   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Invulnerable when reappearing"; m[opt].value=Netgame.invul; opt++;
5670         
5671   opt_marker_view = opt;
5672   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Allow camera views from Markers"; m[opt].value=Netgame.Allow_marker_view; opt++;
5673   opt_light = opt;
5674   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Indestructible lights"; m[opt].value=Netgame.AlwaysLighting; opt++;
5675
5676   opt_bright = opt;
5677   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Bright player ships"; m[opt].value=Netgame.BrightPlayers; opt++;
5678   
5679   opt_show_names=opt;
5680   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Show enemy names on HUD"; m[opt].value=Netgame.ShowAllNames; opt++;
5681
5682   opt_show_on_map=opt;
5683   m[opt].type = NM_TYPE_CHECK; m[opt].text = TXT_SHOW_ON_MAP; m[opt].value=(Netgame.game_flags & NETGAME_FLAG_SHOW_MAP); opt_show_on_map=opt; opt++;
5684
5685   opt_short_packets=opt;
5686   m[opt].type = NM_TYPE_CHECK; m[opt].text = "Short packets"; m[opt].value=Netgame.ShortPackets; opt++;
5687
5688   opt_setpower = opt;
5689   m[opt].type = NM_TYPE_MENU;  m[opt].text = "Set Objects allowed..."; opt++;
5690
5691   if (Network_game_type == IPX_GAME) {
5692           m[opt].type = NM_TYPE_TEXT; m[opt].text = "Network socket"; opt++;
5693           opt_socket = opt;
5694           m[opt].type = NM_TYPE_INPUT; m[opt].text = socket_string; m[opt].text_len=4; opt++;
5695   }
5696
5697   m[opt].type = NM_TYPE_TEXT; m[opt].text = "Packets per second (2 - 20)"; opt++;
5698   opt_packets=opt;
5699   m[opt].type = NM_TYPE_INPUT; m[opt].text=packstring; m[opt].text_len=2; opt++;
5700
5701   LastKillGoal=Netgame.KillGoal;
5702   LastPTA=Netgame.PlayTimeAllowed;
5703
5704   menu:
5705
5706   ExtGameStatus=GAMESTAT_MORE_NETGAME_OPTIONS; 
5707   i = newmenu_do1( NULL, "Additional netgame options", opt, m, network_more_options_poll, 0 );
5708
5709    //control_invul_time = atoi( srinvul )*60*F1_0;
5710     control_invul_time = m[opt_cinvul].value;
5711     Netgame.control_invul_time = control_invul_time*5*F1_0*60;
5712
5713   if (i==opt_setpower)
5714    {
5715     network_set_power ();
5716     goto menu;
5717    }
5718
5719   Netgame.PacketsPerSec=atoi(packstring);
5720
5721   if (Netgame.PacketsPerSec>20)
5722         {
5723          Netgame.PacketsPerSec=20;
5724          nm_messagebox(TXT_ERROR, 1, TXT_OK, "Packet value out of range\nSetting value to 20");
5725         }
5726   if (Netgame.PacketsPerSec<2)
5727         {
5728           nm_messagebox(TXT_ERROR, 1, TXT_OK, "Packet value out of range\nSetting value to 2");
5729           Netgame.PacketsPerSec=2;      
5730         }
5731
5732   mprintf ((0,"Hey! Sending out %d packets per second\n",Netgame.PacketsPerSec));
5733
5734         if (Network_game_type == IPX_GAME) { 
5735                 if ((atoi(socket_string))!=Network_socket) {
5736                         Network_socket=atoi(socket_string);
5737                         ipx_change_default_socket( IPX_DEFAULT_SOCKET + Network_socket );
5738                 }
5739         }
5740
5741   Netgame.invul=m[opt_start_invul].value;       
5742   Netgame.BrightPlayers=m[opt_bright].value;
5743   Netgame.ShortPackets=m[opt_short_packets].value;
5744   Netgame.ShowAllNames=m[opt_show_names].value;
5745   network_AdjustMaxDataSize();
5746
5747   Netgame.Allow_marker_view=m[opt_marker_view].value;   
5748   Netgame.AlwaysLighting=m[opt_light].value;     
5749   netgame_difficulty=Difficulty_level = m[opt_difficulty].value;
5750   if (m[opt_show_on_map].value)
5751         Netgame.game_flags |= NETGAME_FLAG_SHOW_MAP;
5752         
5753         
5754  }
5755
5756 void network_more_options_poll( int nitems, newmenu_item * menus, int * key, int citem )
5757  {
5758    if ( last_cinvul != menus[opt_cinvul].value )   {
5759         sprintf( menus[opt_cinvul].text, "%s: %d %s", TXT_REACTOR_LIFE, menus[opt_cinvul].value*5, TXT_MINUTES_ABBREV );
5760         last_cinvul = menus[opt_cinvul].value;
5761         menus[opt_cinvul].redraw = 1;
5762    }
5763   
5764   if (menus[opt_playtime].value!=LastPTA)
5765    {
5766     #ifdef SHAREWARE
5767       LastPTA=0;
5768       nm_messagebox ("Sorry",1,TXT_OK,"Registered version only!");
5769       menus[opt_playtime].value=0;
5770       menus[opt_playtime].redraw=1;
5771       return;
5772     #endif  
5773
5774     if (Game_mode & GM_MULTI_COOP)
5775      {
5776       LastPTA=0;
5777       nm_messagebox ("Sorry",1,TXT_OK,"You can't change those for coop!");
5778       menus[opt_playtime].value=0;
5779       menus[opt_playtime].redraw=1;
5780       return;
5781      }
5782
5783     Netgame.PlayTimeAllowed=menus[opt_playtime].value;
5784     sprintf( menus[opt_playtime].text, "Max Time: %d %s", Netgame.PlayTimeAllowed*5, TXT_MINUTES_ABBREV );
5785     LastPTA=Netgame.PlayTimeAllowed;
5786     menus[opt_playtime].redraw=1;
5787    }
5788   if (menus[opt_killgoal].value!=LastKillGoal)
5789    {
5790     #ifdef SHAREWARE
5791       nm_messagebox ("Sorry",1,TXT_OK,"Registered version only!");
5792       menus[opt_killgoal].value=0;
5793       menus[opt_killgoal].redraw=1;
5794       LastKillGoal=0;
5795       return;
5796          #endif         
5797
5798
5799     if (Game_mode & GM_MULTI_COOP)
5800      {
5801       nm_messagebox ("Sorry",1,TXT_OK,"You can't change those for coop!");
5802       menus[opt_killgoal].value=0;
5803       menus[opt_killgoal].redraw=1;
5804       LastKillGoal=0;
5805       return;
5806      }
5807
5808     
5809     Netgame.KillGoal=menus[opt_killgoal].value;
5810     sprintf( menus[opt_killgoal].text, "Kill Goal: %d kills", Netgame.KillGoal*5);
5811     LastKillGoal=Netgame.KillGoal;
5812     menus[opt_killgoal].redraw=1;
5813    }
5814  }
5815
5816 extern void multi_send_light (int,ubyte);
5817 extern void multi_send_light_specific (int,int,ubyte);
5818
5819 void network_send_smash_lights (int pnum) 
5820  {
5821   // send the lights that have been blown out
5822
5823   int i;
5824
5825   for (i=0;i<=Highest_segment_index;i++)
5826    if (Light_subtracted[i])
5827     multi_send_light_specific(pnum,i,Light_subtracted[i]);
5828  }
5829
5830 extern int Num_triggers;
5831 extern void multi_send_trigger_specific (char pnum,char);
5832
5833 void network_send_fly_thru_triggers (int pnum) 
5834  {
5835   // send the fly thru triggers that have been disabled
5836
5837   int i;
5838
5839   for (i=0;i<Num_triggers;i++)
5840    if (Triggers[i].flags & TF_DISABLED)
5841     multi_send_trigger_specific(pnum,i);
5842  }
5843
5844 void network_send_player_flags()
5845  {
5846   int i;
5847
5848   for (i=0;i<N_players;i++)
5849         multi_send_flags(i);
5850  }
5851
5852 void network_ping (ubyte flag,int pnum)
5853 {
5854         ubyte mybuf[2];
5855
5856         mybuf[0]=flag;
5857         mybuf[1]=Player_num;
5858
5859         if (Network_game_type == IPX_GAME)
5860                 ipx_send_packet_data( (ubyte *)mybuf, 2, NetPlayers.players[pnum].network.ipx.server, NetPlayers.players[pnum].network.ipx.node,Players[pnum].net_address );
5861         #ifdef MACINTOSH
5862         else
5863                 appletalk_send_packet_data( (ubyte *)mybuf, 2, NetPlayers.players[pnum].network.appletalk.node, NetPlayers.players[pnum].network.appletalk.net, NetPlayers.players[pnum].network.appletalk.socket);
5864         #endif
5865 }
5866
5867 extern fix PingLaunchTime,PingReturnTime;
5868
5869 void network_handle_ping_return (ubyte pnum)
5870  {
5871   if (PingLaunchTime==0 || pnum>=N_players)
5872         {
5873          mprintf ((0,"Got invalid PING RETURN from %s!\n",Players[pnum].callsign));
5874     return;
5875    }
5876   
5877   PingReturnTime=timer_get_fixed_seconds();
5878
5879   HUD_init_message ("Ping time for %s is %d ms!",Players[pnum].callsign,
5880         f2i(fixmul(PingReturnTime-PingLaunchTime,i2f(1000))));
5881   PingLaunchTime=0;
5882  }
5883         
5884 void network_send_ping (ubyte pnum)
5885  {
5886   network_ping (PID_PING_SEND,pnum);
5887  }  
5888
5889 void DoRefuseStuff (sequence_packet *their)
5890  {
5891   int i,new_player_num;
5892
5893   ClipRank (&their->player.rank);
5894         
5895   for (i=0;i<MAX_PLAYERS;i++)
5896          if (!strcmp (their->player.callsign,Players[i].callsign))
5897         {
5898                 network_welcome_player(their);
5899                         return;
5900                 }
5901   
5902    if (!WaitForRefuseAnswer)    
5903     {
5904         for (i=0;i<MAX_PLAYERS;i++)
5905                  if (!strcmp (their->player.callsign,Players[i].callsign))
5906                 {
5907                         network_welcome_player(their);
5908                                 return;
5909                         }
5910    
5911       digi_play_sample (SOUND_HUD_JOIN_REQUEST,F1_0*2);           
5912   
5913       if (Game_mode & GM_TEAM)
5914                  {
5915         
5916                                         
5917       if (!FindArg("-norankings"))
5918               HUD_init_message ("%s %s wants to join",RankStrings[their->player.rank],their->player.callsign);
5919         #ifndef MACINTOSH
5920                 HUD_init_message ("%s joining. Alt-1 assigns to team %s. Alt-2 to team %s",their->player.callsign,Netgame.team_name[0],Netgame.team_name[1]);
5921                 #else
5922                 HUD_init_message ("%s joining. Opt-1 assigns to team %s. Opt-2 to team %s",their->player.callsign,Netgame.team_name[0],Netgame.team_name[1]);
5923                 #endif
5924 //                      HUD_init_message ("Alt-1 to place on team %s!",Netgame.team_name[0]);
5925 //                      HUD_init_message ("Alt-2 to place on team %s!",Netgame.team_name[1]);
5926                  }               
5927                 else    
5928                 HUD_init_message ("%s wants to join...press F6 to connect",their->player.callsign);
5929
5930            strcpy (RefusePlayerName,their->player.callsign);
5931            RefuseTimeLimit=timer_get_approx_seconds();   
5932                 RefuseThisPlayer=0;
5933                 WaitForRefuseAnswer=1;
5934          }
5935         else
5936          {      
5937         for (i=0;i<MAX_PLAYERS;i++)
5938                  if (!strcmp (their->player.callsign,Players[i].callsign))
5939                 {
5940                         network_welcome_player(their);
5941                                 return;
5942                         }
5943       
5944                 if (strcmp(their->player.callsign,RefusePlayerName))
5945                         return;
5946
5947                 if (RefuseThisPlayer)
5948                  {
5949                                 RefuseTimeLimit=0;
5950                                 RefuseThisPlayer=0;
5951                                 WaitForRefuseAnswer=0;
5952                                 if (Game_mode & GM_TEAM)
5953                                  {
5954                                         new_player_num=GetNewPlayerNumber (their);
5955                                         mprintf ((0,"Newplayernum=%d\n",new_player_num));
5956                 
5957                                         Assert (RefuseTeam==1 || RefuseTeam==2);        
5958                                 
5959                                         if (RefuseTeam==1)      
5960                                         Netgame.team_vector &=(~(1<<new_player_num));
5961                                         else
5962                                         Netgame.team_vector |=(1<<new_player_num);
5963                                         network_welcome_player(their);
5964                                         network_send_netgame_update (); 
5965                                  }
5966                                 else
5967                                         network_welcome_player(their);
5968                            return;
5969                  }
5970                                         
5971           if ((timer_get_approx_seconds()) > RefuseTimeLimit+REFUSE_INTERVAL)
5972                 {
5973                         RefuseTimeLimit=0;
5974                         RefuseThisPlayer=0;
5975                         WaitForRefuseAnswer=0;
5976                         if (!strcmp (their->player.callsign,RefusePlayerName)) {
5977                                 if (Network_game_type == IPX_GAME)
5978                                         network_dump_player(their->player.network.ipx.server,their->player.network.ipx.node, DUMP_DORK);
5979                                 #ifdef MACINTOSH
5980                                 else
5981                                         network_dump_appletalk_player(their->player.network.appletalk.node,their->player.network.appletalk.net, their->player.network.appletalk.socket, DUMP_DORK);
5982                                 #endif
5983                         }
5984                         return;
5985                 }
5986                                                         
5987     }
5988  }
5989
5990 int GetNewPlayerNumber (sequence_packet *their)
5991   {
5992          int i;
5993         
5994                 if ( N_players < MaxNumNetPlayers)
5995                         return (N_players);
5996                 
5997                 else
5998                 {
5999                         // Slots are full but game is open, see if anyone is
6000                         // disconnected and replace the oldest player with this new one
6001                 
6002                         int oldest_player = -1;
6003                         fix oldest_time = timer_get_approx_seconds();
6004
6005                         Assert(N_players == MaxNumNetPlayers);
6006
6007                         for (i = 0; i < N_players; i++)
6008                         {
6009                                 if ( (!Players[i].connected) && (LastPacketTime[i] < oldest_time))
6010                                 {
6011                                         oldest_time = LastPacketTime[i];
6012                                         oldest_player = i;
6013                                 }
6014                         }
6015             return (oldest_player);
6016           }
6017   }
6018
6019 void network_send_extras ()
6020  {
6021         Assert (Player_joining_extras>-1);
6022
6023    if (!network_i_am_master())
6024          {
6025           mprintf ((0,"Hey! I'm not the master and I was gonna send info!\n"));
6026          // Int3();     
6027          // Network_sending_extras=0;
6028          // return;
6029     }
6030
6031
6032    if (Network_sending_extras==40)
6033                 network_send_fly_thru_triggers(Player_joining_extras);
6034    if (Network_sending_extras==38)
6035         network_send_door_updates(Player_joining_extras);
6036    if (Network_sending_extras==35)
6037                 network_send_markers();
6038    if (Network_sending_extras==30 && (Game_mode & GM_MULTI_ROBOTS))
6039                 multi_send_stolen_items();
6040         if (Network_sending_extras==25 && (Netgame.PlayTimeAllowed || Netgame.KillGoal))
6041                 multi_send_kill_goal_counts();
6042    if (Network_sending_extras==20)
6043                 network_send_smash_lights(Player_joining_extras);
6044    if (Network_sending_extras==15)
6045                 network_send_player_flags();    
6046    if (Network_sending_extras==10)
6047                 multi_send_powerup_update();  
6048  //  if (Network_sending_extras==5)
6049 //              network_send_door_updates(Player_joining_extras); // twice!
6050
6051         Network_sending_extras--;
6052    if (!Network_sending_extras)
6053          Player_joining_extras=-1;
6054  }
6055
6056
6057 void network_send_naked_packet(char *buf, short len, int who)
6058 {
6059         if (!(Game_mode&GM_NETWORK)) return;
6060
6061    if (NakedPacketLen==0)
6062          {
6063            NakedBuf[0]=PID_NAKED_PDATA;
6064            NakedBuf[1]=Player_num;
6065                 NakedPacketLen=2;
6066          }
6067
6068    if (len+NakedPacketLen>MaxXDataSize)
6069     {
6070 //         mprintf ((0,"Sending a naked packet of %d bytes.\n",NakedPacketLen));
6071                 if (Network_game_type == IPX_GAME)
6072                         ipx_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[who].network.ipx.server, NetPlayers.players[who].network.ipx.node,Players[who].net_address );
6073                 #ifdef MACINTOSH
6074                 else
6075                         appletalk_send_packet_data( (ubyte *)NakedBuf, NakedPacketLen, NetPlayers.players[who].network.appletalk.node, NetPlayers.players[who].network.appletalk.net, NetPlayers.players[who].network.appletalk.socket );
6076                 #endif
6077                 NakedPacketLen=2;
6078                 memcpy (&NakedBuf[NakedPacketLen],buf,len);     
6079                 NakedPacketLen+=len;
6080                 NakedPacketDestPlayer=who;
6081          }
6082    else
6083          {
6084                 memcpy (&NakedBuf[NakedPacketLen],buf,len);     
6085                 NakedPacketLen+=len;
6086                 NakedPacketDestPlayer=who;
6087          }
6088  }
6089
6090
6091 void network_process_naked_pdata (char *data,int len)
6092  {
6093    int pnum=data[1]; 
6094    Assert (data[0]=PID_NAKED_PDATA);
6095
6096 //   mprintf ((0,"Processing a naked packet of %d length.\n",len));
6097
6098         if (pnum < 0) {
6099            mprintf ((0,"Naked packet is bad!\n"));
6100                 Int3(); // This packet is bogus!!
6101                 return;
6102         }
6103
6104         if (!multi_quit_game && (pnum >= N_players)) {
6105                 if (Network_status!=NETSTAT_WAITING)
6106                  {
6107                         Int3(); // We missed an important packet!
6108                         network_consistency_error();
6109                         return;
6110                  }
6111                 else
6112                  return;
6113         }
6114
6115         if (Endlevel_sequence || (Network_status == NETSTAT_ENDLEVEL) ) {
6116                 int old_Endlevel_sequence = Endlevel_sequence;
6117                 Endlevel_sequence = 1;
6118                 multi_process_bigdata( data+2, len-2);
6119                 Endlevel_sequence = old_Endlevel_sequence;
6120                 return;
6121         }
6122
6123         multi_process_bigdata( data+2, len-2 );
6124  }
6125
6126 int ConnectionPacketLevel[]={0,1,1,1};
6127 int ConnectionSecLevel[]={12,3,5,7};
6128
6129 int AppletalkConnectionPacketLevel[]={0,1,0};
6130 int AppletalkConnectionSecLevel[]={10,3,8};
6131
6132 #if defined(RELEASE) && !defined(MACINTOSH)             // use the code below for mac appletalk games
6133 int network_choose_connect ()
6134  {
6135   return (1);
6136  }
6137 #else
6138 int network_choose_connect ()
6139  {
6140 #if 0
6141         newmenu_item m[16];
6142         int choice,opt=0;
6143 #endif
6144
6145         if (Network_game_type == IPX_GAME) {  
6146                 #if 0
6147            m[opt].type = NM_TYPE_MENU;  m[opt].text = "Local Subnet"; opt++;
6148            m[opt].type = NM_TYPE_MENU;  m[opt].text = "14.4 modem over Internet"; opt++;
6149            m[opt].type = NM_TYPE_MENU;  m[opt].text = "28.8 modem over Internet"; opt++;
6150            m[opt].type = NM_TYPE_MENU;  m[opt].text = "ISDN or T1 over Internet"; opt++;
6151
6152            choice = newmenu_do1( NULL, "Choose connection type", opt, m, NULL, 0 );
6153
6154                 if (choice<0)
6155                  return (NULL);
6156
6157            Assert (choice>=0 && choice<=3);
6158    
6159                 Netgame.ShortPackets=ConnectionPacketLevel[choice];
6160                 Netgame.PacketsPerSec=ConnectionSecLevel[choice];
6161                 #endif
6162            return (1);
6163         #ifdef MACINTOSH
6164         } else {
6165            m[opt].type = NM_TYPE_MENU;  m[opt].text = "EtherTalk"; opt++;
6166            m[opt].type = NM_TYPE_MENU;  m[opt].text = "LocalTalk"; opt++;
6167            m[opt].type = NM_TYPE_MENU;  m[opt].text = "Other"; opt++;
6168         
6169            choice = newmenu_do1( NULL, "Choose connection type", opt, m, NULL, 0 );
6170
6171                 if (choice<0)
6172                  return (NULL);
6173
6174                 Network_appletalk_type = choice;
6175                 
6176                 Assert (choice>=0 && choice<=2);
6177    
6178                 Netgame.ShortPackets=AppletalkConnectionPacketLevel[choice];
6179                 Netgame.PacketsPerSec=AppletalkConnectionSecLevel[choice];
6180            return (1);
6181         #endif
6182         }
6183   return (0);   
6184  }
6185 #endif
6186
6187
6188
6189 #ifdef NETPROFILING
6190 void OpenSendLog ()
6191  {
6192   int i;
6193   SendLogFile=(FILE *)fopen ("sendlog.net","w");
6194   for (i=0;i<100;i++)
6195         TTSent[i]=0;
6196  }
6197 void OpenRecieveLog ()
6198  {
6199   int i;
6200   RecieveLogFile=(FILE *)fopen ("recvlog.net","w");
6201   for (i=0;i<100;i++)
6202         TTRecv[i]=0;
6203  }
6204 #endif
6205
6206 int GetMyNetRanking ()
6207  {
6208   int rank;
6209   int eff;
6210
6211   if (Netlife_kills+Netlife_killed==0)
6212          return (1);
6213  
6214   rank=(int) (((float)Netlife_kills/3000.0)*8.0);
6215  
6216   eff=(int)((float)((float)Netlife_kills/((float)Netlife_killed+(float)Netlife_kills))*100.0);
6217
6218   if (rank>8)
6219    rank=8;
6220   
6221   if (eff<0)
6222          eff=0;
6223  
6224   if (eff<60)
6225         rank-=((59-eff)/10);
6226         
6227   if (rank<0)
6228         rank=0;
6229   if (rank>8)
6230         rank=8;
6231  
6232   mprintf ((0,"Rank is %d (%s)\n",rank+1,RankStrings[rank+1]));
6233   return (rank+1);
6234  }
6235
6236 void ClipRank (ubyte *rank)
6237  {
6238   // This function insures no crashes when dealing with D2 1.0
6239
6240  
6241   if (*rank > 9)
6242         *rank = 0;
6243  }
6244 void network_check_for_old_version (char pnum)
6245  {  
6246   if (NetPlayers.players[(int)pnum].version_major==1 && (NetPlayers.players[(int)pnum].version_minor & 0x0F)==0)
6247         NetPlayers.players[(int)pnum].rank=0;
6248  }
6249
6250 void network_request_player_names (int n)
6251  {
6252   network_send_all_info_request (PID_GAME_PLAYERS,Active_games[n].Security);
6253   NamesInfoSecurity=Active_games[n].Security;
6254  }
6255
6256 extern char already_showing_info;
6257 extern int newmenu_dotiny2( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem));
6258
6259 void network_process_names_return (ubyte *data)
6260  {
6261         newmenu_item m[15];
6262    char mtext[15][50],temp[50];
6263         int i,t,l,gnum,num=0,count=5,numplayers;
6264    
6265    if (NamesInfoSecurity!=(*(int *)(data+1)))
6266          {
6267           mprintf ((0,"Bad security on names return!\n"));
6268           mprintf ((0,"NIS=%d data=%d\n",NamesInfoSecurity,(*(int *)(data+1))));
6269           return;
6270          }
6271
6272    numplayers=data[count]; count++;
6273
6274    if (numplayers==255)
6275          {
6276                  SurfingNet=0;  
6277                  NamesInfoSecurity=-1;
6278                  nm_messagebox(NULL, 1, "OK", "That game is refusing\nname requests.\n");
6279                  SurfingNet=1;
6280                  return;
6281          }
6282
6283    Assert (numplayers>0 && numplayers<MAX_NUM_NET_PLAYERS);
6284         
6285    for (i=0;i<12;i++)
6286         {
6287          m[i].text=(char *)&mtext[i];
6288     m[i].type=NM_TYPE_TEXT;             
6289         }
6290
6291    for (gnum=-1,i=0;i<num_active_games;i++)
6292          {
6293           if (NamesInfoSecurity==Active_games[i].Security)
6294                 {
6295                  gnum=i;
6296                  break;
6297                 }
6298          }
6299         
6300         if (gnum==-1)
6301     {
6302        SurfingNet=0;
6303                  NamesInfoSecurity=-1;
6304                  nm_messagebox(NULL, 1, "OK", "The game you have requested\nnames from is gone.\n");
6305                  SurfingNet=1;
6306                  return;
6307          }
6308  
6309    sprintf (mtext[num],"Players of game '%s':",Active_games[gnum].game_name); num++;
6310    for (i=0;i<numplayers;i++)
6311          {
6312           l=data[count++];
6313
6314      mprintf ((0,"%s\n",data+count));
6315
6316           for (t=0;t<CALLSIGN_LEN+1;t++)
6317                  temp[t]=data[count++];   
6318      if (FindArg("-norankings"))        
6319              sprintf (mtext[num],"%s",temp);
6320           else
6321              sprintf (mtext[num],"%s%s",RankStrings[l],temp);
6322         
6323           num++;        
6324          }
6325
6326         if (data[count]==99)
6327         {
6328          sprintf (mtext[num++]," ");
6329          sprintf (mtext[num++],"Short packets: %s",data[count+1]?"On":"Off");
6330          sprintf (mtext[num++],"Packets Per Second: %d",data[count+2]);
6331    }
6332
6333         already_showing_info=1; 
6334         newmenu_dotiny2( NULL, NULL, num, m, NULL);
6335         already_showing_info=0; 
6336  }
6337
6338 char NameReturning=1;
6339
6340 void network_send_player_names (sequence_packet *their)
6341  {
6342   int numconnected=0,count=0,i,t;
6343   char buf[80];
6344
6345   if (!their)
6346    {
6347     mprintf ((0,"Got a player name without a return address! Get Jason\n"));
6348          return;
6349         }
6350
6351    buf[0]=PID_NAMES_RETURN; count++;
6352    (*(int *)(buf+1))=Netgame.Security; count+=4;
6353
6354    if (!NameReturning)
6355          {
6356      buf[count]=255; count++; 
6357           goto sendit;
6358          }
6359  
6360    mprintf ((0,"RealSec=%d DS=%d\n",Netgame.Security,*(int *)(buf+1)));
6361   
6362    for (i=0;i<N_players;i++)
6363          if (Players[i].connected)
6364                 numconnected++;
6365
6366    buf[count]=numconnected; count++; 
6367    for (i=0;i<N_players;i++)
6368          if (Players[i].connected)
6369           {
6370                 buf[count++]=NetPlayers.players[i].rank; 
6371                 
6372                 for (t=0;t<CALLSIGN_LEN+1;t++)
6373                  {
6374                   buf[count]=NetPlayers.players[i].callsign[t];
6375                   count++;
6376                  }
6377           }
6378
6379    buf[count++]=99;
6380         buf[count++]=Netgame.ShortPackets;              
6381         buf[count++]=Netgame.PacketsPerSec;
6382   
6383    sendit:
6384                                 ;               // empty statement allows compilation on mac which does not have the
6385                                                 // statement below and kills the compiler when there is no
6386                                                 // statement following the label "sendit"
6387            
6388    #ifndef MACINTOSH
6389            ipx_send_internetwork_packet_data((ubyte *)buf, count, their->player.network.ipx.server, their->player.network.ipx.node);
6390         #endif
6391  }
6392
6393
6394 int HoardEquipped()
6395 {
6396         static int checked=-1;
6397
6398 #ifdef WINDOWS
6399         return 0;
6400 #endif
6401
6402         if (checked==-1)
6403         {
6404                 if (cfexist("hoard.ham"))
6405                         checked=1;
6406                 else
6407                         checked=0;
6408         }
6409         return (checked);
6410 }