renderer.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. geom := grmat.GetGraphic().GetGeometry()
  306. // Add defines from material and geometry
  307. r.specs.Defines = *gls.NewShaderDefines()
  308. r.specs.Defines.Add(&mat.ShaderDefines)
  309. r.specs.Defines.Add(&geom.ShaderDefines)
  310. // Sets the shader specs for this material and sets shader program
  311. r.specs.Name = mat.Shader()
  312. r.specs.ShaderUnique = mat.ShaderUnique()
  313. r.specs.UseLights = mat.UseLights()
  314. r.specs.MatTexturesMax = mat.TextureCount()
  315. // Set active program and apply shader specs
  316. _, err = r.shaman.SetProgram(&r.specs)
  317. if err != nil {
  318. return
  319. }
  320. // Setup lights (transfer lights' uniforms)
  321. for idx, l := range r.ambLights {
  322. l.RenderSetup(r.gs, &r.rinfo, idx)
  323. r.stats.Lights++
  324. }
  325. for idx, l := range r.dirLights {
  326. l.RenderSetup(r.gs, &r.rinfo, idx)
  327. r.stats.Lights++
  328. }
  329. for idx, l := range r.pointLights {
  330. l.RenderSetup(r.gs, &r.rinfo, idx)
  331. r.stats.Lights++
  332. }
  333. for idx, l := range r.spotLights {
  334. l.RenderSetup(r.gs, &r.rinfo, idx)
  335. r.stats.Lights++
  336. }
  337. // Render this graphic material
  338. grmat.Render(r.gs, &r.rinfo)
  339. r.stats.Graphics++
  340. }
  341. }
  342. renderGraphicMaterials(r.grmatsOpaque) // Render opaque objects (front to back)
  343. renderGraphicMaterials(r.grmatsTransp) // Render transparent objects (back to front)
  344. return err
  345. }
  346. // renderGui renders the Gui
  347. func (r *Renderer) renderGui() error {
  348. // If no 3D scene was rendered sets Gui panels as renderable for background
  349. // User must define the colors
  350. if (len(r.rgraphics) == 0) && (len(r.cgraphics) == 0) {
  351. r.panelGui.SetRenderable(true)
  352. if r.panel3D != nil {
  353. r.panel3D.SetRenderable(true)
  354. }
  355. } else {
  356. r.panelGui.SetRenderable(false)
  357. if r.panel3D != nil {
  358. r.panel3D.SetRenderable(false)
  359. }
  360. }
  361. // Clears list of panels to render
  362. r.panList = r.panList[0:0]
  363. // Redraw all GUI elements elements (panel3D == nil and 3D scene drawn)
  364. if r.redrawGui {
  365. r.appendPanel(r.panelGui)
  366. // Redraw GUI elements only if changed
  367. // Set the number of frame buffers to draw these changes
  368. } else if r.checkChanged(r.panelGui) {
  369. r.appendPanel(r.panelGui)
  370. r.frameCount = r.frameBuffers
  371. // No change, but need to update frame buffers
  372. } else if r.frameCount > 0 {
  373. r.appendPanel(r.panelGui)
  374. // No change, draw only panels over 3D if any
  375. } else {
  376. r.getPanelsOver3D()
  377. }
  378. if len(r.panList) == 0 {
  379. return nil
  380. }
  381. // Updates panels bounds and relative positions
  382. r.panelGui.GetPanel().UpdateMatrixWorld()
  383. // Disable the scissor test which could have been set by the 3D scene renderer
  384. // and then clear the depth buffer, so the panels will be rendered over the 3D scene.
  385. r.gs.Disable(gls.SCISSOR_TEST)
  386. r.gs.Clear(gls.DEPTH_BUFFER_BIT)
  387. // Render panels
  388. for i := 0; i < len(r.panList); i++ {
  389. err := r.renderPanel(r.panList[i])
  390. if err != nil {
  391. return err
  392. }
  393. }
  394. r.frameCount--
  395. r.rendered = true
  396. return nil
  397. }
  398. // getPanelsOver3D builds list of panels over 3D to be rendered
  399. func (r *Renderer) getPanelsOver3D() {
  400. // If panel3D not set or renderable, nothing to do
  401. if r.panel3D == nil || r.panel3D.Renderable() {
  402. return
  403. }
  404. // Internal recursive function to check if any child of the
  405. // specified panel is unbounded and over 3D.
  406. // If it is, it is inserted in the list of panels to render.
  407. var checkUnbounded func(pan *gui.Panel)
  408. checkUnbounded = func(pan *gui.Panel) {
  409. for i := 0; i < len(pan.Children()); i++ {
  410. child := pan.Children()[i].(gui.IPanel).GetPanel()
  411. if !child.Bounded() && r.checkPanelOver3D(child) {
  412. r.appendPanel(child)
  413. continue
  414. }
  415. checkUnbounded(child)
  416. }
  417. }
  418. // For all children of the Gui, checks if it is over the 3D panel
  419. children := r.panelGui.GetPanel().Children()
  420. for i := 0; i < len(children); i++ {
  421. pan := children[i].(gui.IPanel).GetPanel()
  422. if !pan.Visible() {
  423. continue
  424. }
  425. if r.checkPanelOver3D(pan) {
  426. r.appendPanel(pan)
  427. continue
  428. }
  429. // Current child is not over 3D but can have an unbounded child which is
  430. checkUnbounded(pan)
  431. }
  432. }
  433. // renderPanel renders the specified panel and all its children
  434. // and then sets the panel as not changed.
  435. func (r *Renderer) renderPanel(ipan gui.IPanel) error {
  436. // If panel not visible, ignore it and all its children
  437. pan := ipan.GetPanel()
  438. if !pan.Visible() {
  439. pan.SetChanged(false)
  440. return nil
  441. }
  442. // If panel is renderable, renders it
  443. if pan.Renderable() {
  444. // Sets shader program for the panel's material
  445. grmat := pan.GetGraphic().Materials()[0]
  446. mat := grmat.GetMaterial().GetMaterial()
  447. r.specs.Name = mat.Shader()
  448. r.specs.ShaderUnique = mat.ShaderUnique()
  449. _, err := r.shaman.SetProgram(&r.specs)
  450. if err != nil {
  451. return err
  452. }
  453. // Render this panel's graphic material
  454. grmat.Render(r.gs, &r.rinfo)
  455. r.stats.Panels++
  456. }
  457. pan.SetChanged(false)
  458. // Renders this panel children
  459. for i := 0; i < len(pan.Children()); i++ {
  460. err := r.renderPanel(pan.Children()[i].(gui.IPanel))
  461. if err != nil {
  462. return err
  463. }
  464. }
  465. return nil
  466. }
  467. // appendPanel appends the specified panel to the list of panels to render.
  468. // Currently there is no need to check for duplicates.
  469. func (r *Renderer) appendPanel(ipan gui.IPanel) {
  470. r.panList = append(r.panList, ipan)
  471. }
  472. // checkChanged checks if the specified panel or any of its children is changed
  473. func (r *Renderer) checkChanged(ipan gui.IPanel) bool {
  474. // Unbounded panels are checked even if not visible
  475. pan := ipan.GetPanel()
  476. if !pan.Bounded() && pan.Changed() {
  477. pan.SetChanged(false)
  478. return true
  479. }
  480. // Ignore invisible panel and its children
  481. if !pan.Visible() {
  482. return false
  483. }
  484. if pan.Changed() && pan.Renderable() {
  485. return true
  486. }
  487. for i := 0; i < len(pan.Children()); i++ {
  488. res := r.checkChanged(pan.Children()[i].(gui.IPanel))
  489. if res {
  490. return res
  491. }
  492. }
  493. return false
  494. }
  495. // checkPanelOver3D checks if the specified panel is over
  496. // the area where the 3D scene will be rendered.
  497. func (r *Renderer) checkPanelOver3D(ipan gui.IPanel) bool {
  498. pan := ipan.GetPanel()
  499. if !pan.Visible() {
  500. return false
  501. }
  502. if r.panel3D.GetPanel().Intersects(pan) {
  503. return true
  504. }
  505. return false
  506. }