summaryrefslogtreecommitdiff
path: root/src/uqm/supermelee/netplay/netmelee.c
blob: e9368fdfd53b76cb76888f4abf01d9fb41b8ef13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
/*
 *  Copyright 2006  Serge van den Boom <svdb@stack.nl>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#define PORT_WANT_ERRNO
#include "port.h"
#include "netmelee.h"
#include "libs/async.h"
#include "libs/callback.h"
#include "libs/log.h"
#include "libs/net.h"
#include "netinput.h"
#include "netmisc.h"
#include "netsend.h"
#include "notify.h"
#include "packetq.h"
#include "proto/npconfirm.h"
#include "proto/ready.h"
#include "proto/reset.h"

#include "../../battlecontrols.h"
		// for NetworkInputContext
#include "../../controls.h"
		// for BATTLE_INPUT_STATE
#include "../../init.h"
		// for NUM_PLAYERS
#include "../../globdata.h"
		// for GLOBAL

#include <errno.h>
#include <stdlib.h>


////////////////////////////////////////////////////////////////////////////


NetConnection *netConnections[NUM_PLAYERS];
size_t numNetConnections;

void
addNetConnection(NetConnection *conn, int playerNr) {
	netConnections[playerNr] = conn;
	numNetConnections++;
}

void
removeNetConnection(int playerNr) {
	netConnections[playerNr] = NULL;
	numNetConnections--;
}

size_t
getNumNetConnections(void) {
	return numNetConnections;
}

// If the callback function returns 'false', the function will immediately
// return with 'false'. Otherwise it will return 'true' after calling
// the callback function for each connected player.
bool
forEachConnectedPlayer(ForEachConnectionCallback callback, void *arg) {
	COUNT player;
	
	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		if (!(*callback)(conn, arg))
			return false;
	}
	return true;
}

void
closeAllConnections(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];

		if (conn != NULL)
			closePlayerNetworkConnection(player);
	}
}

void
closeDisconnectedConnections(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];

		if (conn != NULL && !NetConnection_isConnected(conn))
			closePlayerNetworkConnection(player);
	}
}

////////////////////////////////////////////////////////////////////////////


struct melee_state *
NetMelee_getMeleeState(NetConnection *conn) {
	if (NetConnection_getState(conn) > NetState_connecting) {
		BattleStateData *battleStateData =
				(BattleStateData *) NetConnection_getStateData(conn);
		return battleStateData->meleeState;
	} else {
		return (struct melee_state *) NetConnection_getExtra(conn);
	}
}

struct battlestate_struct *
NetMelee_getBattleState(NetConnection *conn) {
	if (NetConnection_getState(conn) > NetState_connecting) {
		BattleStateData *battleStateData =
				(BattleStateData *) NetConnection_getStateData(conn);
		return battleStateData->battleState;
	} else {
		return NULL;
	}
}

////////////////////////////////////////////////////////////////////////////

static inline void
netInputAux(uint32 timeoutMs) {
	NetManager_process(&timeoutMs);
			// This may cause more packets to be queued, hence the
			// flushPacketQueues().
	Async_process();
	flushPacketQueues();
			// During the flush, a disconnect may be noticed, which triggers
			// another callback. It must be handled immediately, before
			// another flushPacketQueue() can occur, which would not know
			// that the socket is no longer valid.
			// TODO: modify the close handling so this order isn't
			//       necessary.
	Callback_process();
}

// Check the network connections for input.
void
netInput(void) {
	netInputAux(0);
}

void
netInputBlocking(uint32 timeoutMs) {
	uint32 nextAsyncMs;
		
	nextAsyncMs = Async_timeBeforeNextMs();
	if (nextAsyncMs < timeoutMs)
		timeoutMs = nextAsyncMs;

	netInputAux(timeoutMs);
}


////////////////////////////////////////////////////////////////////////////


// Send along all pending network packets.
void
flushPacketQueues(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn;
		int flushStatus;

		conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		flushStatus = flushPacketQueue(conn);
		if (flushStatus == -1 && errno != EAGAIN && errno != EWOULDBLOCK)
			closePlayerNetworkConnection(player);
	}
}

void
confirmConnections(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		Netplay_confirm(conn);
	}
}

void
cancelConfirmations(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		Netplay_cancelConfirmation(conn);
	}
}

void
connectionsLocalReady(NetConnection_ReadyCallback callback, void *arg) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		Netplay_localReady(conn, callback, arg, true);
	}
}

bool
allConnected(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			return false;
	}
	return true;
}

void
initBattleStateDataConnections(void) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		BattleStateData *battleStateData;
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		battleStateData =
				(BattleStateData *) NetConnection_getStateData(conn);
		battleStateData->endFrameCount = 0;
	}
}

void
setBattleStateConnections(struct battlestate_struct *bs) {
	COUNT player;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		BattleStateData *battleStateData;
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		battleStateData =
				(BattleStateData *) NetConnection_getStateData(conn);
		battleStateData->battleState = bs;
	}
}

BATTLE_INPUT_STATE
networkBattleInput(NetworkInputContext *context, STARSHIP *StarShipPtr) {
	BattleInputBuffer *bib = getBattleInputBuffer(context->playerNr);
	BATTLE_INPUT_STATE result;
	
	for (;;) {
		bool ok;
		
#if 0
		// This is a useful debugging trick. By enabling this #if
		// block, this side will always lag the maximum number of frames
		// behind the other side. When the remote side stops on some event
		// (a breakpoint or so), this side will stop too, waiting for input
		// in the loop below, but it won't have processed the frame that
		// triggered the event yet. If you then jump over this 'if'
		// statement here, you can walk through the decisive frames
		// manually. Works best with no input delay.
		if (bib->size <= getBattleInputDelay() + 1) {
			ok = false;
		} else
#endif
			ok = BattleInputBuffer_pop(bib, &result);
					// Get the input from the front of the
					// buffer.
		if (ok)
			break;
			
		{
			NetConnection *conn = netConnections[context->playerNr];

			// First try whether there is incoming data, without blocking.
			// If there isn't any, only then give a warning, and then
			// block after all.
			netInput();
			if (!NetConnection_isConnected(conn))
			{
				// Connection aborted.
				GLOBAL(CurrentActivity) |= CHECK_ABORT;
				return (BATTLE_INPUT_STATE) 0;
			}
		
			if (GLOBAL(CurrentActivity) & CHECK_ABORT)
				return (BATTLE_INPUT_STATE) 0;

#if 0
			log_add(log_Warning, "NETPLAY: [%d] stalling for "
					"network input. Increase the input delay if this "
					"happens a lot.\n", context->playerNr);
#endif
#define MAX_BLOCK_TIME 500
			netInputBlocking(MAX_BLOCK_TIME);
			if (!NetConnection_isConnected(conn))
			{
				// Connection aborted.
				GLOBAL(CurrentActivity) |= CHECK_ABORT;
				return (BATTLE_INPUT_STATE) 0;
			}
		}
	}

	(void) StarShipPtr;
	return result;
}

static void
deleteConnectionCallback(NetConnection *conn) {
	removeNetConnection(NetConnection_getPlayerNr(conn));
}

NetConnection *
openPlayerNetworkConnection(COUNT player, void *extra) {
	NetConnection *conn;

	assert(netConnections[player] == NULL);

	conn = NetConnection_open(player,
			&netplayOptions.peer[player], NetMelee_connectCallback,
			NetMelee_closeCallback, NetMelee_errorCallback,
			deleteConnectionCallback, extra);

	addNetConnection(conn, player);
	return conn;
}

void
closePlayerNetworkConnection(COUNT player) {
	assert(netConnections[player] != NULL);

	NetConnection_close(netConnections[player]);
}

bool
setupInputDelay(size_t localInputDelay) {
	COUNT player;
	bool haveNetworkPlayer = false;
			// We have at least one network controlled player.
	size_t inputDelay = 0;
	
	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn))
			continue;

		haveNetworkPlayer = true;
		if (NetConnection_getInputDelay(conn) > inputDelay)
			inputDelay = NetConnection_getInputDelay(conn);
	}

	if (haveNetworkPlayer && inputDelay < localInputDelay)
		inputDelay = localInputDelay;

	setBattleInputDelay(inputDelay);
	return true;
}

static bool
setStateConnection(NetConnection *conn, void *arg) {
	const NetState *state = (NetState *) arg;
	NetConnection_setState(conn, *state);
	return true;
}

bool
setStateConnections(NetState state) {
	return forEachConnectedPlayer(setStateConnection, &state);
}

static bool
sendAbortConnection(NetConnection *conn, void *arg) {
	const NetplayAbortReason *reason = (NetplayAbortReason *) arg;
	sendAbort(conn, *reason);
	return true;
}

bool
sendAbortConnections(NetplayAbortReason reason) {
	return forEachConnectedPlayer(sendAbortConnection, &reason);
}

static bool
resetConnection(NetConnection *conn, void *arg) {
	const NetplayResetReason *reason = (NetplayResetReason *) arg;
	Netplay_localReset(conn, *reason);
	return true;
}

bool
resetConnections(NetplayResetReason reason) {
	return forEachConnectedPlayer(resetConnection, &reason);
}

/////////////////////////////////////////////////////////////////////////////

typedef struct {
	NetConnection_ReadyCallback readyCallback;
	void *readyCallbackArg;
	bool notifyRemote;
} LocalReadyConnectionArg;

static bool
localReadyConnection(NetConnection *conn, void *arg) {
	LocalReadyConnectionArg *readyArg = (LocalReadyConnectionArg *) arg;
	Netplay_localReady(conn, readyArg->readyCallback,
			readyArg->readyCallbackArg, readyArg->notifyRemote);
	return true;
}

bool
localReadyConnections(NetConnection_ReadyCallback readyCallback,
		void *readyArg, bool notifyRemote) {
	LocalReadyConnectionArg arg;
	arg.readyCallback = readyCallback;
	arg.readyCallbackArg = readyArg;
	arg.notifyRemote = notifyRemote;

	return forEachConnectedPlayer(localReadyConnection, &arg);
}


/////////////////////////////////////////////////////////////////////////////

#define NETWORK_POLL_DELAY (ONE_SECOND / 24)

typedef struct NegotiateReadyState NegotiateReadyState;
struct NegotiateReadyState {
	// Common fields of INPUT_STATE_DESC, from which this structure
	// "inherits".
	BOOLEAN(*InputFunc)(void *pInputState);

	NetConnection *conn;
	NetState nextState;
	bool done;
};

static BOOLEAN
negotiateReadyInputFunc(NegotiateReadyState *state) {
	netInputBlocking(NETWORK_POLL_DELAY);
	// The timing out is necessary so that immediate key presses get
	// handled while we wait. If we could do without the timeout,
	// we wouldn't even need negotiateReadyInputFunc() and the
	// DoInput() call.
	
	// No need to call flushPacketQueues(); nothing needs to be sent
	// right now.

	if (!NetConnection_isConnected(state->conn))
		return FALSE;

	return !state->done;
}

// Called when both sides are ready
static void
negotiateReadyBothReadyCallback(NetConnection *conn, void *arg) {
	NegotiateReadyState *state =(NegotiateReadyState *) arg;

	NetConnection_setState(conn, state->nextState);
			// This has to be done immediately, as more packets in the
			// receive queue may be handled by the netInput() call that
			// triggered this callback.
			// This is the reason for the nextState argument to
			// negotiateReady(); setting the state after the call to
			// negotiateReady() would be too late.
	state->done = true;
}

bool
negotiateReady(NetConnection *conn, bool notifyRemote, NetState nextState) {
	NegotiateReadyState state;
	state.InputFunc = (BOOLEAN(*)(void *)) negotiateReadyInputFunc;
	state.conn = conn;
	state.nextState = nextState;
	state.done = false;

	Netplay_localReady(conn, negotiateReadyBothReadyCallback,
			(void *) &state, notifyRemote);
	flushPacketQueue(conn);
	if (!state.done)
		DoInput(&state, FALSE);

	return NetConnection_isConnected(conn);
}

// Wait for all connections to get ready.
// XXX: Right now all connections are handled one by one. Handling them all
//      at once would be faster but would require more work, which is
//      not worth it as the time is minimal and this function is not
//      time critical.
bool
negotiateReadyConnections(bool notifyRemote, NetState nextState) {
	COUNT player;
	size_t numDisconnected = 0;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn)) {
			numDisconnected++;
			continue;
		}

		negotiateReady(conn, notifyRemote, nextState);
	}

	return numDisconnected == 0;
}

typedef struct WaitReadyState WaitReadyState;
struct WaitReadyState {
	// Common fields of INPUT_STATE_DESC, from which this structure
	// "inherits".
	BOOLEAN (*InputFunc)(void *pInputState);

	NetConnection *conn;
	NetConnection_ReadyCallback readyCallback;
	void *readyCallbackArg;
	bool done;
};

static void
waitReadyCallback(NetConnection *conn, void *arg) {
	WaitReadyState *state =(WaitReadyState *) arg;
	state->done = true;

	// Call the original callback.
	state->readyCallback(conn, state->readyCallbackArg);
}

static BOOLEAN
waitReadyInputFunc(WaitReadyState *state) {
	netInputBlocking(NETWORK_POLL_DELAY);
	// The timing out is necessary so that immediate key presses get
	// handled while we wait. If we could do without the timeout,
	// we wouldn't even need negotiateReadyInputFunc() and the
	// DoInput() call.
	
	// No need to call flushPacketQueues(); nothing needs to be sent
	// right now.

	if (!NetConnection_isConnected(state->conn))
		return FALSE;

	return !state->done;
}

bool
waitReady(NetConnection *conn) {
	WaitReadyState state;
	state.InputFunc =(BOOLEAN(*)(void *)) waitReadyInputFunc;
	state.conn = conn;
	state.readyCallback = NetConnection_getReadyCallback(conn);
	state.readyCallbackArg = NetConnection_getReadyCallbackArg(conn);
	state.done = false;

	NetConnection_setReadyCallback(conn, waitReadyCallback, (void *) &state);

	DoInput(&state, FALSE);

	return NetConnection_isConnected(conn);
}


////////////////////////////////////////////////////////////////////////////

typedef struct WaitResetState WaitResetState;
struct WaitResetState {
	// Common fields of INPUT_STATE_DESC, from which this structure
	// "inherits".
	BOOLEAN(*InputFunc)(void *pInputState);

	NetConnection *conn;
	NetState nextState;
	bool done;
};

static BOOLEAN
waitResetInputFunc(WaitResetState *state) {
	netInputBlocking(NETWORK_POLL_DELAY);
	// The timing out is necessary so that immediate key presses get
	// handled while we wait. If we could do without the timeout,
	// we wouldn't even need waitResetInputFunc() and the
	// DoInput() call.
	
	// No need to call flushPacketQueues(); nothing needs to be sent
	// right now.

	if (!NetConnection_isConnected(state->conn))
		return FALSE;

	return !state->done;
}

// Called when both sides are reset.
static void
waitResetBothResetCallback(NetConnection *conn, void *arg) {
	WaitResetState *state = (WaitResetState *) arg;

	if (state->nextState != (NetState) -1) {
		NetConnection_setState(conn, state->nextState);
		// This has to be done immediately, as more packets in the
		// receive queue may be handled by the netInput() call that
		// triggered this callback.
		// This is the reason for the nextState argument to
		// waitReset(); setting the state after the call to
		// waitReset() would be too late.
	}
	state->done = true;
}

bool
waitReset(NetConnection *conn, NetState nextState) {
	WaitResetState state;
	state.InputFunc = (BOOLEAN(*)(void *)) waitResetInputFunc;
	state.conn = conn;
	state.nextState = nextState;
	state.done = false;

	Netplay_setResetCallback(conn, waitResetBothResetCallback,
			(void *) &state);
	if (state.done)
		goto out;
		

	if (!Netplay_isLocalReset(conn)) {
		Netplay_localReset(conn, ResetReason_manualReset);
		flushPacketQueue(conn);
	}

	if (!state.done)
		DoInput(&state, FALSE);

out:
	return NetConnection_isConnected(conn);
}

// Wait until we have received a reset packet from all connections. If we
// ourselves have not sent a reset packet, one is sent, with reason
// 'manualReset'.
// XXX: Right now all connections are handled one by one. Handling them all
//      at once would be faster but would require more work, which is
//      not worth it as the time is minimal and this function is not
//      time critical.
// Use '(NetState) -1' for nextState to keep the current state.
bool
waitResetConnections(NetState nextState) {
	COUNT player;
	size_t numDisconnected = 0;

	for (player = 0; player < NUM_PLAYERS; player++)
	{
		NetConnection *conn = netConnections[player];
		if (conn == NULL)
			continue;

		if (!NetConnection_isConnected(conn)) {
			numDisconnected++;
			continue;
		}

		waitReset(conn, nextState);
	}

	return numDisconnected == 0;
}

////////////////////////////////////////////////////////////////////////////