summaryrefslogtreecommitdiff
path: root/lib/physics.c
blob: adcf4338cb51e6129c9cad2d35402112e37a6476 (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
#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "common.h"
#include "player.h"
#include "snapshot.h"
#include "types.h"

#include "physics.h"

struct context *
dp_physics_context_create(size_t snapshots)
{
	struct context *ctx = NULL;

	if (!(ctx = malloc(sizeof(*ctx))))
		return NULL;
	memset(ctx, 0, sizeof(*ctx));

	ctx->snapshots_len = snapshots;
	if (!(ctx->snapshots = malloc(sizeof(*ctx->snapshots) * snapshots)))
	{
		free(ctx);
		return NULL;
	}
	memset(ctx->snapshots, 0, sizeof(*ctx->snapshots) * snapshots);

	return ctx;
}

void
dp_physics_context_free(struct context *ctx)
{
	if (!ctx)
		return;
	if (ctx->snapshots)
		free(ctx->snapshots);
	free(ctx);
}

struct snapshot *dp_physics_context_get_snapshot(struct context *ctx)
{
	size_t i;
	struct snapshot *s;

	for (i = 0; i < ctx->snapshots_len; i++)
	{
		s = &ctx->snapshots[i];
		if (!s->active)
		{
			s->active = true;
			return s;
		}
	}
	return NULL;
}

void dp_physics_context_return_snapshot(struct context *ctx, struct snapshot *s)
{
	size_t i;

	assert(s->active);

	for (i = 0; i < ctx->snapshots_len; i++)
	{
		if (s == &ctx->snapshots[i])
		{
			s->active = false;
		}
	}

	assert(!s->active);
}

static void
dp_physics_tick_player(const struct player *cur, double delta, struct player *next)
{
	vec2 acc;

	next->state = cur->state;
	if (next->state == STATE_REMOVED)
		next->state = STATE_INACTIVE;
	if (next->state == STATE_INACTIVE)
		return;

	acc = dp_player_calculate_acceleration(cur);
	next->vel = dp_vec2_add(cur->vel, dp_vec2_mul(acc, delta));
	next->pos = dp_vec2_add(cur->pos, dp_vec2_mul(next->vel, delta));
}

static void
dp_physics_tick_ball(const struct ball *cur, double delta, struct ball *next)
{
	next->state = cur->state;
	if (next->state == STATE_REMOVED)
		next->state = STATE_INACTIVE;
	if (next->state == STATE_INACTIVE)
		return;

	next->pos = dp_vec2_add(cur->pos, dp_vec2_mul(cur->vel, delta));
}

int
dp_physics_tick(const struct snapshot *cur, double delta, struct snapshot *next)
{
	size_t i;

	assert(cur->active);
	assert(next->active);

	for (i = 0; i < LENGTH(cur->players); i++)
	{
		dp_physics_tick_player(&cur->players[i], delta, &next->players[i]);
	}

	for (i = 0; i < LENGTH(cur->balls); i++)
	{
		dp_physics_tick_ball(&cur->balls[i], delta, &next->balls[i]);
	}

	next->tick = cur->tick + 1;
	return 0;
}