renderer.go 17 KB

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