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