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