application.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. package application
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "runtime"
  7. "runtime/pprof"
  8. "runtime/trace"
  9. "time"
  10. "github.com/g3n/engine/audio/al"
  11. "github.com/g3n/engine/audio/vorbis"
  12. "github.com/g3n/engine/camera"
  13. "github.com/g3n/engine/camera/control"
  14. "github.com/g3n/engine/core"
  15. "github.com/g3n/engine/gls"
  16. "github.com/g3n/engine/gui"
  17. "github.com/g3n/engine/math32"
  18. "github.com/g3n/engine/renderer"
  19. "github.com/g3n/engine/util/logger"
  20. "github.com/g3n/engine/window"
  21. )
  22. // Application is a standard application object which can be used as a base for G3N applications.
  23. // It creates a Window, OpenGL state, default cameras, default scene and Gui and has a method to run the render loop.
  24. type Application struct {
  25. core.Dispatcher // Embedded event dispatcher
  26. core.TimerManager // Embedded timer manager
  27. wmgr window.IWindowManager // Window manager
  28. win window.IWindow // Application window
  29. gl *gls.GLS // OpenGL state
  30. log *logger.Logger // Default application logger
  31. renderer *renderer.Renderer // Renderer object
  32. camPersp *camera.Perspective // Perspective camera
  33. camOrtho *camera.Orthographic // Orthographic camera
  34. camera camera.ICamera // Current camera
  35. orbit *control.OrbitControl // Camera orbit controller
  36. frameRater *FrameRater // Render loop frame rater
  37. keyState *KeyState // State of keys
  38. audioDev *al.Device // Default audio device
  39. scene *core.Node // Node container for 3D tests
  40. guiroot *gui.Root // Gui root panel
  41. frameCount uint64 // Frame counter
  42. frameTime time.Time // Time at the start of the frame
  43. frameDelta time.Duration // Time delta from previous frame
  44. startTime time.Time // Time at the start of the render loop
  45. fullScreen *bool // Full screen option
  46. swapInterval *int // Swap interval option
  47. targetFPS *uint // Target FPS option
  48. noglErrors *bool // No OpenGL check errors options
  49. cpuProfile *string // File to write cpu profile to
  50. execTrace *string // File to write execution trace data to
  51. }
  52. // Options defines initial options passed to the application creation function
  53. type Options struct {
  54. Title string // Initial window title
  55. Height int // Initial window height (default is screen width)
  56. Width int // Initial window width (default is screen height)
  57. Fullscreen bool // Window full screen flag (default = false)
  58. LogPrefix string // Log prefix (default = "")
  59. LogLevel int // Initial log level (default = DEBUG)
  60. EnableFlags bool // Enable command line flags (default = false)
  61. TargetFPS uint // Desired frames per second rate (default = 60)
  62. }
  63. // OnBeforeRender is the event generated by Application just before rendering the scene/gui
  64. const OnBeforeRender = "util.application.OnBeforeRender"
  65. // OnAfterRender is the event generated by Application just after rendering the scene/gui
  66. const OnAfterRender = "util.application.OnAfterRender"
  67. // OnQuit is the event generated by Application when the user tries to close the window
  68. // or the Quit() method is called.
  69. const OnQuit = "util.application.OnQuit"
  70. // appInstance contains the pointer to the single Application instance
  71. var appInstance *Application
  72. // Create creates and returns the application object using the specified options.
  73. // This function must be called only once.
  74. func Create(ops Options) (*Application, error) {
  75. if appInstance != nil {
  76. return nil, fmt.Errorf("Application already created")
  77. }
  78. app := new(Application)
  79. appInstance = app
  80. app.Dispatcher.Initialize()
  81. app.TimerManager.Initialize()
  82. // Initialize options defaults
  83. app.fullScreen = new(bool)
  84. app.swapInterval = new(int)
  85. app.targetFPS = new(uint)
  86. app.noglErrors = new(bool)
  87. app.cpuProfile = new(string)
  88. app.execTrace = new(string)
  89. *app.swapInterval = -1
  90. *app.targetFPS = 60
  91. // Options parameter overrides some options
  92. if ops.TargetFPS != 0 {
  93. *app.fullScreen = ops.Fullscreen
  94. *app.targetFPS = ops.TargetFPS
  95. }
  96. // Creates flags if requested (override options defaults)
  97. if ops.EnableFlags {
  98. app.fullScreen = flag.Bool("fullscreen", false, "Starts application with full screen")
  99. app.swapInterval = flag.Int("swapinterval", -1, "Sets the swap buffers interval to this value")
  100. app.targetFPS = flag.Uint("targetfps", 60, "Sets the frame rate in frames per second")
  101. app.noglErrors = flag.Bool("noglerrors", false, "Do not check OpenGL errors at each call (may increase FPS)")
  102. app.cpuProfile = flag.String("cpuprofile", "", "Activate cpu profiling writing profile to the specified file")
  103. app.execTrace = flag.String("exectrace", "", "Activate execution tracer writing data to the specified file")
  104. }
  105. flag.Parse()
  106. // Creates application logger
  107. app.log = logger.New(ops.LogPrefix, nil)
  108. app.log.AddWriter(logger.NewConsole(false))
  109. app.log.SetFormat(logger.FTIME | logger.FMICROS)
  110. app.log.SetLevel(ops.LogLevel)
  111. // Window event handling must run on the main OS thread
  112. runtime.LockOSThread()
  113. // Get the window manager
  114. wmgr, err := window.Manager("glfw")
  115. if err != nil {
  116. return nil, err
  117. }
  118. app.wmgr = wmgr
  119. // Get the screen resolution
  120. swidth, sheight := app.wmgr.ScreenResolution(nil)
  121. var posx, posy int
  122. // If not full screen, sets the window size
  123. if !*app.fullScreen {
  124. if ops.Width != 0 {
  125. posx = (swidth - ops.Width) / 2
  126. if posx < 0 {
  127. posx = 0
  128. }
  129. swidth = ops.Width
  130. }
  131. if ops.Height != 0 {
  132. posy = (sheight - ops.Height) / 2
  133. if posy < 0 {
  134. posy = 0
  135. }
  136. sheight = ops.Height
  137. }
  138. }
  139. // Creates window
  140. win, err := app.wmgr.CreateWindow(swidth, sheight, ops.Title, *app.fullScreen)
  141. if err != nil {
  142. return nil, err
  143. }
  144. win.SetPos(posx, posy)
  145. app.win = win
  146. // Create OpenGL state
  147. gl, err := gls.New()
  148. if err != nil {
  149. return nil, err
  150. }
  151. app.gl = gl
  152. // Checks OpenGL errors
  153. app.gl.SetCheckErrors(!*app.noglErrors)
  154. // Logs OpenGL version
  155. glVersion := app.Gl().GetString(gls.VERSION)
  156. app.log.Info("OpenGL version: %s", glVersion)
  157. // Clears the screen
  158. cc := math32.NewColor("gray")
  159. app.gl.ClearColor(cc.R, cc.G, cc.B, 1)
  160. app.gl.Clear(gls.DEPTH_BUFFER_BIT | gls.STENCIL_BUFFER_BIT | gls.COLOR_BUFFER_BIT)
  161. // Creates KeyState
  162. app.keyState = NewKeyState(win)
  163. // Creates perspective camera
  164. width, height := app.win.Size()
  165. aspect := float32(width) / float32(height)
  166. app.camPersp = camera.NewPerspective(65, aspect, 0.01, 1000)
  167. // Creates orthographic camera
  168. app.camOrtho = camera.NewOrthographic(-2, 2, 2, -2, 0.01, 100)
  169. app.camOrtho.SetPosition(0, 0, 3)
  170. app.camOrtho.LookAt(&math32.Vector3{0, 0, 0})
  171. app.camOrtho.SetZoom(1.0)
  172. // Default camera is perspective
  173. app.camera = app.camPersp
  174. // Creates orbit camera control
  175. // It is important to do this after the root panel subscription
  176. // to avoid GUI events being propagated to the orbit control.
  177. app.orbit = control.NewOrbitControl(app.camera, app.win)
  178. // Creates scene for 3D objects
  179. app.scene = core.NewNode()
  180. // Creates gui root panel
  181. app.guiroot = gui.NewRoot(app.gl, app.win)
  182. app.guiroot.SetColor(math32.NewColor("silver"))
  183. // Creates renderer
  184. app.renderer = renderer.NewRenderer(gl)
  185. err = app.renderer.AddDefaultShaders()
  186. if err != nil {
  187. return nil, fmt.Errorf("Error from AddDefaulShaders:%v", err)
  188. }
  189. app.renderer.SetScene(app.scene)
  190. app.renderer.SetGui(app.guiroot)
  191. // Create frame rater
  192. app.frameRater = NewFrameRater(*app.targetFPS)
  193. // Sets the default window resize event handler
  194. app.win.SubscribeID(window.OnWindowSize, app, func(evname string, ev interface{}) {
  195. app.OnWindowResize()
  196. })
  197. app.OnWindowResize()
  198. return app, nil
  199. }
  200. // Get returns the application single instance or nil
  201. // if the application was not created yet
  202. func Get() *Application {
  203. return appInstance
  204. }
  205. // Log returns the application logger
  206. func (app *Application) Log() *logger.Logger {
  207. return app.log
  208. }
  209. // Window returns the application window
  210. func (app *Application) Window() window.IWindow {
  211. return app.win
  212. }
  213. // KeyState returns the application KeyState
  214. func (app *Application) KeyState() *KeyState {
  215. return app.keyState
  216. }
  217. // Gl returns the OpenGL state
  218. func (app *Application) Gl() *gls.GLS {
  219. return app.gl
  220. }
  221. // Gui returns the current application Gui root panel
  222. func (app *Application) Gui() *gui.Root {
  223. return app.guiroot
  224. }
  225. // Scene returns the current application 3D scene
  226. func (app *Application) Scene() *core.Node {
  227. return app.scene
  228. }
  229. // SetScene sets the 3D scene to be rendered
  230. func (app *Application) SetScene(scene *core.Node) {
  231. app.renderer.SetScene(scene)
  232. }
  233. // SetGui sets the root panel of the gui to be rendered
  234. func (app *Application) SetGui(root *gui.Root) {
  235. app.guiroot = root
  236. app.renderer.SetGui(app.guiroot)
  237. }
  238. // SetPanel3D sets the gui panel inside which the 3D scene is shown.
  239. func (app *Application) SetPanel3D(panel3D gui.IPanel) {
  240. app.renderer.SetGuiPanel3D(panel3D)
  241. }
  242. // Panel3D returns the current gui panel where the 3D scene is shown.
  243. func (app *Application) Panel3D() gui.IPanel {
  244. return app.renderer.Panel3D()
  245. }
  246. // CameraPersp returns the application perspective camera
  247. func (app *Application) CameraPersp() *camera.Perspective {
  248. return app.camPersp
  249. }
  250. // CameraOrtho returns the application orthographic camera
  251. func (app *Application) CameraOrtho() *camera.Orthographic {
  252. return app.camOrtho
  253. }
  254. // Camera returns the current application camera
  255. func (app *Application) Camera() camera.ICamera {
  256. return app.camera
  257. }
  258. // SetCamera sets the current application camera
  259. func (app *Application) SetCamera(cam camera.ICamera) {
  260. app.camera = cam
  261. }
  262. // Orbit returns the current camera orbit control
  263. func (app *Application) Orbit() *control.OrbitControl {
  264. return app.orbit
  265. }
  266. // SetOrbit sets the camera orbit control
  267. func (app *Application) SetOrbit(oc *control.OrbitControl) {
  268. app.orbit = oc
  269. }
  270. // FrameRater returns the FrameRater object
  271. func (app *Application) FrameRater() *FrameRater {
  272. return app.frameRater
  273. }
  274. // FrameCount returns the total number of frames since the call to Run()
  275. func (app *Application) FrameCount() uint64 {
  276. return app.frameCount
  277. }
  278. // FrameDelta returns the duration of the previous frame
  279. func (app *Application) FrameDelta() time.Duration {
  280. return app.frameDelta
  281. }
  282. // FrameDeltaSeconds returns the duration of the previous frame
  283. // in float32 seconds
  284. func (app *Application) FrameDeltaSeconds() float32 {
  285. return float32(app.frameDelta.Seconds())
  286. }
  287. // RunTime returns the duration since the call to Run()
  288. func (app *Application) RunTime() time.Duration {
  289. return time.Now().Sub(app.startTime)
  290. }
  291. // RunSeconds returns the elapsed time in seconds since the call to Run()
  292. func (app *Application) RunSeconds() float32 {
  293. return float32(time.Now().Sub(app.startTime).Seconds())
  294. }
  295. // Renderer returns the application renderer
  296. func (app *Application) Renderer() *renderer.Renderer {
  297. return app.renderer
  298. }
  299. // SetCPUProfile must be called before Run() and sets the file name for cpu profiling.
  300. // If set the cpu profiling starts before running the render loop and continues
  301. // till the end of the application.
  302. func (app *Application) SetCPUProfile(fname string) {
  303. *app.cpuProfile = fname
  304. }
  305. // SetOnWindowResize replaces the default window resize handler with the specified one
  306. func (app *Application) SetOnWindowResize(f func(evname string, ev interface{})) {
  307. app.win.UnsubscribeID(window.OnWindowSize, app)
  308. app.win.SubscribeID(window.OnWindowSize, app, f)
  309. }
  310. // Run runs the application render loop
  311. func (app *Application) Run() error {
  312. // Set swap interval
  313. if *app.swapInterval >= 0 {
  314. app.wmgr.SetSwapInterval(*app.swapInterval)
  315. app.log.Debug("Swap interval set to: %v", *app.swapInterval)
  316. }
  317. // Start profiling if requested
  318. if *app.cpuProfile != "" {
  319. f, err := os.Create(*app.cpuProfile)
  320. if err != nil {
  321. return err
  322. }
  323. defer f.Close()
  324. err = pprof.StartCPUProfile(f)
  325. if err != nil {
  326. return err
  327. }
  328. defer pprof.StopCPUProfile()
  329. app.log.Info("Started writing CPU profile to: %s", *app.cpuProfile)
  330. }
  331. // Start execution trace if requested
  332. if *app.execTrace != "" {
  333. f, err := os.Create(*app.execTrace)
  334. if err != nil {
  335. return err
  336. }
  337. defer f.Close()
  338. err = trace.Start(f)
  339. if err != nil {
  340. return err
  341. }
  342. defer trace.Stop()
  343. app.log.Info("Started writing execution trace to: %s", *app.execTrace)
  344. }
  345. app.startTime = time.Now()
  346. app.frameTime = time.Now()
  347. // Render loop
  348. for true {
  349. // If was requested to terminate the application by trying to close the window
  350. // or by calling Quit(), dispatch OnQuit event for subscribers.
  351. // If no subscriber cancelled the event, terminates the application.
  352. if app.win.ShouldClose() {
  353. canceled := app.Dispatch(OnQuit, nil)
  354. if canceled {
  355. app.win.SetShouldClose(false)
  356. } else {
  357. break
  358. }
  359. }
  360. // Starts measuring this frame
  361. app.frameRater.Start()
  362. // Updates frame start and time delta in context
  363. now := time.Now()
  364. app.frameDelta = now.Sub(app.frameTime)
  365. app.frameTime = now
  366. // Process root panel timers
  367. if app.Gui() != nil {
  368. app.Gui().TimerManager.ProcessTimers()
  369. }
  370. // Process application timers
  371. app.ProcessTimers()
  372. // Dispatch before render event
  373. app.Dispatch(OnBeforeRender, nil)
  374. // Renders the current scene and/or gui
  375. rendered, err := app.renderer.Render(app.camera)
  376. if err != nil {
  377. return err
  378. }
  379. // Poll input events and process them
  380. app.wmgr.PollEvents()
  381. if rendered {
  382. app.win.SwapBuffers()
  383. }
  384. // Dispatch after render event
  385. app.Dispatch(OnAfterRender, nil)
  386. // Controls the frame rate
  387. app.frameRater.Wait()
  388. app.frameCount++
  389. }
  390. // Dispose resources
  391. if app.scene != nil {
  392. app.scene.DisposeChildren(true)
  393. }
  394. if app.guiroot != nil {
  395. app.guiroot.DisposeChildren(true)
  396. }
  397. // Close default audio device
  398. if app.audioDev != nil {
  399. al.CloseDevice(app.audioDev)
  400. }
  401. // Terminates window manager
  402. app.wmgr.Terminate()
  403. // This is important when using the execution tracer
  404. runtime.UnlockOSThread()
  405. return nil
  406. }
  407. // OpenDefaultAudioDevice opens the default audio device setting it to the current context
  408. func (app *Application) OpenDefaultAudioDevice() error {
  409. // Opens default audio device
  410. var err error
  411. app.audioDev, err = al.OpenDevice("")
  412. if err != nil {
  413. return fmt.Errorf("Error: %s opening OpenAL default device", err)
  414. }
  415. // Checks for OpenAL effects extension support
  416. audioEFX := false
  417. if al.IsExtensionPresent("ALC_EXT_EFX") {
  418. audioEFX = true
  419. }
  420. // Creates audio context with auxiliary sends
  421. var attribs []int
  422. if audioEFX {
  423. attribs = []int{al.MAX_AUXILIARY_SENDS, 4}
  424. }
  425. acx, err := al.CreateContext(app.audioDev, attribs)
  426. if err != nil {
  427. return fmt.Errorf("Error creating OpenAL context:%s", err)
  428. }
  429. // Makes the context the current one
  430. err = al.MakeContextCurrent(acx)
  431. if err != nil {
  432. return fmt.Errorf("Error setting OpenAL context current:%s", err)
  433. }
  434. // Logs audio library versions
  435. app.log.Info("%s version: %s", al.GetString(al.Vendor), al.GetString(al.Version))
  436. app.log.Info("%s", vorbis.VersionString())
  437. return nil
  438. }
  439. // Quit requests to terminate the application
  440. // Application will dispatch OnQuit events to registered subscriber which
  441. // can cancel the process by calling CancelDispatch().
  442. func (app *Application) Quit() {
  443. app.win.SetShouldClose(true)
  444. }
  445. // OnWindowResize is default handler for window resize events.
  446. func (app *Application) OnWindowResize() {
  447. // Get framebuffer size and sets the viewport accordingly
  448. width, height := app.win.FramebufferSize()
  449. app.gl.Viewport(0, 0, int32(width), int32(height))
  450. // Sets perspective camera aspect ratio
  451. aspect := float32(width) / float32(height)
  452. app.Camera().SetAspect(aspect)
  453. // Sets the GUI root panel size to the size of the framebuffer
  454. if app.guiroot != nil {
  455. app.guiroot.SetSize(float32(width), float32(height))
  456. }
  457. }