-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.go
301 lines (255 loc) · 9.71 KB
/
main.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
// main.go
// Copyright(c) 2022-2024 vice contributors, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
// This file contains the implementation of the main() function, which
// initializes the system and then runs the event loop until the system
// exits.
import (
_ "embed"
"flag"
"fmt"
"log/slog"
_ "net/http/pprof"
"os"
"runtime"
"runtime/debug"
"strings"
"time"
av "github.com/mmp/vice/pkg/aviation"
"github.com/mmp/vice/pkg/log"
"github.com/mmp/vice/pkg/panes"
"github.com/mmp/vice/pkg/platform"
"github.com/mmp/vice/pkg/rand"
"github.com/mmp/vice/pkg/renderer"
"github.com/mmp/vice/pkg/sim"
"github.com/mmp/vice/pkg/util"
"github.com/apenwarr/fixconsole"
"github.com/mmp/imgui-go/v4"
)
var (
//go:embed resources/version.txt
buildVersion string
// Command-line options are only used for developer features.
cpuprofile = flag.String("cpuprofile", "", "write CPU profile to file")
memprofile = flag.String("memprofile", "", "write memory profile to this file")
logLevel = flag.String("loglevel", "info", "logging level: debug, info, warn, error")
logDir = flag.String("logdir", "", "log file directory")
lintScenarios = flag.Bool("lint", false, "check the validity of the built-in scenarios")
server = flag.Bool("runserver", false, "run vice scenario server")
serverPort = flag.Int("port", sim.ViceServerPort, "port to listen on when running server")
serverAddress = flag.String("server", sim.ViceServerAddress+fmt.Sprintf(":%d", sim.ViceServerPort), "IP address of vice multi-controller server")
scenarioFilename = flag.String("scenario", "", "filename of JSON file with a scenario definition")
videoMapFilename = flag.String("videomap", "", "filename of JSON file with video map definitions")
broadcastMessage = flag.String("broadcast", "", "message to broadcast to all active clients on the server")
broadcastPassword = flag.String("password", "", "password to authenticate with server for broadcast message")
resetSim = flag.Bool("resetsim", false, "discard the saved simulation and do not try to resume it")
showRoutes = flag.String("routes", "", "display the STARS, SIDs, and approaches known for the given airport")
listMaps = flag.String("listmaps", "", "path to a video map file to list maps of (e.g., resources/videomaps/ZNY-videomaps.gob.zst)")
)
func init() {
// OpenGL and friends require that all calls be made from the primary
// application thread, while by default, go allows the main thread to
// run on different hardware threads over the course of
// execution. Therefore, we must lock the main thread at startup time.
runtime.LockOSThread()
}
func main() {
flag.Parse()
rand.Seed(time.Now().UnixNano())
// Common initialization for both client and server
if err := fixconsole.FixConsoleIfNeeded(); err != nil {
// Not sure this will actually appear, but what else are we going
// to do...
fmt.Printf("FixConsole: %v\n", err)
}
// Initialize the logging system first and foremost.
lg := log.New(*server, *logLevel, *logDir)
profiler, err := util.CreateProfiler(*cpuprofile, *memprofile)
if err != nil {
lg.Errorf("%v", err)
}
defer profiler.Cleanup()
if *serverAddress != "" && !strings.Contains(*serverAddress, ":") {
*serverAddress += fmt.Sprintf(":%d", sim.ViceServerPort)
}
if *lintScenarios {
var e util.ErrorLogger
scenarioGroups, _, _ :=
sim.LoadScenarioGroups(true, *scenarioFilename, *videoMapFilename, &e, lg)
videoMaps := make(map[string]interface{})
for _, sgs := range scenarioGroups {
for _, sg := range sgs {
if sg.STARSFacilityAdaptation.VideoMapFile != "" {
videoMaps[sg.STARSFacilityAdaptation.VideoMapFile] = nil
}
}
}
for m := range videoMaps {
av.CheckVideoMapManifest(m, &e)
}
if e.HaveErrors() {
e.PrintErrors(nil)
os.Exit(1)
}
scenarioAirports := make(map[string]map[string]interface{})
for tracon, scenarios := range scenarioGroups {
if scenarioAirports[tracon] == nil {
scenarioAirports[tracon] = make(map[string]interface{})
}
for _, sg := range scenarios {
for name := range sg.Airports {
scenarioAirports[tracon][name] = nil
}
}
}
for _, tracon := range util.SortedMapKeys(scenarioAirports) {
airports := util.SortedMapKeys(scenarioAirports[tracon])
fmt.Printf("%s (%s),\n", tracon, strings.Join(airports, ", "))
}
os.Exit(0)
} else if *broadcastMessage != "" {
sim.BroadcastMessage(*serverAddress, *broadcastMessage, *broadcastPassword, lg)
} else if *server {
sim.RunServer(*scenarioFilename, *videoMapFilename, *serverPort, lg)
} else if *showRoutes != "" {
if err := av.PrintCIFPRoutes(*showRoutes); err != nil {
lg.Errorf("%s", err)
}
} else if *listMaps != "" {
var e util.ErrorLogger
av.PrintVideoMaps(*listMaps, &e)
if e.HaveErrors() {
e.PrintErrors(lg)
}
} else {
var stats Stats
var render renderer.Renderer
var plat platform.Platform
// Catch any panics so that we can put up a dialog box and hopefully
// get a bug report.
if os.Getenv("DELVE_GOVERSION") == "" { // hack: don't catch panics when debugging..
defer func() {
if err := recover(); err != nil {
lg.Error("Caught panic!", slog.String("stack", string(debug.Stack())))
ShowFatalErrorDialog(render, plat, lg,
"Unfortunately an unexpected error has occurred and vice is unable to recover.\n"+
"Apologies! Please do file a bug and include the vice.log file for this session\nso that "+
"this bug can be fixed.\n\nError: %v", err)
}
}()
}
///////////////////////////////////////////////////////////////////////////
// Global initialization and set up. Note that there are some subtle
// inter-dependencies in the following; the order is carefully crafted.
_ = imguiInit()
config, configErr := LoadOrMakeDefaultConfig(lg)
var controlClient *sim.ControlClient
var mgr *sim.ConnectionManager
var err error
var simErrorLogger util.ErrorLogger
mgr, err = sim.MakeServerConnection(*serverAddress, *scenarioFilename, *videoMapFilename,
&simErrorLogger, lg,
func(c *sim.ControlClient) { // updated client
if c != nil {
panes.ResetSim(config.DisplayRoot, c, c.State, plat, lg)
}
uiResetControlClient(c)
controlClient = c
},
func(err error) {
switch err {
case sim.ErrRPCVersionMismatch:
ShowErrorDialog(plat, lg,
"This version of vice is incompatible with the vice multi-controller server.\n"+
"If you're using an older version of vice, please upgrade to the latest\n"+
"version for multi-controller support. (If you're using a beta build, then\n"+
"thanks for your help testing vice; when the beta is released, the server\n"+
"will be updated as well.)")
case sim.ErrServerDisconnected:
ShowErrorDialog(plat, lg, "Lost connection to the vice server.")
uiShowConnectDialog(mgr, false, config, plat, lg)
default:
lg.Error("Server connection error: %v", err)
}
},
)
if err != nil {
lg.Errorf("%v", err)
os.Exit(1)
}
plat, err = platform.New(&config.Config, lg)
if err != nil {
panic(fmt.Sprintf("Unable to create application window: %v", err))
}
if configErr != nil {
ShowErrorDialog(plat, lg, "Configuration file is corrupt: %v", configErr)
}
imgui.CurrentIO().SetClipboard(plat.GetClipboard())
render, err = renderer.NewOpenGL2Renderer(lg)
if err != nil {
panic(fmt.Sprintf("Unable to initialize OpenGL: %v", err))
}
renderer.FontsInit(render, plat)
eventStream := sim.NewEventStream(lg)
uiInit(render, plat, config, eventStream, lg)
config.Activate(render, plat, eventStream, lg)
if simErrorLogger.HaveErrors() { // After we have plat and render
ShowFatalErrorDialog(render, plat, lg, "%s", simErrorLogger.String())
}
// After config.Activate(), if we have a loaded sim, get configured for it.
if config.Sim != nil && !*resetSim {
if client, err := mgr.LoadLocalSim(config.Sim, lg); err != nil {
lg.Errorf("Error loading local sim: %v", err)
} else {
panes.LoadedSim(config.DisplayRoot, client, client.State, plat, lg)
uiResetControlClient(client)
controlClient = client
}
}
if !mgr.Connected() {
uiShowConnectDialog(mgr, false, config, plat, lg)
}
///////////////////////////////////////////////////////////////////////////
// Main event / rendering loop
lg.Info("Starting main loop")
stats.startTime = time.Now()
for {
plat.SetWindowTitle("vice: " + controlClient.Status())
if controlClient == nil {
SetDiscordStatus(DiscordStatus{Start: mgr.ConnectionStartTime()}, config, lg)
} else {
SetDiscordStatus(DiscordStatus{
TotalDepartures: controlClient.State.TotalDepartures,
TotalArrivals: controlClient.State.TotalArrivals,
Callsign: controlClient.State.Callsign,
Start: mgr.ConnectionStartTime(),
}, config, lg)
}
mgr.Update(eventStream, lg)
// Inform imgui about input events from the user.
plat.ProcessEvents()
stats.redraws++
plat.NewFrame()
imgui.NewFrame()
// Generate and render vice draw lists
stats.drawPanes = panes.DrawPanes(config.DisplayRoot, plat, render, controlClient,
ui.menuBarHeight, &config.AudioEnabled, lg)
// Draw the user interface
stats.drawUI = uiDraw(mgr, config, plat, render, controlClient, eventStream, lg)
// Wait for vsync
plat.PostRender()
// Periodically log current memory use, etc.
if stats.redraws%18000 == 0 {
lg.Info("performance", slog.Any("stats", stats))
}
if plat.ShouldStop() && len(ui.activeModalDialogs) == 0 {
// Do this while we're still running the event loop.
saveSim := mgr.ClientIsLocal()
config.SaveIfChanged(render, plat, controlClient, saveSim, lg)
mgr.Disconnect()
break
}
}
}
}