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