renderer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. // Copyright 2016 The G3N Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package renderer
  5. import (
  6. "github.com/g3n/engine/camera"
  7. "github.com/g3n/engine/core"
  8. "github.com/g3n/engine/gls"
  9. "github.com/g3n/engine/graphic"
  10. "github.com/g3n/engine/gui"
  11. "github.com/g3n/engine/light"
  12. )
  13. // Renderer renders a 3D scene and/or a 2D GUI on the current window.
  14. type Renderer struct {
  15. gs *gls.GLS
  16. shaman Shaman // Internal shader manager
  17. stats Stats // Renderer statistics
  18. prevStats Stats // Renderer statistics for previous frame
  19. scene core.INode // Node containing 3D scene to render
  20. panelGui gui.IPanel // Panel containing GUI to render
  21. panel3D gui.IPanel // Panel which contains the 3D scene
  22. ambLights []*light.Ambient // Array of ambient lights for last scene
  23. dirLights []*light.Directional // Array of directional lights for last scene
  24. pointLights []*light.Point // Array of point
  25. spotLights []*light.Spot // Array of spot lights for the scene
  26. others []core.INode // Other nodes (audio, players, etc)
  27. grmats []*graphic.GraphicMaterial // Array of all graphic materials for scene
  28. rinfo core.RenderInfo // Preallocated Render info
  29. specs ShaderSpecs // Preallocated Shader specs
  30. redrawGui bool // Flag indicating the gui must be redrawn completely
  31. rendered bool // Flag indicating if anything was rendered
  32. panList []gui.IPanel // list of panels to render
  33. frameBuffers int // Number of frame buffers
  34. frameCount int // Current number of frame buffers to write
  35. }
  36. // Stats describes how many object types were rendered
  37. // It is cleared at the start of each render
  38. type Stats struct {
  39. Graphics int // Number of graphic objects rendered
  40. Lights int // Number of lights rendered
  41. Panels int // Number of Gui panels rendered
  42. Others int // Number of other objects rendered
  43. }
  44. // NewRenderer creates and returns a pointer to a new Renderer
  45. func NewRenderer(gs *gls.GLS) *Renderer {
  46. r := new(Renderer)
  47. r.gs = gs
  48. r.shaman.Init(gs)
  49. r.ambLights = make([]*light.Ambient, 0)
  50. r.dirLights = make([]*light.Directional, 0)
  51. r.pointLights = make([]*light.Point, 0)
  52. r.spotLights = make([]*light.Spot, 0)
  53. r.others = make([]core.INode, 0)
  54. r.grmats = make([]*graphic.GraphicMaterial, 0)
  55. r.panList = make([]gui.IPanel, 0)
  56. r.frameBuffers = 2
  57. return r
  58. }
  59. // AddDefaultShaders adds to this renderer's shader manager all default
  60. // include chunks, shaders and programs statically registered.
  61. func (r *Renderer) AddDefaultShaders() error {
  62. return r.shaman.AddDefaultShaders()
  63. }
  64. // AddChunk adds a shader chunk with the specified name and source code
  65. func (r *Renderer) AddChunk(name, source string) {
  66. r.shaman.AddChunk(name, source)
  67. }
  68. // AddShader adds a shader program with the specified name and source code
  69. func (r *Renderer) AddShader(name, source string) {
  70. r.shaman.AddShader(name, source)
  71. }
  72. // AddProgram adds a program with the specified name and associated vertex
  73. // and fragment shaders names (previously registered)
  74. func (r *Renderer) AddProgram(name, vertex, frag string, others ...string) {
  75. r.shaman.AddProgram(name, vertex, frag, others...)
  76. }
  77. // SetGui sets the gui panel which contains the Gui to render.
  78. // If set to nil, no Gui will be rendered
  79. func (r *Renderer) SetGui(gui gui.IPanel) {
  80. r.panelGui = gui
  81. }
  82. // SetGuiPanel3D sets the gui panel inside which the 3D scene is shown.
  83. // This informs the renderer that the Gui elements over this panel
  84. // must be redrawn even if they didn't change.
  85. // This panel panel must not be renderable, otherwise it will cover the 3D scene.
  86. func (r *Renderer) SetGuiPanel3D(panel3D gui.IPanel) {
  87. r.panel3D = panel3D
  88. }
  89. // Panel3D returns the current gui panel over the 3D scene
  90. func (r *Renderer) Panel3D() gui.IPanel {
  91. return r.panel3D
  92. }
  93. // SetScene sets the 3D scene to render
  94. // If set to nil, no 3D scene will be rendered
  95. func (r *Renderer) SetScene(scene core.INode) {
  96. r.scene = scene
  97. }
  98. // Returns statistics
  99. func (r *Renderer) Stats() Stats {
  100. return r.stats
  101. }
  102. // Render renders the previously set Scene and Gui using the specified camera
  103. // Returns an indication if anything was rendered and an error
  104. func (r *Renderer) Render(icam camera.ICamera) (bool, error) {
  105. r.redrawGui = false
  106. r.rendered = false
  107. r.stats = Stats{}
  108. // Renders the 3D scene
  109. if r.scene != nil {
  110. err := r.renderScene(r.scene, icam)
  111. if err != nil {
  112. return r.rendered, err
  113. }
  114. }
  115. // Renders the Gui over the 3D scene
  116. if r.panelGui != nil {
  117. err := r.renderGui()
  118. if err != nil {
  119. return r.rendered, err
  120. }
  121. }
  122. return r.rendered, nil
  123. }
  124. // renderScene renders the 3D scene using the specified camera
  125. func (r *Renderer) renderScene(iscene core.INode, icam camera.ICamera) error {
  126. // Updates world matrices of all scene nodes
  127. iscene.UpdateMatrixWorld()
  128. scene := iscene.GetNode()
  129. // Builds RenderInfo calls RenderSetup for all visible nodes
  130. icam.ViewMatrix(&r.rinfo.ViewMatrix)
  131. icam.ProjMatrix(&r.rinfo.ProjMatrix)
  132. // Clear scene arrays
  133. r.ambLights = r.ambLights[0:0]
  134. r.dirLights = r.dirLights[0:0]
  135. r.pointLights = r.pointLights[0:0]
  136. r.spotLights = r.spotLights[0:0]
  137. r.others = r.others[0:0]
  138. r.grmats = r.grmats[0:0]
  139. // Internal function to classify a node and its children
  140. var classifyNode func(inode core.INode)
  141. classifyNode = func(inode core.INode) {
  142. // If node not visible, ignore
  143. node := inode.GetNode()
  144. if !node.Visible() {
  145. return
  146. }
  147. // Checks if node is a Graphic
  148. igr, ok := inode.(graphic.IGraphic)
  149. if ok {
  150. if igr.Renderable() {
  151. // Appends to list each graphic material for this graphic
  152. gr := igr.GetGraphic()
  153. materials := gr.Materials()
  154. for i := 0; i < len(materials); i++ {
  155. r.grmats = append(r.grmats, &materials[i])
  156. }
  157. }
  158. // Node is not a Graphic
  159. } else {
  160. // Checks if node is a Light
  161. il, ok := inode.(light.ILight)
  162. if ok {
  163. switch l := il.(type) {
  164. case *light.Ambient:
  165. r.ambLights = append(r.ambLights, l)
  166. case *light.Directional:
  167. r.dirLights = append(r.dirLights, l)
  168. case *light.Point:
  169. r.pointLights = append(r.pointLights, l)
  170. case *light.Spot:
  171. r.spotLights = append(r.spotLights, l)
  172. default:
  173. panic("Invalid light type")
  174. }
  175. // Other nodes
  176. } else {
  177. r.others = append(r.others, inode)
  178. }
  179. }
  180. // Classify node children
  181. for _, ichild := range node.Children() {
  182. classifyNode(ichild)
  183. }
  184. }
  185. // Classify all scene nodes
  186. classifyNode(scene)
  187. // Sets lights count in shader specs
  188. r.specs.AmbientLightsMax = len(r.ambLights)
  189. r.specs.DirLightsMax = len(r.dirLights)
  190. r.specs.PointLightsMax = len(r.pointLights)
  191. r.specs.SpotLightsMax = len(r.spotLights)
  192. // Render other nodes (audio players, etc)
  193. for i := 0; i < len(r.others); i++ {
  194. inode := r.others[i]
  195. if !inode.GetNode().Visible() {
  196. continue
  197. }
  198. r.others[i].Render(r.gs)
  199. r.stats.Others++
  200. }
  201. // If there is graphic material to render or there was in the previous frame
  202. // it is necessary to clear the screen.
  203. if len(r.grmats) > 0 || r.prevStats.Graphics > 0 {
  204. // If the 3D scene to draw is to be confined to user specified panel
  205. // sets scissor to avoid erasing gui elements outside of this panel
  206. if r.panel3D != nil {
  207. pos := r.panel3D.GetPanel().Pospix()
  208. width, height := r.panel3D.GetPanel().Size()
  209. _, _, _, viewheight := r.gs.GetViewport()
  210. r.gs.Enable(gls.SCISSOR_TEST)
  211. r.gs.Scissor(int32(pos.X), viewheight-int32(pos.Y)-int32(height), uint32(width), uint32(height))
  212. } else {
  213. r.gs.Disable(gls.SCISSOR_TEST)
  214. r.redrawGui = true
  215. }
  216. // Clears the area inside the current scissor
  217. r.gs.Clear(gls.DEPTH_BUFFER_BIT | gls.STENCIL_BUFFER_BIT | gls.COLOR_BUFFER_BIT)
  218. r.rendered = true
  219. }
  220. // For each *GraphicMaterial
  221. for _, grmat := range r.grmats {
  222. mat := grmat.GetMaterial().GetMaterial()
  223. // Sets the shader specs for this material and sets shader program
  224. r.specs.Name = mat.Shader()
  225. r.specs.ShaderUnique = mat.ShaderUnique()
  226. r.specs.UseLights = mat.UseLights()
  227. r.specs.MatTexturesMax = mat.TextureCount()
  228. _, err := r.shaman.SetProgram(&r.specs)
  229. if err != nil {
  230. return err
  231. }
  232. // Setup lights (transfer lights uniforms)
  233. for idx, l := range r.ambLights {
  234. l.RenderSetup(r.gs, &r.rinfo, idx)
  235. r.stats.Lights++
  236. }
  237. for idx, l := range r.dirLights {
  238. l.RenderSetup(r.gs, &r.rinfo, idx)
  239. r.stats.Lights++
  240. }
  241. for idx, l := range r.pointLights {
  242. l.RenderSetup(r.gs, &r.rinfo, idx)
  243. r.stats.Lights++
  244. }
  245. for idx, l := range r.spotLights {
  246. l.RenderSetup(r.gs, &r.rinfo, idx)
  247. r.stats.Lights++
  248. }
  249. // Render this graphic material
  250. grmat.Render(r.gs, &r.rinfo)
  251. r.stats.Graphics++
  252. }
  253. r.prevStats = r.stats
  254. return nil
  255. }
  256. // renderGui renders the Gui
  257. func (r *Renderer) renderGui() error {
  258. // If no 3D scene was rendered sets Gui panels as renderable for background
  259. // User must define the colors
  260. if len(r.grmats) == 0 {
  261. r.panelGui.SetRenderable(true)
  262. if r.panel3D != nil {
  263. r.panel3D.SetRenderable(true)
  264. }
  265. } else {
  266. r.panelGui.SetRenderable(false)
  267. if r.panel3D != nil {
  268. r.panel3D.SetRenderable(false)
  269. }
  270. }
  271. // Clears list of panels to render
  272. r.panList = r.panList[0:0]
  273. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  274. if r.redrawGui {
  275. r.appendPanel(r.panelGui)
  276. // Redraw GUI elements only if changed
  277. // Set the number of frame buffers to draw these changes
  278. } else if r.checkChanged(r.panelGui) {
  279. r.appendPanel(r.panelGui)
  280. r.frameCount = r.frameBuffers
  281. // No change, but need to update frame buffers
  282. } else if r.frameCount > 0 {
  283. r.appendPanel(r.panelGui)
  284. // No change, draw only panels over 3D if any
  285. } else {
  286. r.getPanelsOver3D()
  287. }
  288. if len(r.panList) == 0 {
  289. return nil
  290. }
  291. // Updates panels bounds and relative positions
  292. r.panelGui.GetPanel().UpdateMatrixWorld()
  293. // Disable the scissor test which could have been set by the 3D scene renderer
  294. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  295. r.gs.Disable(gls.SCISSOR_TEST)
  296. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  297. // Render panels
  298. for i := 0; i < len(r.panList); i++ {
  299. err := r.renderPanel(r.panList[i])
  300. if err != nil {
  301. return err
  302. }
  303. }
  304. r.frameCount--
  305. r.rendered = true
  306. return nil
  307. }
  308. // getPanelsOver3D builds list of panels over 3D to be rendered
  309. func (r *Renderer) getPanelsOver3D() {
  310. // If panel3D not set or renderable, nothing to do
  311. if r.panel3D == nil || r.panel3D.Renderable() {
  312. return
  313. }
  314. // Internal recursive function to check if any child of the
  315. // specified panel is unbounded and over 3D.
  316. // If it is, it is inserted in the list of panels to render.
  317. var checkUnbounded func(pan *gui.Panel)
  318. checkUnbounded = func(pan *gui.Panel) {
  319. for i := 0; i < len(pan.Children()); i++ {
  320. child := pan.Children()[i].(gui.IPanel).GetPanel()
  321. if !child.Bounded() && r.checkPanelOver3D(child) {
  322. r.appendPanel(child)
  323. continue
  324. }
  325. checkUnbounded(child)
  326. }
  327. }
  328. // For all children of the Gui, checks if it is over the 3D panel
  329. children := r.panelGui.GetPanel().Children()
  330. for i := 0; i < len(children); i++ {
  331. pan := children[i].(gui.IPanel).GetPanel()
  332. if !pan.Visible() {
  333. continue
  334. }
  335. if r.checkPanelOver3D(pan) {
  336. r.appendPanel(pan)
  337. continue
  338. }
  339. // Current child is not over 3D but can have an unbounded child which is
  340. checkUnbounded(pan)
  341. }
  342. }
  343. // renderPanel renders the specified panel and all its children
  344. // and then sets the panel as not changed.
  345. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  346. // If panel not visible, ignore it and all its children
  347. pan := ipan.GetPanel()
  348. if !pan.Visible() {
  349. pan.SetChanged(false)
  350. return nil
  351. }
  352. // If panel is renderable, renders it
  353. if pan.Renderable() {
  354. // Sets shader program for the panel's material
  355. grmat := pan.GetGraphic().Materials()[0]
  356. mat := grmat.GetMaterial().GetMaterial()
  357. r.specs.Name = mat.Shader()
  358. r.specs.ShaderUnique = mat.ShaderUnique()
  359. _, err := r.shaman.SetProgram(&r.specs)
  360. if err != nil {
  361. return err
  362. }
  363. // Render this panel's graphic material
  364. grmat.Render(r.gs, &r.rinfo)
  365. r.stats.Panels++
  366. }
  367. pan.SetChanged(false)
  368. // Renders this panel children
  369. for i := 0; i < len(pan.Children()); i++ {
  370. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  371. if err != nil {
  372. return err
  373. }
  374. }
  375. return nil
  376. }
  377. // appendPanel appends the specified panel to the list of panels to render.
  378. // Currently there is no need to check for duplicates.
  379. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  380. r.panList = append(r.panList, ipan)
  381. }
  382. // checkChanged checks if the specified panel or any of its children is changed
  383. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  384. // Unbounded panels are checked even if not visible
  385. pan := ipan.GetPanel()
  386. if !pan.Bounded() && pan.Changed() {
  387. pan.SetChanged(false)
  388. return true
  389. }
  390. // Ignore invisible panel and its children
  391. if !pan.Visible() {
  392. return false
  393. }
  394. if pan.Changed() && pan.Renderable() {
  395. return true
  396. }
  397. for i := 0; i < len(pan.Children()); i++ {
  398. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  399. if res {
  400. return res
  401. }
  402. }
  403. return false
  404. }
  405. // checkPanelOver3D checks if the specified panel is over
  406. // the area where the 3D scene will be rendered.
  407. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  408. pan := ipan.GetPanel()
  409. if !pan.Visible() {
  410. return false
  411. }
  412. if r.panel3D.GetPanel().Intersects(pan) {
  413. return true
  414. }
  415. return false
  416. }