renderer.go 18 KB

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