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