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