aboutsummaryrefslogtreecommitdiff
path: root/muswd.c
blob: 249e516836b330a6f050563a791dfbcdb4492e55 (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
#include <u.h>
#include <libc.h>
#include <thread.h>
#include "dat.h"
#include "fns.h"

int debug;

GameState state;
double t, Δt;

Lobby *lobby;


static long
_iolisten(va_list *arg)
{
	char *adir, *ldir;

	adir = va_arg(*arg, char*);
	ldir = va_arg(*arg, char*);

	return listen(adir, ldir);
}

long
iolisten(Ioproc *io, char *adir, char *ldir)
{
	return iocall(io, _iolisten, adir, ldir);
}

void
threadlisten(void *arg)
{
	int lcfd, dfd;
	char *adir, ldir[40];
	Ioproc *io;

	adir = arg;
	io = ioproc();

	for(;;){
		lcfd = iolisten(io, adir, ldir);
		if(lcfd < 0){
			fprint(2, "iolisten: %r\n");
			continue;
		}
		/*
		 * handle connection and allocate user on a seat, ready
		 * to play
		 */
		dfd = accept(lcfd, ldir);
		if(dfd < 0){
			fprint(2, "accept: %r\n");
			continue;
		}

		lobby->takeseat(lobby, dfd);

		if(debug)
			fprint(2, "added conn for %lud conns at %lud max\n",
				lobby->seats.len, lobby->seats.cap);
	}
}

void
resetsim(void)
{
	t = 0;
	memset(&state, 0, sizeof state);
	state.x = 100;
}

void
threadsim(void *)
{
	int i;
	uvlong then, now;
	double frametime, timeacc;
	Ioproc *io;

	Δt = 0.01;
	then = nanosec();
	timeacc = 0;
	io = ioproc();

	resetsim();

	for(;;){
		now = nanosec();
		frametime = now - then;
		then = now;
		timeacc += frametime/1e9;

		for(i = 0; i < lobby->seats.len; i++)
			if(fprint(lobby->seats.fds[i], "state: x=%g v=%g\n", state.x, state.v) < 0){
				if(debug)
					fprint(2, "client #%d hanged up\n", i+1);

				lobby->leaveseat(lobby, i);

				if(debug)
					fprint(2, "removed conn %d for %lud conns at %lud max\n",
						i, lobby->seats.len, lobby->seats.cap);

				i--;
			}

		while(timeacc >= Δt){
			integrate(&state, t, Δt);
			timeacc -= Δt;
			t += Δt;
		}

		iosleep(io, FPS2MS(1));
	}
}

void
usage(void)
{
	fprint(2, "usage: %s [-d]\n", argv0);
	threadexitsall("usage");
}

void
threadmain(int argc, char *argv[])
{
	int acfd;
	char adir[40];

	ARGBEGIN{
	case 'd':
		debug++;
		break;
	default:
		usage();
	}ARGEND;
	if(argc != 0)
		usage();

	acfd = announce("tcp!*!112", adir);
	if(acfd < 0)
		sysfatal("announce: %r");

	lobby = newlobby();

	threadcreate(threadlisten, adir, 4096);
	threadcreate(threadsim, nil, 4096);
	threadexits(nil);
}