-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsystem.go
More file actions
371 lines (309 loc) · 9.63 KB
/
system.go
File metadata and controls
371 lines (309 loc) · 9.63 KB
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
package ecs
import (
"fmt"
"sync/atomic"
"time"
"runtime"
)
// Represents an individual system
type System struct {
Name string
Func func(dt time.Duration)
}
func (s System) Build(world *World) System {
return s
}
// Create a new system. The system name will be automatically created based on the function name that calls this function
func NewSystem(lambda func(dt time.Duration)) System {
systemName := "UnknownSystemName"
pc, _, _, ok := runtime.Caller(1)
if ok {
details := runtime.FuncForPC(pc)
systemName = details.Name()
}
return System{
Name: systemName,
Func: lambda,
}
}
// Executes the system once, returning the time taken.
// This is mostly used by the scheduler, but you can use it too.
func (s *System) step(dt time.Duration) {
// Note: Disable timing
s.Func(dt)
// return 0
// fmt.Println(s.Name) // Spew
// start := time.Now()
// s.Func(dt)
// return time.Since(start)
}
// A log of a system and the time it took to execute
type SystemLog struct {
Name string
Time time.Duration
}
func (s *SystemLog) String() string {
return fmt.Sprintf("%s: %s", s.Name, s.Time)
}
// // TODO - Just use an atomic here?
// type signal struct {
// mu sync.Mutex
// value bool
// }
// func (s *signal) Set(val bool) {
// s.mu.Lock()
// s.value = val
// s.mu.Unlock()
// }
// func (s *signal) Get() bool {
// s.mu.Lock()
// ret := s.value
// s.mu.Unlock()
// return ret
// }
// Scheduler is a place to put your systems and have them run.
// There are two types of systems: Fixed time systems and dynamic time systems
// 1. Fixed time systems will execute on a fixed time step
// 2. Dynamic time systems will execute as quickly as they possibly can
// The scheduler may change in the future, but right now how it works is simple:
// Input: Execute input systems (Dynamic time systems)
// Physics: Execute physics systems (Fixed time systems)
// Render: Execute render systems (Dynamic time systems)
type Scheduler struct {
world *World
systems [][]System
sysTimeFront, sysTimeBack [][]SystemLog // Rotating log of how long each system takes
// stageTimingFront, stageTimingBack []SystemLog // Rotating log of how long each stage takes
fixedTimeStep time.Duration
accumulator time.Duration
gameSpeed float64
quit atomic.Bool
pauseRender atomic.Bool
maxLoopCount int
}
// Creates a scheduler
func NewScheduler(world *World) *Scheduler {
return &Scheduler{
world: world,
systems: make([][]System, StageLast+1),
sysTimeFront: make([][]SystemLog, StageLast+1),
sysTimeBack: make([][]SystemLog, StageLast+1),
fixedTimeStep: 16 * time.Millisecond,
accumulator: 0,
gameSpeed: 1,
}
}
// TODO make SetGameSpeed and SetFixedTimeStep thread safe.
// Sets the rate at which time accumulates. Also, you want them to only change at the end of a frame, else you might get some inconsistencies. Just use a mutex and a single temporary variable
func (s *Scheduler) SetGameSpeed(speed float64) {
s.gameSpeed = speed
}
// Tells the scheduler to exit. Scheduler will finish executing its remaining tick before closing.
func (s *Scheduler) SetQuit(value bool) {
s.quit.Store(true)
}
// Returns the quit value of the scheduler
func (s *Scheduler) Quit() bool {
return s.quit.Load()
}
// Pauses the set of render systems (ie they will be skipped).
// Deprecated: This API is tentatitive
func (s *Scheduler) PauseRender(value bool) {
s.pauseRender.Store(value)
}
// Sets the amount of time required before the fixed time systems will execute
func (s *Scheduler) SetFixedTimeStep(t time.Duration) {
s.fixedTimeStep = t
}
type Stage uint8
func (s Stage) String() string {
switch s {
case StageStartup:
return "StageStartup"
case StagePreUpdate:
return "StagePreUpdate"
case StageFixedUpdate:
return "StageFixedUpdate"
case StageUpdate:
return "StageUpdate"
case StageLast:
return "StageLast"
}
return "Unknown"
}
const (
// StagePreStartup
StageStartup Stage = iota
// StagePostStartup
// StageFirst
StagePreUpdate // Note: Used to be Input
// StageStateTransition
StageFixedUpdate
// StagePostFixedUpdate
StageUpdate
// StagePostUpdate
StageLast
)
// Returns true if the scheduler only has fixed systems
func (s *Scheduler) isFixedOnly() bool {
return len(s.systems[StagePreUpdate]) == 0 && len(s.systems[StageUpdate]) == 0 && len(s.systems[StageLast]) == 0
}
func (s *Scheduler) ClearSystems(stage Stage) {
// Note: Make a new slices so that any of the old system pointers get released
s.systems[stage] = make([]System, 0)
}
func (s *Scheduler) AddSystems(stage Stage, systems ...SystemBuilder) {
for _, sys := range systems {
system := sys.Build(s.world)
s.systems[stage] = append(s.systems[stage], system)
}
}
func (s *Scheduler) SetSystems(stage Stage, systems ...SystemBuilder) {
s.ClearSystems(stage)
s.AddSystems(stage, systems...)
}
// Sets the accumulator maximum point so that if the accumulator gets way to big, we will reset it and continue on, dropping all physics ticks that would have been executed. This is useful in a runtime like WASM where the browser may not let us run as frequently as we may need (for example, when the tab is hidden or minimized).
// Note: This must be set before you call scheduler.Run()
// Note: The default value is 0, which will force every physics tick to run. I highly recommend setting this to something if you plan to build for WASM!
func (s *Scheduler) SetMaxPhysicsLoopCount(count int) {
s.maxLoopCount = count
}
func (s *Scheduler) Syslog(stage Stage) []SystemLog {
return s.sysTimeFront[stage]
}
// Returns an interpolation value which represents how close we are to the next fixed time step execution. Can be useful for interpolating dynamic time systems to the fixed time systems. I might rename this
func (s *Scheduler) GetRenderInterp() float64 {
return s.accumulator.Seconds() / s.fixedTimeStep.Seconds()
}
func (s *Scheduler) runUntrackedStage(stage Stage, dt time.Duration) {
for _, sys := range s.systems[stage] {
sys.step(dt)
s.world.cmd.Execute()
}
}
func (s *Scheduler) runStage(stage Stage, dt time.Duration) {
// start := time.Now()
// Rotate syslog
{
tmp := s.sysTimeFront[stage]
s.sysTimeFront[stage] = s.sysTimeBack[stage]
s.sysTimeBack[stage] = tmp[:0]
}
// Append all stages
for _, sys := range s.systems[stage] {
sysStart := time.Now()
sys.step(dt)
s.world.cmd.Execute()
s.sysTimeBack[stage] = append(s.sysTimeBack[stage], SystemLog{
Name: sys.Name,
Time: time.Since(sysStart),
})
}
// // Track full stage timing
// // TODO: This doesn't work, because it clears on every single stage run
// {
// tmp := s.stageTimingFront
// s.stageTimingFront = s.stageTimingBack
// s.stageTimingBack = tmp[:0]
// }
// s.stageTimingBack = append(s.stageTimingBack, SystemLog{
// Name: "STAGE NAME TODO",
// Time: time.Since(start),
// })
}
// Performs a single step of the scheduler with the provided time
func (s *Scheduler) Step(dt time.Duration) {
// Pre Update
s.runStage(StagePreUpdate, dt)
maxLoopCount := time.Duration(s.maxLoopCount)
if maxLoopCount > 0 {
if s.accumulator > (maxLoopCount * s.fixedTimeStep) {
s.accumulator = s.fixedTimeStep // Just run one loop
}
}
// Physics Systems
for s.accumulator >= s.fixedTimeStep {
s.runStage(StageFixedUpdate, s.fixedTimeStep)
s.accumulator -= s.fixedTimeStep
}
// Render Systems
if !s.pauseRender.Load() {
s.runStage(StageUpdate, dt)
}
}
// Note: Would be nice to sleep or something to prevent spinning while we wait for work to do
// Could also separate the render loop from the physics loop (requires some thread safety in ECS)
func (s *Scheduler) Run() {
s.runUntrackedStage(StageStartup, 0)
frameStart := time.Now()
dt := s.fixedTimeStep
s.accumulator = 0
for !s.quit.Load() {
s.Step(dt)
// Edge case for schedules only fixed time steps
if s.isFixedOnly() {
// Note: This is guaranteed to be positive because the physics execution loops until the accumulator is less than fixedtimestep
time.Sleep(s.fixedTimeStep - s.accumulator)
}
// Capture Frame time
now := time.Now()
dt = now.Sub(frameStart)
frameStart = now
scaledDt := float64(dt.Nanoseconds()) * s.gameSpeed
s.accumulator += time.Duration(scaledDt)
}
}
// //Separates physics loop from render loop
// func (s *Scheduler) Run2() {
// var worldMu sync.Mutex
// frameStart := time.Now()
// dt := s.fixedTimeStep
// // var accumulator time.Duration
// s.accumulator = 0
// maxLoopCount := time.Duration(s.maxLoopCount)
// // physicsTicker := time.NewTicker(s.fixedTimeStep)
// // defer physicsTicker.Stop()
// go func() {
// // for {
// // _, more := <-physicsTicker.C
// // if !more { break } // Exit early, ticker channel is closed
// // // fmt.Println(phyTime)
// // worldMu.Lock()
// // for _, sys := range s.physics {
// // sys.Run(s.fixedTimeStep)
// // }
// // worldMu.Unlock()
// // }
// for !s.quit.Load() {
// worldMu.Lock()
// if maxLoopCount > 0 {
// if s.accumulator > (maxLoopCount * s.fixedTimeStep) {
// s.accumulator = s.fixedTimeStep // Just run one loop
// }
// }
// for s.accumulator >= s.fixedTimeStep {
// for _, sys := range s.physics {
// sys.Run(s.fixedTimeStep)
// }
// s.accumulator -= s.fixedTimeStep
// }
// worldMu.Unlock()
// time.Sleep(s.fixedTimeStep - s.accumulator)
// }
// }()
// for !s.quit.Load() {
// worldMu.Lock()
// for _, sys := range s.render {
// sys.Run(dt)
// }
// for _, sys := range s.input {
// sys.Run(dt)
// }
// // Capture Frame time
// now := time.Now()
// dt = now.Sub(frameStart)
// frameStart = now
// s.accumulator += dt
// worldMu.Unlock()
// }
// }