-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsim.go
272 lines (216 loc) · 5.79 KB
/
sim.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
package game
import (
"fmt"
"log"
"net/http"
"sync"
"text/template"
"github.com/ghthor/aodd/game/datastore"
"github.com/ghthor/filu/rpg2d"
"github.com/ghthor/filu/rpg2d/coord"
"github.com/ghthor/filu/rpg2d/entity"
"github.com/ghthor/filu/rpg2d/quad"
"github.com/ghthor/filu/sim/stime"
)
// Store actor's indexed by id
type ActorIndex map[rpg2d.ActorId]*actor
const quadMaxSize = 20
// A wrapper for actorIndex that provides
// safety for concurrent access.
type ActorIndexLocker struct {
sync.RWMutex
index ActorIndex
}
func (m *ActorIndexLocker) RLock() ActorIndex {
m.RWMutex.RLock()
return m.index
}
func (m *ActorIndexLocker) Lock() ActorIndex {
m.RWMutex.Lock()
return m.index
}
func (m *ActorIndexLocker) Unlock(index ActorIndex) {
m.index = index
m.RWMutex.Unlock()
}
func NewActorIndexLocker(around ActorIndex) *ActorIndexLocker {
return &ActorIndexLocker{index: around}
}
// Type used to wrap a running simulation interface
// and start and stop the actor's IO muxer.
// Also adds and removes actors from the
// simulation's actor index.
type simulation struct {
*ActorIndexLocker
rpg2d.RunningSimulation
}
func (s simulation) ConnectActor(a rpg2d.Actor) {
switch a := a.(type) {
case *actor:
a.startIO()
actorIndex := s.ActorIndexLocker.Lock()
actorIndex[a.Id()] = a
s.ActorIndexLocker.Unlock(actorIndex)
default:
panic(fmt.Sprint("unexpected sim.Actor:", a))
}
s.RunningSimulation.ConnectActor(a)
}
func (s simulation) RemoveActor(a rpg2d.Actor) {
s.RunningSimulation.RemoveActor(a)
switch a := a.(type) {
case *actor:
a.stopIO()
actorIndex := s.ActorIndexLocker.Lock()
delete(actorIndex, a.Id())
s.ActorIndexLocker.Unlock(actorIndex)
default:
panic(fmt.Sprint("unexpected sim.Actor:", a))
}
}
func NewSimulation(actorIndex *ActorIndexLocker, sim rpg2d.RunningSimulation) rpg2d.RunningSimulation {
return simulation{
ActorIndexLocker: actorIndex,
RunningSimulation: sim,
}
}
type indexHandler struct {
tmpl *template.Template
settings ClientSettings
}
func (index indexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := index.tmpl.Execute(w, index.settings)
if err != nil {
http.Error(w, fmt.Sprint("template error:", err), http.StatusInternalServerError)
}
}
// A set of data that the index page template will
// have access to when it is executed.
type ClientSettings struct {
JsMain string
WebsocketURL string
Simulation SimulationSettings
}
// Part of the ClientSettings that are rpg2d.Simulation specific
type SimulationSettings struct {
Width, Height int
}
type ShardConfig struct {
// Flag whether the server is running from heroku
OnHeroku bool
// FQDN that the server is running at
Domain,
// Port that the server is running on
Port,
// Path to javascript directory
JsDir,
// The javascript module that require.js should
// call as the javascript main.
JsMain,
// Path to the graphic asset directory
AssetDir,
// Path to the css directory
CssDir string
// A template for the index page. The template
// will be executed with a game.ClientSettings{} struct.
IndexTmpl *template.Template
// A mux that http server will use. Is provided so the
// user can extend the server with additional routes.
Mux *http.ServeMux
// A handler that will be used instead of the Mux
// when setting the Handler field of the *http.Server.
// If Handler is nil, the Mux will be used instead.
Handler http.Handler
}
type inputReceiver struct {
*actor
disconnect func()
}
func (i inputReceiver) Close() {
i.disconnect()
}
func NewSimShard(c ShardConfig) (*http.Server, error) {
// TODO pull this information from a datastore
bounds := coord.Bounds{
coord.Cell{1, -1},
coord.Cell{128, -128},
}
quadTree, err := quad.New(bounds, quadMaxSize, nil)
if err != nil {
return nil, err
}
terrainMap, err := rpg2d.NewTerrainMap(bounds, startingTerrain)
if err != nil {
return nil, err
}
now := stime.Time(0)
actorIndex := NewActorIndexLocker(make(ActorIndex))
entityIdGen := entity.NewIdGenerator()
quadTree = addWalls(quadTree, entityIdGen)
simDef := rpg2d.SimulationDef{
FPS: 40,
// Initial World State
Now: now,
QuadTree: quadTree,
TerrainMap: terrainMap,
UpdatePhaseHandler: updatePhaseLocker{actorIndex},
InputPhaseHandler: inputPhaseLocker{actorIndex, entityIdGen},
NarrowPhaseHandler: newNarrowPhaseLocker(actorIndex),
}
runningSim, err := simDef.Begin()
if err != nil {
return nil, err
}
wsUrl := "ws://" + c.Domain
wsRoute := "/actor/socket/gob"
if !c.OnHeroku {
wsUrl += ":" + c.Port
}
wsUrl += wsRoute
indexHandler := indexHandler{
c.IndexTmpl,
ClientSettings{
c.JsMain,
wsUrl,
SimulationSettings{
Width: quadTree.Bounds().Width(),
Height: quadTree.Bounds().Height(),
},
},
}
mux := c.Mux
ds := datastore.NewMemDatastore()
sim := NewSimulation(actorIndex, runningSim)
mux.Handle("/", indexHandler)
mux.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir(c.JsDir))))
mux.Handle("/asset/", http.StripPrefix("/asset/", http.FileServer(http.Dir(c.AssetDir))))
mux.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir(c.CssDir))))
mux.Handle(wsRoute, newGobWebsocketHandler(
ds,
func(dsactor datastore.Actor, stateWriter InitialStateWriter) (InputReceiver, entity.State) {
actor := NewActor(entityIdGen(), dsactor, stateWriter)
sim.ConnectActor(actor)
return inputReceiver{
actor: actor,
disconnect: func() {
sim.RemoveActor(actor)
log.Println("actor removed", actor.name)
},
}, actor.Entity().ToState()
},
))
defaultHandler := c.Handler
if defaultHandler == nil {
defaultHandler = mux
}
var laddr string
if c.OnHeroku {
laddr = ":" + c.Port
} else {
laddr = fmt.Sprintf("%s:%s", c.Domain, c.Port)
}
return &http.Server{
Addr: laddr,
Handler: defaultHandler,
}, nil
}