forked from gazed/vu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vu.go
458 lines (413 loc) · 14.8 KB
/
vu.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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright © 2015 Galvanized Logic Inc.
// Use is governed by a BSD-style license found in the LICENSE file.
// Package vu, virtual universe, provides 3D application support. Vu wraps
// subsystems like rendering, physics, data loading, audio, etc. to provide
// higher level functionality that includes:
// • Transform graphs and composite objects.
// • Timestepped update/render loop.
// • Access to user input events.
// • Cameras and transform manipulation.
// • Delivering loaded assets to render and audio devices.
// Refer to the vu/eg package for examples of engine functionality.
//
// Vu dependencies are:
// • OpenGL for graphics card access. See package vu/render.
// • OpenAL for sound card access. See package vu/audio.
// • Cocoa for OSX windowing and input. See package vu/device.
// • WinAPI for Windows windowing and input. See package vu/device.
package vu
// Design note: vu contains the main thread "machine" which
// is controlled by the "engine" state update goroutine.
// Concurrency design is based on "Share memory by communicating"
// http://golang.org/doc/codewalk/sharemem
// in which passing pointers to structure instances between goroutines
// passes ownership of those instances.
import (
"fmt"
"log"
"os"
"runtime/debug"
"github.com/gazed/vu/audio"
"github.com/gazed/vu/device"
"github.com/gazed/vu/render"
)
// New creates the Engine and initializes the underlying resources needed
// by the engine. It then starts application callbacks through the engine
// App interface. This is expected to be called once on application startup.
func New(app App, name string, wx, wy, ww, wh int) (err error) {
m := &machine{} // main thread and device facing handler.
if app == nil {
return fmt.Errorf("No application. Shutting down.")
}
m.counts = map[uint32]*meshCount{}
// initialize the os specific shell, graphics context, and input tracker.
name, wx, wy, ww, wh = m.vet(name, wx, wy, ww, wh)
m.dev = device.New(name, wx, wy, ww, wh)
// initialize the audio layer.
m.ac = audio.New()
if err = m.ac.Init(); err != nil {
m.shutdown()
return // failed to initialize audio layer
}
// initialize the graphics layer.
m.gc = render.New()
if err = m.gc.Init(); err != nil {
m.shutdown()
return // failed to initialize graphics layer.
}
m.gc.Viewport(ww, wh)
m.dev.Open()
m.input = m.dev.Update()
m.frame1 = []render.Draw{} // Previous render frame.
m.frame0 = []render.Draw{} // Most recent render frame.
// Start the application facing loop for state updates.
// Run the device facing loop for rendering and user input polling.
m.reqs = make(chan msg)
m.stop = make(chan bool)
m.uf = make(chan []render.Draw)
go runEngine(app, wx, wy, ww, wh, m.reqs, m.uf, m.stop)
m.run() // underlying device polling and rendering.
defer m.shutdown() // ensure shutdown happens no matter what.
return nil // report successful termination.
}
// Engine constants needed as input to methods as noted in the
// comments below.
const (
// Global graphic state constants. See Eng.State
BLEND = render.BLEND // Alpha blending. Enabled by default.
CULL = render.CULL // Backface culling. Enabled by default.
DEPTH = render.DEPTH // Z-buffer awareness. Enabled by default.
// Per-part rendering constants for Model.SetDrawMode.
TRIANGLES = render.TRIANGLES // Triangles are the norm.
POINTS = render.POINTS // Used for particle effects.
LINES = render.LINES // Used for drawing squares and boxes.
// User input key released indicator. Total time down, in update ticks,
// is key down ticks minus RELEASED. See App.Update.
RELEASED = device.KEY_RELEASED
// Texture rendering directives for Model.SetTexMode()
TEX_REPEAT = iota // Repeat texture when UV greater than 1.
TEX_CLAMP // Clamp to texture edge.
// 3D Direction constants. Primarily used for panning or rotating a camera.
// See Camera.Spin.
XAxis // Affect only the X axis.
YAxis // Affect only the Y axis.
ZAxis // Affect only the Z axis.
// Application created and controlled objects associated with the transform
// hierarchy. See Pov.Dispose.
POV // Transform hierarchy node and 3D location:orientation.
MODEL // Rendered model attached to a Pov.
BODY // Physics body attached to a Pov.
CAMERA // Camera attached to a Pov.
NOISE // Sound attached to a Pov.
LIGHT // Light attached to a Pov.
LAYER // Render pass layer attached to a Pov.
)
// vu
// =============================================================================
// This is the machine and it is driven by the application facing engine class.
// machine deals with initialization and handling of all underlying hardware;
// generally through the OS, GPU, and audio API's. Machine is expected to be
// run from the main thread -- this is enforced by those aforementioned API's.
// Machine process requests from the application facing engine class.
type machine struct {
gc render.Renderer // Graphics card interface layer.
dev device.Device // Os specific window and rendering context.
ac audio.Audio // Audio card interface layer.
input *device.Pressed // Latest user keyboard and mouse input.
frame1 []render.Draw // Previous render frame.
frame0 []render.Draw // Most recent render frame.
uf chan []render.Draw // pass back frame for updating.
reqs chan msg // Requests from the application loop.
stop chan bool // Used to shutdown the engine.
// Counts keeps track of the number of faces and verticies for
// each successfully bound mesh.
counts map[uint32]*meshCount
}
// run is the main thread. Only the main thread can interact with the
// device layer and the rendering context. This loop depends on frequent
// and regular calls from the application update both for polling
// user input and rendering.
func (m *machine) run() {
m.gc.Enable(BLEND, true) // expected application startup state.
m.gc.Enable(CULL, true) // expected application startup state.
for m.dev != nil && m.dev.IsAlive() {
req := <-m.reqs // req is nil for closed channel.
// handle all communication, blocking until there is a request
// to process. Requests wait until the current request is finished.
switch t := req.(type) {
case *shutdown:
return // exit immediately. User shutdown engine.
case *appData:
m.refreshAppData(t) // poll to refresh device input.
default:
switch t := req.(type) {
case *renderFrame:
m.render(t)
case *bindData:
m.bind(t)
case *setColour:
m.gc.Color(t.r, t.g, t.b, t.a)
case *enableAttr:
m.gc.Enable(t.attr, t.enable)
case *toggleScreen:
m.dev.ToggleFullScreen()
case *setVolume:
m.ac.SetGain(t.gain)
case *setCursor:
m.dev.SetCursorAt(t.cx, t.cy)
case *showCursor:
m.dev.ShowCursor(t.enable)
case *placeListener:
m.ac.PlaceListener(t.x, t.y, t.z)
case *playSound:
m.ac.PlaySound(t.sid, t.x, t.y, t.z)
case *releaseData:
m.release(t)
case nil:
return // exit immediately: channel closed.
default:
log.Printf("machine: unknown msg %T", t)
}
}
}
close(m.stop) // The underlying device is gone, stop the engine.
}
// shutdown properly cleans up and closes the device layers.
func (m *machine) shutdown() {
if m.ac != nil {
m.ac.Dispose()
m.ac = nil
}
if m.dev != nil {
m.dev.Dispose()
m.dev = nil
}
}
// render passes the frame draw data to the supporting render layer.
// If there is a new frame, then unused frame is sent back for updating.
func (m *machine) render(r *renderFrame) {
// update the previous and current render frames with a new frame.
if r.frame != nil && len(r.frame) > 0 {
updateFrame := m.frame1 // return this frame to be updated.
m.frame1 = m.frame0 // previous frame.
m.frame0 = r.frame // new frame.
m.uf <- updateFrame // return frame for updating.
}
// FUTURE: use interpolation between current and previous frames
// for render requests between frame updates.
m.gc.Clear()
for _, drawing := range m.frame0 {
if drawing.Vao() > 0 {
m.setCounts(drawing)
m.gc.Render(drawing)
} else {
log.Printf("machine.render: bad mesh vao %d", drawing.Vao())
}
}
m.dev.SwapBuffers()
}
// refreshAppData gathers user input and returns it on request.
// The underlying device layer collects input since last call.
// Expected to be called once per update tick.
func (m *machine) refreshAppData(data *appData) {
data.input.convertInput(m.input, 0, 0) // refresh user data.
if data.input.Resized {
data.state.setScreen(m.dev.Size())
m.gc.Viewport(data.state.W, data.state.H)
}
data.state.FullScreen = m.dev.IsFullScreen()
data.reply <- data // return refreshed app data.
m.input = m.dev.Update() // get latest user input for next refresh.
}
// setCounts ensures the draw frame has the most recent number of
// verticies and faces. The objects may have been updated after the
// draw object was created by the engine.
func (m *machine) setCounts(d render.Draw) {
if cnts, ok := m.counts[d.Vao()]; ok {
d.SetCounts(cnts.faces, cnts.verticies)
} else {
log.Printf("machine.setCounts: must have mesh counts %d", d.Vao())
}
}
// bind sends data to the graphics or audio card and replies on the supplied
// channel when finished. Data needs to be bound once before it can be used
// for rendering or audio. Data needs rebinding if it is changed.
func (m *machine) bind(bd *bindData) {
switch d := bd.data.(type) {
case *mesh:
err := m.gc.BindMesh(&d.vao, d.vdata, d.faces)
if err != nil {
bd.reply <- fmt.Errorf("Failed mesh bind %s: %s", d.name, err)
} else {
cnts, ok := m.counts[d.vao]
if !ok {
cnts = &meshCount{}
m.counts[d.vao] = cnts
}
if d.faces != nil {
cnts.faces = d.faces.Len()
}
if d.vdata != nil && len(d.vdata) > 0 {
cnts.verticies = d.vdata[0].Len()
}
bd.reply <- nil
}
case *shader:
var err error
d.program, err = m.gc.BindShader(d.vsh, d.fsh, d.uniforms, d.layouts)
if err != nil {
bd.reply <- fmt.Errorf("Failed shader bind %s: %s", d.name, err)
} else {
bd.reply <- nil
}
case *texture:
err := m.gc.BindTexture(&d.tid, d.img, d.repeat)
if err != nil {
bd.reply <- fmt.Errorf("Failed texture bind %s: %s", d.name, err)
} else {
bd.reply <- nil
}
case *sound:
err := m.ac.BindSound(&d.sid, &d.did, d.data)
if err != nil {
bd.reply <- fmt.Errorf("Failed sound bind %s: %s", d.name, err)
} else {
bd.reply <- nil
}
case *layer:
err := m.gc.BindFrame(d.attr, &d.bid, &d.tex.tid, &d.db)
if err != nil {
bd.reply <- fmt.Errorf("Failed bind framebuffer %s", err)
} else {
bd.reply <- nil
}
default:
bd.reply <- fmt.Errorf("No bindings for %T", d)
}
}
// meshCount is used by bind to track the latest number
// of faces and verticies bound for a mesh.
type meshCount struct {
faces int // number of faces last bound.
verticies int // number of verticies last bound.
}
// release figures out what data to release based on the releaseData type.
func (m *machine) release(rd *releaseData) {
switch d := rd.data.(type) {
case *mesh:
m.gc.ReleaseMesh(d.vao)
case *shader:
m.gc.ReleaseShader(d.program)
case *texture:
m.gc.ReleaseTexture(d.tid)
case *sound:
m.ac.ReleaseSound(d.sid)
case *layer:
m.gc.ReleaseFrame(d.bid, d.tex.tid, d.db)
d.bid, d.tex.tid, d.db = 0, 0, 0
default:
log.Printf("machine.release: No bindings for %T", rd)
}
}
// constants to ensure reasonable input values.
const (
maxWindowTitle = 40 // Max number of characters for a window title.
minWindowSize = 100 // Miniumum pixels for a window width or height.
minWindowPosition = 0 // Bottom left corner of the screen.
)
// vet ensures that the startup parameters will result in a visible
// window with a window title.
func (m *machine) vet(name string, x0, y0, width, height int) (n string, x, y, w, h int) {
if len(name) > maxWindowTitle {
name = ""
}
if width < minWindowSize {
width = minWindowSize
}
if height < minWindowSize {
height = minWindowSize
}
if x0 < minWindowPosition {
x0 = minWindowPosition
}
if y0 < minWindowPosition {
y0 = minWindowPosition
}
return name, x0, y0, width, height
}
// machine
// =============================================================================
// msg
// msg are requests and data handled by the engine goroutine.
// Messages are pointers to one of the structures below.
// The struct type is the message and the struct fields carry the data.
type msg interface{}
// appData contains both user input and engine state passed to the
// application. A single copy, owned by the engine, is created on startup.
type appData struct {
input *Input // Refreshed each update.
state *State // Refreshed each update.
reply chan *appData // For syncing updates between machine and operator.
}
// newAppData expects to be called on startup for
// updating and communicating user input and global state.
func newAppData() *appData {
as := &appData{reply: make(chan *appData)}
as.input = &Input{Down: map[int]int{}}
as.state = &State{CullBacks: true, Blend: true}
as.state.setColour(0, 0, 0, 1)
return as
}
// shutdown is used to terminate a goroutine.
type shutdown struct{}
// bindData is a request to send data to the graphics or sound card.
type bindData struct {
data interface{} // msh, shd, tex, snd
reply chan error
}
// renderFrame requests a render. New render data is supplied after
// an update. Interpolation values are given for render requests
// between new frames. No reply is expected. Render data is expected
// to be created by the engine update loop and processed by the
// vu machine.
type renderFrame struct {
interp float64 // Fraction between 0 and 1.
frame []render.Draw // May be empty.
ut uint64 // Counter for debugging.
}
// placeListener locates the sounds listener in world space.
type placeListener struct {
x, y, z float64
}
// playSound plays the given sound at the given world location.
type playSound struct {
sid uint64
x, y, z float64
}
// state change messages. Engine to machine. Fire and forget.
type enableAttr struct {
attr uint32
enable bool
}
type setColour struct{ r, g, b, a float32 }
type setVolume struct{ gain float64 }
type setCursor struct{ cx, cy int }
type showCursor struct{ enable bool }
type toggleScreen struct{}
// releaseData is used to request the removal a resources associated
// with one of the following:
// bound and cached: *mesh, *shader, *texture, *sound, *noise,
// cached only : *material, *font, *animation
// bound only : *view
type releaseData struct {
data interface{}
}
// =============================================================================
// catchErrors should be defered at the top of each goroutine so that
// errors can be logged in production loads as required by the application.
func catchErrors() {
if r := recover(); r != nil {
log.Printf("Panic %s: %s Shutting down.", r, debug.Stack())
os.Exit(-1)
}
}