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