renderer.go 16 KB

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