/
hub.go
277 lines (237 loc) · 6.98 KB
/
hub.go
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
// SPDX-FileCopyrightText: 2021 Softbear, Inc.
// SPDX-License-Identifier: AGPL-3.0-or-later
package server
import (
"fmt"
"github.com/SoftbearStudios/mk48/server/terrain"
"github.com/SoftbearStudios/mk48/server/terrain/noise"
"github.com/SoftbearStudios/mk48/server/world"
"github.com/SoftbearStudios/mk48/server/world/sector"
"sync"
"sync/atomic"
"time"
)
const (
botPeriod = time.Second / 4
debugPeriod = time.Second * 5
leaderboardPeriod = time.Second
spawnPeriod = leaderboardPeriod
updatePeriod = world.TickPeriod
// Must spawn at least this many bots per real player,
// to give low-level ships some easier targets
minBotRatio = 0.5
// encodeBotMessages makes BotClient.Send marshal json and check for errors.
// Only useful for testing/benchmarking (drops performance significantly).
encodeBotMessages = false
)
// Hub maintains the set of active clients and broadcasts messages to the clients.
type (
HubOptions struct {
Cloud Cloud
MinClients int
MaxBotSpawnLevel uint8
Auth string
}
Hub struct {
// World state
world *sector.World
worldRadius float32 // interpolated
terrain *terrain.Terrain
clients ClientList // implemented as double-linked list
despawn ClientList // clients that are being removed
teams map[world.TeamID]*Team
// IP address info (must hold ipMu)
ipConns map[string]int // key is stringified IP (IP, being a slice, is not a valid map key type)
ipMu sync.RWMutex
// Flags
minPlayers int
botMaxSpawnLevel uint8
auth string
// Cloud (and things that are served atomically by HTTP)
cloud Cloud
statusJSON atomic.Value
// chats are buffered until next update.
chats []Chat
// funcBenches are benchmarks of core Hub functions.
funcBenches []funcBench
// Inbound channels
inbound chan SignedInbound
register chan Client
unregister chan Client
// Timer based events
cloudTicker *time.Ticker
updateTicker *time.Ticker
skippedCounter int
updateCounter int
leaderboardTicker *time.Ticker
debugTicker *time.Ticker
botsTicker *time.Ticker
}
)
// c can be nil
func NewHub(options HubOptions) *Hub {
if options.MaxBotSpawnLevel > world.BoatLevelMax {
options.MaxBotSpawnLevel = world.BoatLevelMax
}
radius := max(world.MinRadius, world.RadiusOf(options.MinClients))
return &Hub{
cloud: options.Cloud,
world: sector.New(radius),
terrain: terrain.New(noise.NewDefault()),
worldRadius: radius,
teams: make(map[world.TeamID]*Team),
ipConns: make(map[string]int),
minPlayers: options.MinClients,
botMaxSpawnLevel: options.MaxBotSpawnLevel,
auth: options.Auth,
inbound: make(chan SignedInbound, 16+options.MinClients*2),
register: make(chan Client, 8+options.MinClients/256),
unregister: make(chan Client, 16+options.MinClients/128),
cloudTicker: time.NewTicker(options.Cloud.UpdatePeriod()),
updateTicker: time.NewTicker(updatePeriod),
leaderboardTicker: time.NewTicker(leaderboardPeriod),
debugTicker: time.NewTicker(debugPeriod),
botsTicker: time.NewTicker(botPeriod),
}
}
func (h *Hub) Register(client Client) {
select {
case h.register <- client:
default:
go func() {
h.register <- client
}()
}
}
func (h *Hub) GetTerrain() *terrain.Terrain {
return h.terrain
}
func (h *Hub) Unregister(client Client) {
select {
case h.unregister <- client:
default:
go func() {
h.unregister <- client
}()
}
}
// May not use important=true when called on hub goroutine
func (h *Hub) ReceiveSigned(in SignedInbound, important bool) {
select {
case h.inbound <- in:
default:
if important {
go func() {
h.inbound <- in
}()
}
// Otherwise, drop messages to avoid downfall of server.
}
}
func (h *Hub) Run() {
defer DebugExit()
h.Cloud()
for {
select {
case client := <-h.register:
h.clients.Add(client)
client.Data().Hub = h
client.Init()
if !client.Bot() {
h.cloud.IncrementPlayerStatistic()
}
case client := <-h.unregister:
client.Close()
player := &client.Data().Player.Player
// Player no longer is joining teams
// May want to do this during despawn because clearing team requests in O(n).
h.clearTeamRequests(player)
// Removes team or transfers ownership, if applicable
h.leaveTeam(player)
client.Data().Hub = nil
h.clients.Remove(client)
// Remove in Despawn during leaderboard update.
h.despawn.Add(client)
case in := <-h.inbound:
// Read all messages currently in the channel
n := len(h.inbound)
for {
// If not same hub the message is old
data := in.Client.Data()
if h == data.Hub {
in.Process(h, in.Client, &data.Player)
}
if n--; n <= 0 {
break
}
in = <-h.inbound
}
case updateTime := <-h.updateTicker.C:
now := time.Now()
if missed := now.Sub(updateTime) - updatePeriod/10; missed > 0 {
h.skippedCounter += int(missed/updatePeriod) + 1
break
}
// Physics would start to break down after this.
const maxTicksPerUpdate = 4
if h.skippedCounter > maxTicksPerUpdate {
fmt.Println("server behind more than", maxTicksPerUpdate, "ticks:", h.skippedCounter)
h.skippedCounter = maxTicksPerUpdate
}
ticks := world.Ticks(h.skippedCounter) + 1
h.skippedCounter = 0
h.Physics(ticks)
h.Update()
case <-h.leaderboardTicker.C:
h.terrain.Repair()
h.Despawn()
h.Spawn()
h.Leaderboard()
h.worldRadius = world.Lerp(h.worldRadius, world.RadiusOf(h.clients.Len), 0.25)
h.world.Resize(h.worldRadius)
case <-h.debugTicker.C:
h.Debug()
case <-h.botsTicker.C:
// There are two reasons to add bots:
// - When minPlayers is not met by bots + clients
// - When minBotRatio is not met by bots / clients
playerCount := 0
for client := h.clients.First; client != nil; client = client.Data().Next {
if !client.Bot() {
playerCount++
}
}
botCount := h.clients.Len - playerCount
minBots := int(float32(playerCount) * minBotRatio)
totalClients := h.clients.Len + len(h.register) - len(h.unregister)
// Add as many as fit in the channel but don't block because it would deadlock
for i := totalClients; i < h.minPlayers || botCount < minBots; i++ {
select {
case h.register <- &BotClient{}:
botCount++
default:
break
}
}
case <-h.cloudTicker.C:
h.Cloud()
}
}
}
func (h *Hub) clearTeamRequests(player *world.Player) {
for _, team := range h.teams {
team.JoinRequests.Remove(player)
}
}
// Removes a player from the team that they are on. If the player was the owner,
// transfers or deletes the team depending on if there are remaining members
func (h *Hub) leaveTeam(player *world.Player) {
if team := h.teams[player.TeamID]; team != nil {
team.Members.Remove(player)
// Team is empty, delete it
if len(team.Members) == 0 {
delete(h.teams, player.TeamID)
}
}
player.TeamID = world.TeamIDInvalid
}